1;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="59a54a1a-7878-b360-da24-54d6d600bebc")}catch(e){}}(); 2(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([typeof document === "object" ? document.currentScript : undefined, 3653145, ((__turbopack_context__) => { 4"use strict"; 5 6var __TURBOPACK__imported__module__271645__ = __turbopack_context__.i(271645); 7; 8var isCheckBoxInput = (element)=>element.type === 'checkbox'; 9var isFileInput = (element)=>element.type === 'file'; 10var isDateObject = (value1)=>value1 instanceof Date; 11var isNullOrUndefined = (value1)=>value1 == null; 12const isObjectType = (value1)=>typeof value1 === 'object'; 13var isObject = (value1)=>!isNullOrUndefined(value1) && !Array.isArray(value1) && isObjectType(value1) && !isDateObject(value1); 14var getEventValue = (event)=>isObject(event) && event.target ? isCheckBoxInput(event.target) ? event.target.checked : isFileInput(event.target) ? event.target.files : event.target.value : event; 15const FIELD_PATH_RE = /[.[\]'"]/; 16var stringToPath = (input)=>input.split(FIELD_PATH_RE).filter(Boolean); 17function getNullAncestorValue(control, name) { 18 const segments = stringToPath(name); 19 let formValues = control._formValues; 20 let defaultValues = control._defaultValues; 21 for(let i = 0; i < segments.length - 1; i++){ 22 const key = segments[i]; 23 formValues = formValues == null ? formValues : formValues[key]; 24 defaultValues = defaultValues == null ? defaultValues : defaultValues[key]; 25 if (formValues === null || defaultValues === null) { 26 return null; 27 } 28 } 29 return undefined; 30} 31var isNameInFieldArray = (names, name)=>name.split('.').some((part, index, arr)=>!isNaN(Number(part)) && names.has(arr.slice(0, index).join('.'))); 32var isWeb = typeof window !== 'undefined' && typeof window.HTMLElement !== 'undefined' && typeof document !== 'undefined'; 33function cloneObject(data) { 34 if (data === null || typeof data !== 'object') { 35 return data; 36 } 37 if (data instanceof Date) { 38 return new Date(data); 39 } 40 const isBlobInstance = typeof Blob !== 'undefined' && data instanceof Blob; 41 const isFileListInstance = typeof FileList !== 'undefined' && data instanceof FileList; 42 if (isWeb && (isBlobInstance || isFileListInstance)) { 43 return data; 44 } 45 const isArray = Array.isArray(data); 46 if (!isArray && data.constructor !== Object) { 47 return data; 48 } 49 const copy = isArray ? [] : Object.create(Object.getPrototypeOf(data)); 50 for(const key in data){ 51 if (Object.prototype.hasOwnProperty.call(data, key)) { 52 copy[key] = cloneObject(data[key]); 53 } 54 } 55 return copy; 56} 57const EVENTS = { 58 BLUR: 'blur', 59 FOCUS_OUT: 'focusout', 60 CHANGE: 'change', 61 SUBMIT: 'submit', 62 TRIGGER: 'trigger', 63 VALID: 'valid' 64}; 65const VALIDATION_MODE = { 66 onBlur: 'onBlur', 67 onChange: 'onChange', 68 onSubmit: 'onSubmit', 69 onTouched: 'onTouched', 70 all: 'all' 71}; 72const INPUT_VALIDATION_RULES = { 73 max: 'max', 74 min: 'min', 75 maxLength: 'maxLength', 76 minLength: 'minLength', 77 pattern: 'pattern', 78 required: 'required', 79 validate: 'validate' 80}; 81const ROOT_ERROR_TYPE = 'root'; 82const PROTOTYPE_KEYWORDS = [ 83 '__proto__', 84 'constructor', 85 'prototype' 86]; 87const IS_KEY_RE = /^\w*$/; 88var isKey = (value1)=>IS_KEY_RE.test(value1); 89var isUndefined = (val)=>val === undefined; 90var get = (object, path, defaultValue)=>{ 91 if (!path || !isObject(object)) { 92 return defaultValue; 93 } 94 const paths = isKey(path) ? [ 95 path 96 ] : stringToPath(path); 97 if (paths.some((key)=>PROTOTYPE_KEYWORDS.includes(key))) { 98 return defaultValue; 99 } 100 const result = paths.reduce((result, key)=>{ 101 return isNullOrUndefined(result) ? undefined : result[key]; 102 }, object); 103 return isUndefined(result) || result === object ? isUndefined(object[path]) ? defaultValue : object[path] : result; 104}; 105var isBoolean = (value1)=>typeof value1 === 'boolean'; 106var isFunction = (value1)=>typeof value1 === 'function'; 107var set = (object, path, value1)=>{ 108 let index = -1; 109 const tempPath = isKey(path) ? [ 110 path 111 ] : stringToPath(path); 112 const length = tempPath.length; 113 const lastIndex = length - 1; 114 while(++index < length){
115 const key = tempPath[index]; 116 let newValue = value1; 117 if (index !== lastIndex) { 118 const objValue = object[key]; 119 newValue = isObject(objValue) || Array.isArray(objValue) ? objValue : !isNaN(+tempPath[index + 1]) ? [] : {}; 120 } 121 if (PROTOTYPE_KEYWORDS.includes(key)) { 122 return; 123 } 124 object[key] = newValue; 125 object = object[key]; 126 } 127}; 128/** 129 * Separate context for `control` to prevent unnecessary rerenders. 130 * Internal hooks that only need control use this instead of full form context. 131 */ const HookFormControlContext = __TURBOPACK__imported__module__271645__["default"].createContext(null); 132HookFormControlContext.displayName = 'HookFormControlContext'; 133/** 134 * @internal Internal hook to access only control from context. 135 */ const useFormControlContext = ()=>__TURBOPACK__imported__module__271645__["default"].useContext(HookFormControlContext); 136var getProxyFormState = function(formState, control, localProxyFormState) { 137 let isRoot = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : true; 138 const result = {}; 139 for(const key in formState){ 140 Object.defineProperty(result, key, { 141 get: ()=>{ 142 const _key = key; 143 if (control._proxyFormState[_key] !== VALIDATION_MODE.all) { 144 control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all; 145 } 146 localProxyFormState && (localProxyFormState[_key] = true); 147 return formState[_key]; 148 } 149 }); 150 } 151 return result; 152}; 153const useIsomorphicLayoutEffect = isWeb ? __TURBOPACK__imported__module__271645__["default"].useLayoutEffect : __TURBOPACK__imported__module__271645__["default"].useEffect; 154var isPlainObject = (tempObject)=>{ 155 const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype; 156 return isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'); 157}; 158var isPrimitive = (value1)=>isNullOrUndefined(value1) || !isObjectType(value1); 159const isEmptyObjectWithCustomPrototype = (object, keys)=>keys.length === 0 && !Array.isArray(object) && !isPlainObject(object); 160function deepEqual(object1, object2) { 161 let visited = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : new WeakMap(); 162 if (object1 === object2) { 163 return true; 164 } 165 if (isPrimitive(object1) || isPrimitive(object2)) { 166 return Object.is(object1, object2); 167 } 168 if (isDateObject(object1) && isDateObject(object2)) { 169 return Object.is(object1.getTime(), object2.getTime()); 170 } 171 const keys1 = Object.keys(object1); 172 const keys2 = Object.keys(object2); 173 if (keys1.length !== keys2.length) { 174 return false; 175 } 176 if (isEmptyObjectWithCustomPrototype(object1, keys1) || isEmptyObjectWithCustomPrototype(object2, keys2)) { 177 return Object.is(object1, object2); 178 } 179 if (!keys1.length && Array.isArray(object1) !== Array.isArray(object2)) { 180 return false; 181 } 182 const visitedPairs = visited.get(object1); 183 if (visitedPairs && visitedPairs.has(object2)) { 184 return true; 185 } 186 if (visitedPairs) { 187 visitedPairs.add(object2); 188 } else { 189 const ws = new WeakSet(); 190 ws.add(object2); 191 visited.set(object1, ws); 192 } 193 for (const key of keys1){ 194 const val1 = object1[key]; 195 if (!(key in object2)) { 196 return false; 197 } 198 if (key !== 'ref') { 199 const val2 = object2[key]; 200 if (isDateObject(val1) && isDateObject(val2) || (isObject(val1) || Array.isArray(val1)) && (isObject(val2) || Array.isArray(val2)) ? !deepEqual(val1, val2, visited) : !Object.is(val1, val2)) { 201 return false; 202 } 203 } 204 } 205 return true; 206} 207function useResyncOnReconnect(getInitialValue) { 208 const _connected = __TURBOPACK__imported__module__271645__["default"].useRef(false); 209 const _initialized = __TURBOPACK__imported__module__271645__["default"].useRef(false); 210 const _prevValue = __TURBOPACK__imported__module__271645__["default"].useRef(undefined); 211 const _renderCount = __TURBOPACK__imported__module__271645__["default"].useRef(0); 212 _renderCount.current++; 213 if (!_initialized.current && getInitialValue) { 214 _initialized.current = true; 215 _prevValue.current = cloneObject(getInitialValue()); 216 } 217 const resyncIfNeeded = __TURBOPACK__imported__module__271645__["default"].useCallback((enabled, getCurrentValue, setValue)=>{ 218 if (enabled && (_connected.current || _initialized.current && _renderCount.current > 1)) { 219 const currentValue = getCurrentValue(); 220 if (!deepEqual(_prevValue.current, currentValue)) { 221 setValue(currentValue); 222 } 223 } 224 _connected.current = true; 225 }, []); 226 const snapshot = __TURBOPACK__imported__module__271645__["default"].useCallback((enabled, getCurrentValue)=>{ 227 if (enabled) { 228 _prevValue.current = cloneObject(getCurrentValue()); 229 } 230 }, []); 231 return { 232 resyncIfNeeded, 233 snapshot 234 }; 235} 236/** 237 * Subscribes to form state with re-renders isolated to this hook. 238 * Optionally scope to specific field names to minimize re-render surface. 239 * 240 * @see [API](https://react-hook-form.com/docs/useformstate) 241 * 242 * @example 243 * ```tsx 244 * const { errors, isDirty } = useFormState({ control, name: "email" }); 245 * ``` 246 */ function useFormState(props) { 247 const formControl = useFormControlContext(); 248 const { control = formControl, disabled, name, exact } = props || {}; 249 const getCurrentFormState = ()=>({ 250 ...control._formState, 251 defaultValues: control._defaultValues 252 }); 253 const [formState, updateFormState] = __TURBOPACK__imported__module__271645__["default"].useState(getCurrentFormState); 254 const _localProxyFormState = __TURBOPACK__imported__module__271645__["default"].useRef({ 255 isDirty: false, 256 isLoading: false, 257 dirtyFields: false, 258 touchedFields: false, 259 validatingFields: false, 260 isValidating: false, 261 isValid: false, 262 errors: false 263 }); 264 const { resyncIfNeeded, snapshot } = useResyncOnReconnect(getCurrentFormState); 265 useIsomorphicLayoutEffect(()=>{ 266 resyncIfNeeded(!disabled, getCurrentFormState, updateFormState); 267 const unsubscribe = control._subscribe({ 268 name, 269 formState: _localProxyFormState.current, 270 exact, 271 callback: (formState)=>{ 272 !disabled && updateFormState({ 273 ...control._formState, 274 ...formState, 275 defaultValues: control._defaultValues 276 }); 277 } 278 }); 279 return ()=>{ 280 unsubscribe(); 281 snapshot(!disabled, getCurrentFormState); 282 }; 283 }, [ 284 control, 285 name, 286 disabled, 287 exact, 288 resyncIfNeeded, 289 snapshot 290 ]); 291 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 292 _localProxyFormState.current.isValid && control._setValid(true); 293 }, [ 294 control 295 ]); 296 return __TURBOPACK__imported__module__271645__["default"].useMemo(()=>getProxyFormState(formState, control, _localProxyFormState.current, false), [ 297 formState, 298 control 299 ]); 300} 301var isString = (value1)=>typeof value1 === 'string'; 302var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue)=>{ 303 if (isString(names)) { 304 isGlobal && _names.watch.add(names); 305 return get(formValues, names, defaultValue); 306 } 307 if (Array.isArray(names)) { 308 return names.map((fieldName)=>(isGlobal && _names.watch.add(fieldName), get(formValues, fieldName, get(defaultValue, fieldName)))); 309 } 310 isGlobal && (_names.watchAll = true); 311 return formValues; 312}; 313/** 314 * Subscribes to field value changes and isolates re-renders to the hook level. 315 * 316 * @see [API](https://react-hook-form.com/docs/usewatch) 317 * 318 * @example 319 * ```tsx 320 * const email = useWatch({ control, name: "email" }); 321 * const all = useWatch({ control }); 322 * const adult = useWatch({ control, name: "age", compute: (v) => v >= 18 }); 323 * ``` 324 */ function useWatch(props) { 325 const formControl = useFormControlContext(); 326 const { control = formControl, name, defaultValue, disabled, exact, compute } = props || {}; 327 const _defaultValue = __TURBOPACK__imported__module__271645__["default"].useRef(defaultValue); 328 const _compute = __TURBOPACK__imported__module__271645__["default"].useRef(compute); 329 const _prevControl = __TURBOPACK__imported__module__271645__["default"].useRef(control); 330 const _prevName = __TURBOPACK__imported__module__271645__["default"].useRef(name); 331 _compute.current = compute; 332 const getInitialOutput = ()=>{ 333 const defaultValue = control._getWatch(name, _defaultValue.current); 334 return _compute.current ? _compute.current(defaultValue) : defaultValue; 335 };
336 const [value1, updateValue] = __TURBOPACK__imported__module__271645__["default"].useState(getInitialOutput); 337 const _computeFormValues = __TURBOPACK__imported__module__271645__["default"].useRef(value1); 338 const getCurrentOutput = __TURBOPACK__imported__module__271645__["default"].useCallback((values)=>{ 339 const formValues = generateWatchOutput(name, control._names, values || control._formValues, false, _defaultValue.current); 340 return _compute.current ? _compute.current(formValues) : formValues; 341 }, [ 342 control._formValues, 343 control._names, 344 name 345 ]); 346 const refreshValue = __TURBOPACK__imported__module__271645__["default"].useCallback((values)=>{ 347 if (!disabled) { 348 const formValues = generateWatchOutput(name, control._names, values || control._formValues, false, _defaultValue.current); 349 if (_compute.current) { 350 const computedFormValues = _compute.current(formValues); 351 if (!deepEqual(computedFormValues, _computeFormValues.current)) { 352 updateValue(computedFormValues); 353 _computeFormValues.current = computedFormValues; 354 } 355 } else { 356 updateValue(formValues); 357 } 358 } 359 }, [ 360 control._formValues, 361 control._names, 362 disabled, 363 name 364 ]); 365 const { resyncIfNeeded, snapshot } = useResyncOnReconnect(getInitialOutput); 366 const _refreshValue = __TURBOPACK__imported__module__271645__["default"].useRef(refreshValue); 367 _refreshValue.current = refreshValue; 368 const _getCurrentOutput = __TURBOPACK__imported__module__271645__["default"].useRef(getCurrentOutput); 369 _getCurrentOutput.current = getCurrentOutput; 370 useIsomorphicLayoutEffect(()=>{ 371 if (_prevControl.current !== control || !deepEqual(_prevName.current, name)) { 372 _prevControl.current = control; 373 _prevName.current = name; 374 _refreshValue.current(); 375 } else { 376 resyncIfNeeded(!disabled, ()=>_getCurrentOutput.current(), (currentValue)=>{ 377 updateValue(currentValue); 378 _computeFormValues.current = currentValue; 379 }); 380 } 381 const unsubscribe = control._subscribe({ 382 name, 383 formState: { 384 values: true 385 }, 386 exact, 387 callback: (formState)=>{ 388 _refreshValue.current(formState.values); 389 } 390 }); 391 return ()=>{ 392 unsubscribe(); 393 snapshot(!disabled, ()=>_getCurrentOutput.current()); 394 }; 395 }, [ 396 control, 397 exact, 398 name, 399 disabled, 400 resyncIfNeeded, 401 snapshot 402 ]); 403 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>control._removeUnmounted()); 404 // If name or control changed for this render, synchronously reflect the 405 // latest value so callers (like useController) see the correct value 406 // immediately on the same render. 407 // Optimize: Check control reference first before expensive deepEqual 408 const controlChanged = _prevControl.current !== control; 409 const prevName = _prevName.current; 410 // `null`/`undefined` are valid watched values, so a boolean flag (rather 411 // than a sentinel return value) decides whether to return the freshly 412 // computed output instead of the possibly-stale state value. 413 const shouldReturnImmediate = __TURBOPACK__imported__module__271645__["default"].useMemo(()=>{ 414 if (disabled) { 415 return false; 416 } 417 const nameChanged = !controlChanged && !deepEqual(prevName, name); 418 return controlChanged || nameChanged; 419 }, [ 420 disabled, 421 controlChanged, 422 name, 423 prevName 424 ]); 425 return shouldReturnImmediate ? getCurrentOutput() : value1; 426} 427/** 428 * Hook for controlled inputs. Returns `field`, `fieldState`, and `formState`. 429 * Re-renders are isolated to the hook level. 430 * 431 * @see [API](https://react-hook-form.com/docs/usecontroller) 432 * 433 * @example 434 * ```tsx 435 * const { field, fieldState } = useController({ control, name: "email" }); 436 * return <input {...field} />; 437 * ``` 438 */ function useController(props) { 439 const formControl = useFormControlContext(); 440 const { name, disabled, control = formControl, shouldUnregister, defaultValue, exact = true } = props; 441 const isArrayField = isNameInFieldArray(control._names.array, name); 442 const defaultValueMemo = __TURBOPACK__imported__module__271645__["default"].useMemo(()=>{ 443 const resolved = get(control._formValues, name, get(control._defaultValues, name, defaultValue)); 444 return isUndefined(resolved) ? getNullAncestorValue(control, name) : resolved; 445 }, [ 446 control, 447 name, 448 defaultValue 449 ]); 450 const value1 = useWatch({ 451 control, 452 name, 453 defaultValue: defaultValueMemo, 454 exact 455 }); 456 const formState = useFormState({ 457 control, 458 name, 459 exact 460 }); 461 const _props = __TURBOPACK__imported__module__271645__["default"].useRef(props); 462 const _proxyRef = __TURBOPACK__imported__module__271645__["default"].useRef(null); 463 const _registerProps = __TURBOPACK__imported__module__271645__["default"].useRef(control.register(name, { 464 ...props.rules, 465 value: value1, 466 ...isBoolean(props.disabled) ? { 467 disabled: props.disabled 468 } : {} 469 })); 470 _props.current = props; 471 const fieldState = __TURBOPACK__imported__module__271645__["default"].useMemo(()=>Object.defineProperties({}, { 472 invalid: { 473 enumerable: true, 474 get: ()=>!!get(formState.errors, name) 475 }, 476 isDirty: { 477 enumerable: true, 478 get: ()=>!!get(formState.dirtyFields, name) 479 }, 480 isTouched: { 481 enumerable: true, 482 get: ()=>!!get(formState.touchedFields, name) 483 }, 484 isValidating: { 485 enumerable: true, 486 get: ()=>!!get(formState.validatingFields, name) 487 }, 488 error: { 489 enumerable: true, 490 get: ()=>get(formState.errors, name) 491 } 492 }), [ 493 formState, 494 name 495 ]); 496 const onChange = __TURBOPACK__imported__module__271645__["default"].useCallback((event)=>{ 497 const value1 = getEventValue(event); 498 if (!get(control._fields, name)) { 499 _registerProps.current = control.register(name, { 500 ..._props.current.rules, 501 value: value1 502 }); 503 } 504 return _registerProps.current.onChange({ 505 target: { 506 value: getEventValue(event), 507 name: name 508 }, 509 type: EVENTS.CHANGE 510 }); 511 }, [ 512 name, 513 control 514 ]); 515 const onBlur = __TURBOPACK__imported__module__271645__["default"].useCallback(()=>_registerProps.current.onBlur({ 516 target: { 517 value: get(control._formValues, name), 518 name: name 519 }, 520 type: EVENTS.BLUR 521 }), [ 522 name, 523 control._formValues 524 ]); 525 const ref = __TURBOPACK__imported__module__271645__["default"].useCallback((elm)=>{ 526 if (elm) { 527 _proxyRef.current = { 528 focus: ()=>isFunction(elm.focus) && elm.focus(), 529 select: ()=>isFunction(elm.select) && elm.select(), 530 setCustomValidity: (message)=>isFunction(elm.setCustomValidity) && elm.setCustomValidity(message), 531 reportValidity: ()=>isFunction(elm.reportValidity) && elm.reportValidity() 532 }; 533 } 534 const field = get(control._fields, name); 535 if (field && field._f && elm) { 536 field._f.ref = _proxyRef.current; 537 } 538 }, [ 539 control._fields, 540 name 541 ]); 542 const field = __TURBOPACK__imported__module__271645__["default"].useMemo(()=>({ 543 name, 544 value: value1, 545 ...isBoolean(disabled) || formState.disabled ? { 546 disabled: formState.disabled || disabled 547 } : {}, 548 onChange, 549 onBlur, 550 ref 551 }), [ 552 name, 553 disabled, 554 formState.disabled, 555 onChange, 556 onBlur, 557 ref, 558 value1 559 ]); 560 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 561 const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister; 562 _registerProps.current = control.register(name, { 563 ..._props.current.rules, 564 ...isBoolean(_props.current.disabled) ? { 565 disabled: _props.current.disabled 566 } : {} 567 }); 568 const updateMounted = (name, value1)=>{ 569 const field = get(control._fields, name); 570 if (field && field._f) { 571 field._f.mount = value1; 572 } 573 }; 574 updateMounted(name, true); 575 if (_shouldUnregisterField) { 576 const value1 = cloneObject(get(shouldUnregister ? control._defaultValues : control._options.values || control._defaultValues, name, get(control._options.defaultValues, name, _props.current.defaultValue))); 577 set(control._defaultValues, name, value1); 578 if (isUndefined(get(control._formValues, name))) { 579 set(control._formValues, name, value1); 580 } 581 } 582 !isArrayField && control.register(name); 583 if (_proxyRef.current) { 584 const field = get(control._fields, name); 585 if (field && field._f) { 586 field._f.ref = _proxyRef.current; 587 } 588 } 589 return ()=>{ 590 (isArrayField ? _shouldUnregisterField && !control._state.action : _shouldUnregisterField) ? control.unregister(name) : updateMounted(name, false); 591 }; 592 }, [ 593 name, 594 control, 595 isArrayField, 596 shouldUnregister 597 ]); 598 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 599 control._setDisabledField({ 600 disabled, 601 name 602 }); 603 }, [ 604 disabled, 605 name, 606 control 607 ]); 608 return __TURBOPACK__imported__module__271645__["default"].useMemo(()=>({ 609 field, 610 formState, 611 fieldState 612 }), [ 613 field, 614 formState, 615 fieldState 616 ]); 617} 618/** 619 * Component wrapper around `useController` for controlled inputs. 620 * 621 * @see [API](https://react-hook-form.com/docs/usecontroller/controller) 622 * 623 * @example 624 * ```tsx 625 * <Controller 626 * control={control} 627 * name="test" 628 * render={({ field, fieldState, formState }) => <input {...field} />} 629 * /> 630 * ``` 631 */ const Controller = (props)=>props.render(useController(props)); 632/** 633 * Displays the validation error for a single field. 634 * Reads from `control` when provided, otherwise from the nearest `FormProvider`. 635 * 636 * @see [API](https://react-hook-form.com/docs/useformstate/errormessage) 637 * 638 * @example 639 * ```tsx 640 * <ErrorMessage control={control} name="email" as="p" /> 641 * <ErrorMessage name="email" as="span" /> 642 * <ErrorMessage control={control} name="email" 643 * render={({ message }) => <Alert>{message}</Alert>} /> 644 * ``` 645 */ const ErrorMessage = (param)=>{ 646 let { as, control, name, render } = param; 647 const { errors } = useFormState({ 648 control, 649 name: name 650 }); 651 const error = get(errors, name); 652 if (!error) { 653 return null; 654 } 655 const message = error.message || ''; 656 if (render) { 657 return render({ 658 message, 659 messages: error.types 660 }); 661 } 662 return __TURBOPACK__imported__module__271645__["default"].createElement(as || __TURBOPACK__imported__module__271645__["default"].Fragment, null, message); 663}; 664var generateId = ()=>typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c)=>{ 665 const r = Math.random() * 16 | 0; 666 return (c === 'x' ? r : r & 0x3 | 0x8).toString(16); 667 }); 668var getFocusFieldName = function(name, index) { 669 let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; 670 return options.shouldFocus || isUndefined(options.shouldFocus) ? options.focusName || "".concat(name, ".").concat(isUndefined(options.focusIndex) ? index : options.focusIndex, ".") : ''; 671}; 672var getValidationModes = (mode)=>({ 673 isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit, 674 isOnBlur: mode === VALIDATION_MODE.onBlur, 675 isOnChange: mode === VALIDATION_MODE.onChange, 676 isOnAll: mode === VALIDATION_MODE.all, 677 isOnTouch: mode === VALIDATION_MODE.onTouched 678 }); 679var isWatched = (name, _names, isBlurEvent)=>{ 680 if (isBlurEvent) return false;
681 if (_names.watchAll || _names.watch.has(name)) return true; 682 for (const watchName of _names.watch){ 683 if (name.startsWith(watchName) && name.charAt(watchName.length) === '.') return true; 684 } 685 return false; 686}; 687const iterateFieldsByAction = (fields, action, fieldsNames)=>{ 688 for (const key of fieldsNames || Object.keys(fields)){ 689 if (key === '_f') { 690 continue; 691 } 692 const field = fieldsNames ? get(fields, key) : fields[key]; 693 if (field) { 694 const { _f } = field; 695 if (_f) { 696 if (_f.refs && _f.refs[0] && action(_f.refs[0], _f.name)) { 697 return true; 698 } else if (_f.ref && action(_f.ref, _f.name)) { 699 return true; 700 } else { 701 if (iterateFieldsByAction(field, action)) { 702 return true; 703 } 704 } 705 } else if (isObject(field) || Array.isArray(field)) { 706 if (iterateFieldsByAction(field, action)) { 707 return true; 708 } 709 } 710 } 711 } 712 return; 713}; 714var updateFieldArrayRootError = (errors, error, name)=>{ 715 const existingErrors = get(errors, name); 716 const fieldArrayErrors = Array.isArray(existingErrors) ? existingErrors : []; 717 set(fieldArrayErrors, ROOT_ERROR_TYPE, error[name]); 718 set(errors, name, fieldArrayErrors); 719 return errors; 720}; 721var isEmptyObject = (value1)=>isObject(value1) && !Object.keys(value1).length; 722var isHTMLElement = (value1)=>{ 723 if (!isWeb) { 724 return false; 725 } 726 const owner = value1 ? value1.ownerDocument : 0; 727 return value1 instanceof (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement); 728}; 729var isRadioInput = (element)=>element.type === 'radio'; 730var isRegex = (value1)=>value1 instanceof RegExp; 731var appendErrors = (name, validateAllFieldCriteria, errors, type, message)=>validateAllFieldCriteria ? { 732 ...errors[name], 733 types: { 734 ...errors[name] && errors[name].types ? errors[name].types : {}, 735 [type]: message || true 736 } 737 } : {}; 738const defaultResult = { 739 value: false, 740 isValid: false 741}; 742const validResult = { 743 value: true, 744 isValid: true 745}; 746var getCheckboxValue = (options)=>{ 747 if (!Array.isArray(options)) { 748 return defaultResult; 749 } 750 if (options.length > 1) { 751 const values = options.filter((option)=>option && option.checked && !option.disabled).map((option)=>option.value); 752 return { 753 value: values, 754 isValid: !!values.length 755 }; 756 } 757 const option = options[0]; 758 if (!option || !option.checked || option.disabled) { 759 return defaultResult; 760 } 761 if (!option.attributes || !('value' in option.attributes)) { 762 return validResult; 763 } 764 return isUndefined(option.value) || option.value === '' ? validResult : { 765 value: option.value, 766 isValid: true 767 }; 768}; 769const defaultReturn = { 770 isValid: false, 771 value: null 772}; 773var getRadioValue = (options)=>Array.isArray(options) ? options.reduce((previous, option)=>option && option.checked && !option.disabled ? { 774 isValid: true, 775 value: option.value 776 } : previous, defaultReturn) : defaultReturn; 777function getValidateError(result, ref) { 778 let type = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 'validate'; 779 if (isString(result) || Array.isArray(result) && result.every(isString) || isBoolean(result) && !result) { 780 return { 781 type, 782 message: isString(result) ? result : '', 783 ref 784 }; 785 } 786} 787var getValueAndMessage = (validationData)=>isObject(validationData) && !isRegex(validationData) ? validationData : { 788 value: validationData, 789 message: '' 790 }; 791var validateField = async (field, disabledFieldNames, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray)=>{ 792 const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount } = field._f; 793 const inputValue = get(formValues, name); 794 if (!mount || disabledFieldNames.has(name)) { 795 return {}; 796 } 797 const inputRef = refs ? refs[0] : ref; 798 const setCustomValidity = (message)=>{ 799 if (shouldUseNativeValidation && inputRef.reportValidity) { 800 const validityMessage = isBoolean(message) ? '' : message || ''; 801 if (refs) {
802 refs.forEach((ref)=>ref.setCustomValidity(validityMessage)); 803 } else { 804 inputRef.setCustomValidity(validityMessage); 805 } 806 inputRef.reportValidity(); 807 } 808 }; 809 const error = {}; 810 const isRadio = isRadioInput(ref); 811 const isCheckBox = isCheckBoxInput(ref); 812 const isRadioOrCheckbox = isRadio || isCheckBox; 813 const isEmpty = (valueAsNumber || isFileInput(ref)) && isUndefined(ref.value) && isUndefined(inputValue) || isHTMLElement(ref) && ref.value === '' || inputValue === '' || Array.isArray(inputValue) && !inputValue.length; 814 const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error); 815 const getMinMaxMessage = function(exceedMax, maxLengthMessage, minLengthMessage) { 816 let maxType = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : INPUT_VALIDATION_RULES.maxLength, minType = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : INPUT_VALIDATION_RULES.minLength; 817 const message = exceedMax ? maxLengthMessage : minLengthMessage; 818 error[name] = { 819 type: exceedMax ? maxType : minType, 820 message, 821 ref, 822 ...appendErrorsCurry(exceedMax ? maxType : minType, message) 823 }; 824 }; 825 if (isFieldArray ? !Array.isArray(inputValue) || !inputValue.length : required && (!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue)) || isBoolean(inputValue) && !inputValue || isCheckBox && !getCheckboxValue(refs).isValid || isRadio && !getRadioValue(refs).isValid)) { 826 const { value: value1, message } = isString(required) ? { 827 value: !!required, 828 message: required 829 } : getValueAndMessage(required); 830 if (value1) { 831 error[name] = { 832 type: INPUT_VALIDATION_RULES.required, 833 message, 834 ref: inputRef, 835 ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message) 836 }; 837 if (!validateAllFieldCriteria) { 838 setCustomValidity(message); 839 return error; 840 } 841 } 842 } 843 if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) { 844 let exceedMax; 845 let exceedMin; 846 const maxOutput = getValueAndMessage(max); 847 const minOutput = getValueAndMessage(min); 848 if (!isNullOrUndefined(inputValue) && !isDateObject(inputValue) && !isNaN(inputValue)) { 849 const valueNumber = ref.valueAsNumber || (inputValue ? +inputValue : inputValue); 850 if (!isNullOrUndefined(maxOutput.value)) { 851 exceedMax = valueNumber > maxOutput.value; 852 } 853 if (!isNullOrUndefined(minOutput.value)) { 854 exceedMin = valueNumber < minOutput.value; 855 } 856 } else { 857 const valueDate = ref.valueAsDate || new Date(inputValue); 858 const convertTimeToDate = (time)=>new Date(new Date().toDateString() + ' ' + time); 859 const isTime = ref.type == 'time'; 860 const isWeek = ref.type == 'week'; 861 if (isString(maxOutput.value) && inputValue) { 862 exceedMax = isTime ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value) : isWeek ? inputValue > maxOutput.value : valueDate > new Date(maxOutput.value); 863 } 864 if (isString(minOutput.value) && inputValue) { 865 exceedMin = isTime ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value) : isWeek ? inputValue < minOutput.value : valueDate < new Date(minOutput.value); 866 } 867 } 868 if (exceedMax || exceedMin) { 869 getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min); 870 if (!validateAllFieldCriteria) { 871 setCustomValidity(error[name].message); 872 return error; 873 } 874 } 875 } 876 if ((maxLength || minLength) && !isEmpty && (isString(inputValue) || isFieldArray && Array.isArray(inputValue))) { 877 const maxLengthOutput = getValueAndMessage(maxLength); 878 const minLengthOutput = getValueAndMessage(minLength); 879 const exceedMax = !isNullOrUndefined(maxLengthOutput.value) && inputValue.length > +maxLengthOutput.value; 880 const exceedMin = !isNullOrUndefined(minLengthOutput.value) && inputValue.length < +minLengthOutput.value; 881 if (exceedMax || exceedMin) { 882 getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message); 883 if (!validateAllFieldCriteria) { 884 setCustomValidity(error[name].message); 885 return error; 886 } 887 } 888 } 889 if (pattern && !isEmpty && isString(inputValue)) { 890 const { value: patternValue, message } = getValueAndMessage(pattern); 891 if (isRegex(patternValue) && !inputValue.match(patternValue)) { 892 error[name] = { 893 type: INPUT_VALIDATION_RULES.pattern, 894 message, 895 ref, 896 ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message) 897 }; 898 if (!validateAllFieldCriteria) { 899 setCustomValidity(message); 900 return error; 901 } 902 } 903 } 904 if (validate) {
905 if (isFunction(validate)) { 906 const result = await validate(inputValue, formValues); 907 const validateError = getValidateError(result, inputRef); 908 if (validateError) { 909 error[name] = { 910 ...validateError, 911 ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message) 912 }; 913 if (!validateAllFieldCriteria) { 914 setCustomValidity(validateError.message); 915 return error; 916 } 917 } 918 } else if (isObject(validate)) { 919 let validationResult = {}; 920 for(const key in validate){ 921 if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) { 922 break; 923 } 924 const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key); 925 if (validateError) { 926 validationResult = { 927 ...validateError, 928 ...appendErrorsCurry(key, validateError.message) 929 }; 930 if (!validateAllFieldCriteria) { 931 setCustomValidity(validateError.message); 932 } 933 if (validateAllFieldCriteria) { 934 error[name] = validationResult; 935 } 936 } 937 } 938 if (!isEmptyObject(validationResult)) { 939 error[name] = { 940 ref: inputRef, 941 ...validationResult 942 }; 943 if (!validateAllFieldCriteria) { 944 return error; 945 } 946 } 947 } 948 } 949 const fieldError = error[name]; 950 setCustomValidity(fieldError ? fieldError.message : true); 951 return error; 952}; 953var convertToArrayPayload = (value1)=>Array.isArray(value1) ? value1 : [ 954 value1 955 ]; 956var appendAt = (data, value1)=>[ 957 ...data, 958 ...convertToArrayPayload(value1) 959 ]; 960var fillEmptyArray = (value1)=>Array.isArray(value1) ? value1.map(()=>undefined) : undefined; 961function insert(data, index, value1) { 962 return [ 963 ...data.slice(0, index), 964 ...convertToArrayPayload(value1), 965 ...data.slice(index) 966 ]; 967} 968var moveArrayAt = (data, from, to)=>{ 969 if (!Array.isArray(data)) { 970 return []; 971 } 972 if (isUndefined(data[to])) { 973 data[to] = undefined; 974 } 975 data.splice(to, 0, data.splice(from, 1)[0]); 976 return data; 977}; 978var prependAt = (data, value1)=>[ 979 ...convertToArrayPayload(value1), 980 ...convertToArrayPayload(data) 981 ]; 982var compact = (value1)=>Array.isArray(value1) ? value1.filter(Boolean) : []; 983function removeAtIndexes(data, indexes) { 984 let i = 0; 985 const temp = [ 986 ...data 987 ]; 988 for (const index of indexes){ 989 temp.splice(index - i, 1); 990 i++; 991 } 992 return compact(temp).length ? temp : []; 993} 994var removeArrayAt = (data, index)=>isUndefined(index) ? [] : removeAtIndexes(data, convertToArrayPayload(index).sort((a, b)=>a - b)); 995var swapArrayAt = (data, indexA, indexB)=>{ 996 [data[indexA], data[indexB]] = [ 997 data[indexB], 998 data[indexA] 999 ]; 1000}; 1001function baseGet(object, updatePath) { 1002 const length = updatePath.length - 1; 1003 let index = 0; 1004 while(index < length){ 1005 if (isNullOrUndefined(object)) { 1006 object = undefined; 1007 break; 1008 } 1009 object = object[updatePath[index]]; 1010 index++; 1011 } 1012 return object; 1013} 1014function isEmptyArray(obj) { 1015 for(const key in obj){ 1016 if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) { 1017 return false; 1018 } 1019 } 1020 return true; 1021} 1022function unset(object, path) { 1023 if (isString(path) && Object.prototype.hasOwnProperty.call(object, path)) { 1024 delete object[path]; 1025 return object; 1026 } 1027 const paths = Array.isArray(path) ? path : isKey(path) ? [ 1028 path 1029 ] : stringToPath(path); 1030 if (paths.some((segment)=>PROTOTYPE_KEYWORDS.includes(String(segment)))) { 1031 return object; 1032 } 1033 const childObject = paths.length === 1 ? object : baseGet(object, paths); 1034 const index = paths.length - 1;
1035 const key = paths[index]; 1036 if (childObject) { 1037 delete childObject[key]; 1038 } 1039 if (index !== 0 && (isObject(childObject) && isEmptyObject(childObject) || Array.isArray(childObject) && isEmptyArray(childObject))) { 1040 unset(object, paths.slice(0, -1)); 1041 } 1042 return object; 1043} 1044var updateAt = (fieldValues, index, value1)=>{ 1045 fieldValues[index] = value1; 1046 return fieldValues; 1047}; 1048/** 1049 * Hook for dynamic field arrays. Provides `fields` and mutation methods: 1050 * `append`, `prepend`, `remove`, `insert`, `swap`, `move`, `update`, `replace`. 1051 * 1052 * @see [API](https://react-hook-form.com/docs/usefieldarray) 1053 * 1054 * @example 1055 * ```tsx 1056 * const { fields, append } = useFieldArray({ control, name: "items" }); 1057 * return fields.map((f, i) => <input key={f.id} {...register(`items.${i}.name`)} />); 1058 * ``` 1059 */ function useFieldArray(props) { 1060 const formControl = useFormControlContext(); 1061 const { control = formControl, name, keyName = 'id', disabled, shouldUnregister, rules } = props; 1062 const getCurrentFieldArray = ()=>control._getFieldArray(name); 1063 const [fields, setFields] = __TURBOPACK__imported__module__271645__["default"].useState(getCurrentFieldArray); 1064 const ids = __TURBOPACK__imported__module__271645__["default"].useRef(control._getFieldArray(name).map(generateId)); 1065 const _actioned = __TURBOPACK__imported__module__271645__["default"].useRef(false); 1066 const { resyncIfNeeded, snapshot } = useResyncOnReconnect(getCurrentFieldArray); 1067 const _prevControl = __TURBOPACK__imported__module__271645__["default"].useRef(control); 1068 const _prevName = __TURBOPACK__imported__module__271645__["default"].useRef(name); 1069 if (!disabled) { 1070 control._names.array.add(name); 1071 } 1072 __TURBOPACK__imported__module__271645__["default"].useMemo(()=>!disabled && rules && fields.length >= 0 && control.register(name, rules), [ 1073 control, 1074 name, 1075 fields.length, 1076 rules, 1077 disabled 1078 ]); 1079 useIsomorphicLayoutEffect(()=>{ 1080 if (disabled) { 1081 return; 1082 } 1083 if (_prevControl.current === control && _prevName.current === name) { 1084 resyncIfNeeded(true, getCurrentFieldArray, (fieldValues)=>{ 1085 setFields(fieldValues); 1086 ids.current = fieldValues.map(generateId); 1087 }); 1088 } else { 1089 _prevControl.current = control; 1090 _prevName.current = name; 1091 const fieldValues = getCurrentFieldArray(); 1092 if (!deepEqual(fields, fieldValues)) { 1093 setFields(fieldValues); 1094 ids.current = fieldValues.map(generateId); 1095 } 1096 snapshot(true, getCurrentFieldArray); 1097 } 1098 const unsubscribe = control._subjects.array.subscribe({ 1099 next: (param)=>{ 1100 let { values, name: fieldArrayName } = param; 1101 if (fieldArrayName === name || !fieldArrayName) { 1102 const fieldValues = get(values, name); 1103 if (Array.isArray(fieldValues)) { 1104 setFields(fieldValues); 1105 ids.current = fieldValues.map(generateId); 1106 } else if (!fieldArrayName) { 1107 setFields([]); 1108 ids.current = []; 1109 } 1110 } 1111 } 1112 }).unsubscribe; 1113 return ()=>{ 1114 unsubscribe(); 1115 snapshot(true, getCurrentFieldArray); 1116 }; 1117 }, [ 1118 control, 1119 name, 1120 disabled, 1121 resyncIfNeeded, 1122 snapshot 1123 ]); 1124 const updateValues = __TURBOPACK__imported__module__271645__["default"].useCallback((updatedFieldArrayValues)=>{ 1125 _actioned.current = true; 1126 control._setFieldArray(name, updatedFieldArrayValues); 1127 }, [ 1128 control, 1129 name 1130 ]); 1131 const append = (value1, options)=>{ 1132 if (disabled) { 1133 return; 1134 } 1135 const appendValue = convertToArrayPayload(cloneObject(value1)); 1136 const updatedFieldArrayValues = appendAt(control._getFieldArray(name), appendValue); 1137 control._names.focus = getFocusFieldName(name, updatedFieldArrayValues.length - 1, options); 1138 ids.current = appendAt(ids.current, appendValue.map(generateId));
1139 updateValues(updatedFieldArrayValues); 1140 setFields(updatedFieldArrayValues); 1141 control._setFieldArray(name, updatedFieldArrayValues, appendAt, { 1142 argA: fillEmptyArray(value1) 1143 }); 1144 }; 1145 const prepend = (value1, options)=>{ 1146 if (disabled) { 1147 return; 1148 } 1149 const prependValue = convertToArrayPayload(cloneObject(value1)); 1150 const updatedFieldArrayValues = prependAt(control._getFieldArray(name), prependValue); 1151 control._names.focus = getFocusFieldName(name, 0, options); 1152 ids.current = prependAt(ids.current, prependValue.map(generateId)); 1153 updateValues(updatedFieldArrayValues); 1154 setFields(updatedFieldArrayValues); 1155 control._setFieldArray(name, updatedFieldArrayValues, prependAt, { 1156 argA: fillEmptyArray(value1) 1157 }); 1158 }; 1159 const remove = (index)=>{ 1160 if (disabled) { 1161 return; 1162 } 1163 const updatedFieldArrayValues = removeArrayAt(control._getFieldArray(name), index); 1164 ids.current = removeArrayAt(ids.current, index); 1165 updateValues(updatedFieldArrayValues); 1166 setFields(updatedFieldArrayValues); 1167 !Array.isArray(get(control._fields, name)) && set(control._fields, name, undefined); 1168 control._setFieldArray(name, updatedFieldArrayValues, removeArrayAt, { 1169 argA: index 1170 }); 1171 }; 1172 const insert$1 = (index, value1, options)=>{ 1173 if (disabled) { 1174 return; 1175 } 1176 const insertValue = convertToArrayPayload(cloneObject(value1)); 1177 const updatedFieldArrayValues = insert(control._getFieldArray(name), index, insertValue); 1178 control._names.focus = getFocusFieldName(name, index, options); 1179 ids.current = insert(ids.current, index, insertValue.map(generateId)); 1180 updateValues(updatedFieldArrayValues); 1181 setFields(updatedFieldArrayValues); 1182 control._setFieldArray(name, updatedFieldArrayValues, insert, { 1183 argA: index, 1184 argB: fillEmptyArray(value1) 1185 }); 1186 }; 1187 const swap = (indexA, indexB)=>{ 1188 if (disabled) { 1189 return; 1190 } 1191 const updatedFieldArrayValues = control._getFieldArray(name); 1192 swapArrayAt(updatedFieldArrayValues, indexA, indexB); 1193 swapArrayAt(ids.current, indexA, indexB); 1194 updateValues(updatedFieldArrayValues); 1195 setFields(updatedFieldArrayValues); 1196 control._setFieldArray(name, updatedFieldArrayValues, swapArrayAt, { 1197 argA: indexA, 1198 argB: indexB 1199 }, false); 1200 }; 1201 const move = (from, to)=>{ 1202 if (disabled) { 1203 return; 1204 } 1205 const updatedFieldArrayValues = control._getFieldArray(name); 1206 moveArrayAt(updatedFieldArrayValues, from, to); 1207 moveArrayAt(ids.current, from, to); 1208 updateValues(updatedFieldArrayValues); 1209 setFields(updatedFieldArrayValues); 1210 control._setFieldArray(name, updatedFieldArrayValues, moveArrayAt, { 1211 argA: from, 1212 argB: to 1213 }, false); 1214 }; 1215 const update = (index, value1)=>{ 1216 if (disabled) { 1217 return; 1218 } 1219 const updateValue = cloneObject(value1); 1220 const updatedFieldArrayValues = updateAt(control._getFieldArray(name), index, updateValue); 1221 ids.current = [ 1222 ...updatedFieldArrayValues 1223 ].map((item, i)=>!item || i === index ? generateId() : ids.current[i]); 1224 updateValues(updatedFieldArrayValues); 1225 setFields([ 1226 ...updatedFieldArrayValues 1227 ]); 1228 control._setFieldArray(name, updatedFieldArrayValues, updateAt, { 1229 argA: index, 1230 argB: fillEmptyArray(value1) 1231 }); 1232 }; 1233 const replace = (value1)=>{ 1234 if (disabled) { 1235 return; 1236 } 1237 const updatedFieldArrayValues = convertToArrayPayload(cloneObject(value1)); 1238 ids.current = updatedFieldArrayValues.map(generateId); 1239 updateValues([ 1240 ...updatedFieldArrayValues 1241 ]); 1242 setFields([ 1243 ...updatedFieldArrayValues 1244 ]); 1245 control._setFieldArray(name, [ 1246 ...updatedFieldArrayValues 1247 ], (data)=>Array.isArray(data) ? data.slice(0, updatedFieldArrayValues.length) : data, {}); 1248 }; 1249 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 1250 if (disabled) { 1251 control._state.actionArrayLengths.delete(name); 1252 return; 1253 } 1254 control._state.action = false;
1255 control._state.actionArrayLengths.delete(name); 1256 isWatched(name, control._names) && control._subjects.state.next({ 1257 ...control._formState 1258 }); 1259 const validationModes = getValidationModes(control._options.mode); 1260 if (_actioned.current && (!validationModes.isOnSubmit || control._formState.isSubmitted) && !getValidationModes(control._options.reValidateMode).isOnSubmit && !validationModes.isOnBlur) { 1261 if (control._options.resolver) { 1262 control._runSchema([ 1263 name 1264 ]).then((result)=>{ 1265 var _a, _b; 1266 control._updateIsValidating([ 1267 name 1268 ]); 1269 const error = get(result.errors, name); 1270 const existingError = get(control._formState.errors, name); 1271 const existingErrorType = existingError && (existingError.type || ((_a = existingError.root) === null || _a === void 0 ? void 0 : _a.type)); 1272 const existingErrorMessage = existingError && (existingError.message || ((_b = existingError.root) === null || _b === void 0 ? void 0 : _b.message)); 1273 if (existingError ? !error && existingErrorType || error && (existingErrorType !== error.type || existingErrorMessage !== error.message) : error && error.type) { 1274 if (error) { 1275 isObject(error) && !Object.keys(error).some((key)=>!Number.isNaN(+key)) ? updateFieldArrayRootError(control._formState.errors, { 1276 [name]: error 1277 }, name) : set(control._formState.errors, name, error); 1278 } else { 1279 unset(control._formState.errors, name); 1280 } 1281 control._subjects.state.next({ 1282 errors: control._formState.errors 1283 }); 1284 } 1285 }); 1286 } else { 1287 const field = get(control._fields, name); 1288 if (field && field._f) { 1289 validateField(field, control._names.disabled, control._formValues, control._options.criteriaMode === VALIDATION_MODE.all, control._options.shouldUseNativeValidation, true).then((error)=>!isEmptyObject(error) && control._subjects.state.next({ 1290 errors: updateFieldArrayRootError(control._formState.errors, error, name) 1291 })); 1292 } 1293 } 1294 } 1295 // External updates that change `fields` (e.g. reset() or setValue() on 1296 // the array) already notify subscribers with the up-to-date values 1297 // themselves, so only re-broadcast here for genuine array method calls. 1298 _actioned.current && control._subjects.state.next({ 1299 name, 1300 values: cloneObject(control._formValues) 1301 }); 1302 control._names.focus && iterateFieldsByAction(control._fields, (ref, key)=>{ 1303 if (control._names.focus && key.startsWith(control._names.focus) && ref.focus) { 1304 ref.focus(); 1305 return 1; 1306 } 1307 return; 1308 }); 1309 control._names.focus = ''; 1310 control._setValid(); 1311 _actioned.current = false; 1312 }, [ 1313 fields, 1314 name, 1315 control, 1316 disabled 1317 ]); 1318 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 1319 if (!disabled) { 1320 !get(control._formValues, name) && control._setFieldArray(name); 1321 } 1322 return ()=>{ 1323 control._state.actionArrayLengths.delete(name); 1324 if (disabled) { 1325 return; 1326 } 1327 const shouldKeepFieldArrayValues = !(control._options.shouldUnregister || shouldUnregister); 1328 const updateMounted = (name, value1)=>{ 1329 const field = get(control._fields, name); 1330 if (field && field._f) { 1331 field._f.mount = value1; 1332 } 1333 }; 1334 if (_actioned.current && shouldKeepFieldArrayValues) { 1335 control._subjects.state.next({ 1336 name, 1337 values: cloneObject(control._formValues) 1338 }); 1339 } 1340 shouldKeepFieldArrayValues ? updateMounted(name, false) : control.unregister(name); 1341 }; 1342 }, [ 1343 name, 1344 control, 1345 keyName, 1346 shouldUnregister, 1347 disabled 1348 ]); 1349 return { 1350 swap: __TURBOPACK__imported__module__271645__["default"].useCallback(swap, [
1351 updateValues, 1352 name, 1353 control, 1354 disabled 1355 ]), 1356 move: __TURBOPACK__imported__module__271645__["default"].useCallback(move, [ 1357 updateValues, 1358 name, 1359 control, 1360 disabled 1361 ]), 1362 prepend: __TURBOPACK__imported__module__271645__["default"].useCallback(prepend, [ 1363 updateValues, 1364 name, 1365 control, 1366 disabled 1367 ]), 1368 append: __TURBOPACK__imported__module__271645__["default"].useCallback(append, [ 1369 updateValues, 1370 name, 1371 control, 1372 disabled 1373 ]), 1374 remove: __TURBOPACK__imported__module__271645__["default"].useCallback(remove, [ 1375 updateValues, 1376 name, 1377 control, 1378 disabled 1379 ]), 1380 insert: __TURBOPACK__imported__module__271645__["default"].useCallback(insert$1, [ 1381 updateValues, 1382 name, 1383 control, 1384 disabled 1385 ]), 1386 update: __TURBOPACK__imported__module__271645__["default"].useCallback(update, [ 1387 updateValues, 1388 name, 1389 control, 1390 disabled 1391 ]), 1392 replace: __TURBOPACK__imported__module__271645__["default"].useCallback(replace, [ 1393 updateValues, 1394 name, 1395 control, 1396 disabled 1397 ]), 1398 fields: __TURBOPACK__imported__module__271645__["default"].useMemo(()=>fields.map((field, index)=>({ 1399 ...field, 1400 ...isBoolean(disabled) ? { 1401 disabled 1402 } : {}, 1403 [keyName]: ids.current[index] || generateId() 1404 })), [ 1405 fields, 1406 keyName, 1407 disabled 1408 ]) 1409 }; 1410} 1411/** 1412 * Component based on `useFieldArray` hook to work with controlled component. 1413 * 1414 * @example 1415 * ```tsx 1416 * function App() { 1417 * const { control, register } = useForm<FormValues>({ 1418 * defaultValues: { 1419 * test: [ 1420 * { 1421 * value: '', 1422 * }, 1423 * ], 1424 * }, 1425 * }); 1426 * 1427 * return ( 1428 * <form> 1429 * <FieldArray 1430 * control={control} 1431 * name="test" 1432 * render={({ fields }) => 1433 * fields.map((field, index) => ( 1434 * <input key={field.id} {...register(`test.${index}.value`)} /> 1435 * )) 1436 * } 1437 * /> 1438 * </form> 1439 * ); 1440 * } 1441 * ``` 1442 */ const FieldArray = (props)=>props.render(useFieldArray(props)); 1443const isFileLike = (value1)=>typeof Blob !== 'undefined' && value1 instanceof Blob || typeof File !== 'undefined' && value1 instanceof File; 1444const isFileListLike = (value1)=>typeof FileList !== 'undefined' && value1 instanceof FileList; 1445const flatten = (obj)=>{ 1446 const output = {}; 1447 for (const key of Object.keys(obj)){ 1448 if (isObjectType(obj[key]) && obj[key] !== null && !isDateObject(obj[key]) && !isFileLike(obj[key]) && !isFileListLike(obj[key])) { 1449 const nested = flatten(obj[key]); 1450 for (const nestedKey of Object.keys(nested)){ 1451 output["".concat(key, ".").concat(nestedKey)] = nested[nestedKey]; 1452 } 1453 } else { 1454 output[key] = obj[key]; 1455 } 1456 } 1457 return output; 1458}; 1459function jsonToFormData(json) { 1460 const result = new FormData(); 1461 const flattenFormValues = flatten(json); 1462 for(const key in flattenFormValues){ 1463 const value1 = flattenFormValues[key]; 1464 if (isUndefined(value1)) { 1465 continue; 1466 } 1467 if (typeof FileList !== 'undefined' && value1 instanceof FileList) { 1468 for(let index = 0; index < value1.length; index++){ 1469 const file = value1[index]; 1470 file && result.append(key, file); 1471 } 1472 continue; 1473 } 1474 result.append(key, value1); 1475 } 1476 return result; 1477} 1478function safeJSONStringify(value1) { 1479 try { 1480 return JSON.stringify(value1); 1481 } catch (_a) { 1482 return ''; 1483 } 1484} 1485function noop() {} 1486const HookFormContext = __TURBOPACK__imported__module__271645__["default"].createContext(null); 1487HookFormContext.displayName = 'HookFormContext'; 1488/** 1489 * Retrieves all `useForm` methods from the nearest `FormProvider`. 1490 * Use in deeply nested components to avoid prop-drilling. 1491 * 1492 * @see [API](https://react-hook-form.com/docs/useformcontext) 1493 * 1494 * @example 1495 * ```tsx 1496 * const { register } = useFormContext<FormValues>(); 1497 * ``` 1498 */ const useFormContext = ()=>__TURBOPACK__imported__module__271645__["default"].useContext(HookFormContext); 1499/** 1500 * Provides all `useForm` methods to the component tree via React Context. 1501 * Pair with `useFormContext` to consume them in any descendant. 1502 * 1503 * @see [API](https://react-hook-form.com/docs/useformcontext) 1504 * 1505 * @example 1506 * ```tsx 1507 * <FormProvider {...methods}> 1508 * <form onSubmit={methods.handleSubmit(onSubmit)}>{children}</form> 1509 * </FormProvider> 1510 * ``` 1511 */ const FormProvider = (param)=>{ 1512 let { children, watch, getValues, getErrors, getFieldState, setError, clearErrors, setValue, setValues, trigger, formState, resetField, reset, resetDefaultValues, handleSubmit, unregister, control, register, setFocus, subscribe } = param; 1513 const memoizedValue = __TURBOPACK__imported__module__271645__["default"].useMemo(()=>({ 1514 watch, 1515 getValues, 1516 getErrors, 1517 getFieldState, 1518 setError, 1519 clearErrors, 1520 setValue, 1521 setValues, 1522 trigger, 1523 formState, 1524 resetField, 1525 reset, 1526 resetDefaultValues, 1527 handleSubmit, 1528 unregister, 1529 control, 1530 register, 1531 setFocus, 1532 subscribe 1533 }), [ 1534 clearErrors, 1535 control, 1536 formState, 1537 getErrors, 1538 getFieldState, 1539 getValues, 1540 handleSubmit, 1541 register, 1542 reset, 1543 resetDefaultValues, 1544 resetField, 1545 setError, 1546 setFocus, 1547 setValue, 1548 setValues, 1549 subscribe, 1550 trigger, 1551 unregister, 1552 watch 1553 ]); 1554 return __TURBOPACK__imported__module__271645__["default"].createElement(HookFormContext.Provider, { 1555 value: memoizedValue 1556 }, __TURBOPACK__imported__module__271645__["default"].createElement(HookFormControlContext.Provider, { 1557 value: memoizedValue.control 1558 }, children)); 1559}; 1560const POST_REQUEST = 'post'; 1561function defaultValidateStatus(status) { 1562 return status >= 200 && status < 300; 1563} 1564/** 1565 * Form component that handles submission, including optional `action` fetch and server error wiring. 1566 * 1567 * @see [API](https://react-hook-form.com/docs/useform/form) 1568 * 1569 * @example 1570 * ```tsx 1571 * <Form action="/api" control={control}> 1572 * <input {...register("name")} /> 1573 * <p>{errors?.root?.server && 'Server error'}</p> 1574 * <button>Submit</button> 1575 * </Form> 1576 * ``` 1577 */ function Form(props) { 1578 const methods = useFormContext(); 1579 const [mounted, setMounted] = __TURBOPACK__imported__module__271645__["default"].useState(false); 1580 const { control = methods.control, onSubmit = noop, children, action, method = POST_REQUEST, headers, encType, onError = noop, render, onSuccess = noop, validateStatus = defaultValidateStatus, ...rest } = props; 1581 const handleSubmit = __TURBOPACK__imported__module__271645__["default"].useMemo(()=>{ 1582 return control.handleSubmit(async (data, event)=>{ 1583 const formData = jsonToFormData(data); 1584 const formDataJson = safeJSONStringify(data); 1585 if (onSubmit) { 1586 await onSubmit({ 1587 data, 1588 event, 1589 method, 1590 formData, 1591 formDataJson 1592 }); 1593 } 1594 if (isString(action)) { 1595 try { 1596 const shouldStringifySubmissionData = headers && headers['Content-Type'] && headers['Content-Type'].includes('json') || encType && encType.includes('json'); 1597 const response = await fetch(action, { 1598 method, 1599 headers: { 1600 ...headers, 1601 ...encType && encType !== 'multipart/form-data' && { 1602 'Content-Type': encType 1603 } 1604 }, 1605 body: shouldStringifySubmissionData ? formDataJson : formData 1606 }); 1607 if (response && !validateStatus(response.status)) { 1608 onError({ 1609 response 1610 }); 1611 return { 1612 type: String(response.status) 1613 }; 1614 } else { 1615 onSuccess({ 1616 response 1617 }); 1618 } 1619 } catch (error) { 1620 onError({ 1621 error 1622 }); 1623 return { 1624 type: '' 1625 }; 1626 } 1627 } 1628 if (isFunction(action)) { 1629 try { 1630 await action(formData); 1631 } catch (error) { 1632 onError({ 1633 error 1634 }); 1635 return { 1636 type: '' 1637 }; 1638 } 1639 } 1640 // Return nothing when successful. 1641 return; 1642 }); 1643 }, [ 1644 control, 1645 onSubmit, 1646 method, 1647 action, 1648 headers, 1649 encType, 1650 validateStatus, 1651 onError, 1652 onSuccess 1653 ]); 1654 const submit = __TURBOPACK__imported__module__271645__["default"].useCallback(async (event)=>{ 1655 const err = await handleSubmit(event); 1656 if (err && control) { 1657 control._subjects.state.next({ 1658 isSubmitSuccessful: false 1659 }); 1660 control.setError('root.server', err); 1661 } 1662 }, [ 1663 handleSubmit, 1664 control 1665 ]); 1666 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 1667 setMounted(true); 1668 }, []); 1669 if (render) { 1670 return render({ 1671 submit 1672 }); 1673 } 1674 // React forbids passing `method`/`encType` alongside a function `action` 1675 // (a Server-Action-style submission) -- it manages those itself and warns 1676 // if they're present, so they're only rendered for string/URL actions. 1677 return __TURBOPACK__imported__module__271645__["default"].createElement("form", { 1678 noValidate: mounted, 1679 action: action, 1680 ...!isFunction(action) && { 1681 method, 1682 encType 1683 }, 1684 onSubmit: submit, 1685 ...rest 1686 }, children); 1687} 1688const FormState = (param)=>{ 1689 let { control, disabled, exact, name, render } = param; 1690 return render(useFormState({ 1691 control, 1692 name, 1693 disabled, 1694 exact 1695 })); 1696}; 1697/** @deprecated Use `FormState` instead. Kept as an alias for backward compatibility. */ const FormStateSubscribe = FormState; 1698var createSubject = ()=>{ 1699 let _observers = []; 1700 const next = (value1)=>{ 1701 for (const observer of _observers){ 1702 observer.next && observer.next(value1); 1703 } 1704 }; 1705 const subscribe = (observer)=>{ 1706 _observers.push(observer); 1707 return { 1708 unsubscribe: ()=>{ 1709 _observers = _observers.filter((o)=>o !== observer); 1710 } 1711 }; 1712 }; 1713 const unsubscribe = ()=>{ 1714 _observers = []; 1715 }; 1716 return { 1717 get observers () { 1718 return _observers; 1719 }, 1720 next, 1721 subscribe, 1722 unsubscribe 1723 }; 1724}; 1725function extractFormValues(fieldsState, formValues) { 1726 const values = {}; 1727 for(const key in fieldsState){ 1728 if (fieldsState.hasOwnProperty(key)) { 1729 const fieldState = fieldsState[key]; 1730 const fieldValue = formValues[key]; 1731 if (fieldState && isObject(fieldState) && fieldValue) { 1732 const nestedFieldsState = extractFormValues(fieldState, fieldValue); 1733 if (isObject(nestedFieldsState)) { 1734 values[key] = nestedFieldsState; 1735 } 1736 } else if (fieldsState[key]) { 1737 values[key] = fieldValue; 1738 } 1739 } 1740 } 1741 return values; 1742} 1743const hasOwn = (value1, key)=>value1 !== null && isObjectType(value1) && Object.prototype.hasOwnProperty.call(value1, key); 1744var has = (object, path)=>{ 1745 if (!path) { 1746 return false;
1747 } 1748 let result = object; 1749 for (const key of isKey(path) ? [ 1750 path 1751 ] : stringToPath(path)){ 1752 if (!hasOwn(result, key)) { 1753 // `get` also resolves a path held as a single literal key, eg `{ 'a.b': 1 }` 1754 return hasOwn(object, path); 1755 } 1756 result = result[key]; 1757 } 1758 return true; 1759}; 1760var isMultipleSelect = (element)=>element.type === "select-multiple"; 1761var isRadioOrCheckbox = (ref)=>isRadioInput(ref) || isCheckBoxInput(ref); 1762var live = (ref)=>isHTMLElement(ref) && ref.isConnected; 1763function isDirtyContainer(value1) { 1764 return Array.isArray(value1) || isObject(value1); 1765} 1766function collectDirtyFieldNames(dirtyTree, cachedDirtyFields) { 1767 let prefix = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : '', names = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : []; 1768 for(const key in dirtyTree){ 1769 const path = prefix ? "".concat(prefix, ".").concat(key) : key; 1770 const value1 = dirtyTree[key]; 1771 if (isDirtyContainer(value1) && isDirtyContainer(get(cachedDirtyFields, path))) { 1772 collectDirtyFieldNames(value1, cachedDirtyFields, path, names); 1773 } else { 1774 names.push(path); 1775 } 1776 } 1777 return names; 1778} 1779var objectHasFunction = (data)=>{ 1780 for(const key in data){ 1781 if (isFunction(data[key])) { 1782 return true; 1783 } 1784 } 1785 return false; 1786}; 1787function isTraversable(value1) { 1788 return Array.isArray(value1) || isObject(value1) && !objectHasFunction(value1); 1789} 1790function isRegisteredLeaf(fieldRef) { 1791 return !!(fieldRef && '_f' in fieldRef); 1792} 1793function isEmptyDirtyContainer(value1) { 1794 return Array.isArray(value1) ? !value1.some((item)=>!isUndefined(item)) : !Object.keys(value1).length; 1795} 1796function clearDirtyField(container, key) { 1797 if (Array.isArray(container)) { 1798 container[key] = undefined; 1799 } else { 1800 delete container[key]; 1801 } 1802} 1803function markFieldsDirty(data) { 1804 let fields = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, fieldRefs = arguments.length > 2 ? arguments[2] : void 0; 1805 for(const key in data){ 1806 const value1 = data[key]; 1807 const fieldRef = fieldRefs && fieldRefs[key]; 1808 if (isTraversable(value1) && (!Array.isArray(value1) || !isRegisteredLeaf(fieldRef))) { 1809 fields[key] = Array.isArray(value1) ? [] : {}; 1810 markFieldsDirty(value1, fields[key], fieldRef); 1811 if (isEmptyDirtyContainer(fields[key])) { 1812 clearDirtyField(fields, key); 1813 } 1814 } else if (!isUndefined(value1)) { 1815 fields[key] = true; 1816 } 1817 } 1818 return fields; 1819} 1820function getDirtyFields(data, formValues, dirtyFieldsFromValues, fieldRefs) { 1821 if (!dirtyFieldsFromValues) { 1822 dirtyFieldsFromValues = markFieldsDirty(formValues, {}, fieldRefs); 1823 } 1824 for(const key in data){ 1825 const value1 = data[key]; 1826 const fieldRef = fieldRefs && fieldRefs[key]; 1827 if (isTraversable(value1) && (!Array.isArray(value1) || !isRegisteredLeaf(fieldRef))) { 1828 if (isUndefined(formValues) || isPrimitive(dirtyFieldsFromValues[key])) { 1829 dirtyFieldsFromValues[key] = markFieldsDirty(value1, Array.isArray(value1) ? [] : {}, fieldRef); 1830 } else { 1831 getDirtyFields(value1, isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key], fieldRef); 1832 } 1833 if (isEmptyDirtyContainer(dirtyFieldsFromValues[key])) { 1834 clearDirtyField(dirtyFieldsFromValues, key); 1835 } 1836 } else if (deepEqual(value1, formValues[key])) { 1837 clearDirtyField(dirtyFieldsFromValues, key); 1838 } else { 1839 dirtyFieldsFromValues[key] = true; 1840 } 1841 } 1842 return dirtyFieldsFromValues; 1843} 1844var getFieldArrayItemNames = (names, name)=>{ 1845 const segments = name.split('.'); 1846 const matches = []; 1847 let prefix = segments[0]; 1848 for(let i = 1; i < segments.length; prefix += '.' + segments[i++]){ 1849 if (!isNaN(+segments[i]) && names.has(prefix)) { 1850 matches.push("".concat(prefix, ".").concat(segments[i])); 1851 } 1852 } 1853 return matches; 1854}; 1855var getFieldValueAs = (value1, param)=>
1855{ 1856 let { valueAsNumber, valueAsDate, setValueAs } = param; 1857 return isUndefined(value1) ? value1 : valueAsNumber ? value1 === '' ? NaN : value1 ? +value1 : value1 : valueAsDate && isString(value1) ? new Date(value1) : setValueAs ? setValueAs(value1) : value1; 1858}; 1859function getFieldValue(_f) { 1860 const ref = _f.ref; 1861 if (isFileInput(ref)) { 1862 return ref.files; 1863 } 1864 if (isRadioInput(ref)) { 1865 return getRadioValue(_f.refs).value; 1866 } 1867 if (isMultipleSelect(ref)) { 1868 return [ 1869 ...ref.selectedOptions 1870 ].map((param)=>{ 1871 let { value: value1 } = param; 1872 return value1; 1873 }); 1874 } 1875 if (isCheckBoxInput(ref)) { 1876 return getCheckboxValue(_f.refs).value; 1877 } 1878 return getFieldValueAs(ref.value, _f); 1879} 1880var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation)=>{ 1881 const fields = {}; 1882 for (const name of fieldsNames){ 1883 const field = get(_fields, name); 1884 field && set(fields, name, field._f); 1885 } 1886 return { 1887 criteriaMode, 1888 names: [ 1889 ...fieldsNames 1890 ], 1891 fields, 1892 shouldUseNativeValidation 1893 }; 1894}; 1895var getRuleValue = (rule)=>isUndefined(rule) ? rule : isRegex(rule) ? rule.source : isObject(rule) ? isRegex(rule.value) ? rule.value.source : rule.value : rule; 1896const ASYNC_FUNCTION = 'AsyncFunction'; 1897var hasPromiseValidation = (fieldReference)=>{ 1898 if (!fieldReference || !fieldReference.validate) return false; 1899 if (isFunction(fieldReference.validate)) { 1900 return fieldReference.validate.constructor.name === ASYNC_FUNCTION; 1901 } 1902 if (isObject(fieldReference.validate)) { 1903 for(const key in fieldReference.validate){ 1904 if (fieldReference.validate[key].constructor.name === ASYNC_FUNCTION) { 1905 return true; 1906 } 1907 } 1908 } 1909 return false; 1910}; 1911var hasValidation = (options)=>options.mount && (options.required || !isUndefined(options.required) && options.required !== false || !isUndefined(options.min) || !isUndefined(options.max) || !isUndefined(options.maxLength) || !isUndefined(options.minLength) || options.pattern || options.validate); 1912function schemaErrorLookup(errors, _fields, name) { 1913 const error = get(errors, name); 1914 if ((error === null || error === void 0 ? void 0 : error.type) || (error === null || error === void 0 ? void 0 : error.message) || Array.isArray(error)) { 1915 return { 1916 error, 1917 name 1918 }; 1919 } 1920 const names = name.split('.'); 1921 while(names.length){ 1922 const fieldName = names.join('.'); 1923 const field = get(_fields, fieldName); 1924 const foundError = get(errors, fieldName); 1925 if (field && !Array.isArray(field) && name !== fieldName) { 1926 return { 1927 name 1928 }; 1929 } 1930 if (foundError && foundError.type) { 1931 return { 1932 name: fieldName, 1933 error: foundError 1934 }; 1935 } 1936 if (foundError && foundError.root && foundError.root.type) { 1937 return { 1938 name: "".concat(fieldName, ".root"), 1939 error: foundError.root 1940 }; 1941 } 1942 names.pop(); 1943 } 1944 return { 1945 name 1946 }; 1947} 1948var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot)=>{ 1949 updateFormState(formStateData); 1950 const keys = Object.keys(formStateData).filter((key)=>key !== 'name'); 1951 return !keys.length || isRoot && keys.length >= Object.keys(_proxyFormState).length || keys.find((key)=>_proxyFormState[key] === (!isRoot || VALIDATION_MODE.all)); 1952}; 1953var shouldSubscribeByName = (name, signalName, exact)=>!name || !signalName || name === signalName || convertToArrayPayload(name).some((currentName)=>currentName && (exact ? currentName === signalName || currentName.startsWith(signalName + '.') : currentName.startsWith(signalName) || signalName.startsWith(currentName))); 1954var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode)=>{ 1955 if (mode.isOnAll) { 1956 return false; 1957 } else if (!isSubmitted && mode.isOnTouch) { 1958 return !(isTouched || isBlurEvent); 1959 } else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) { 1960 return !isBlurEvent; 1961 } else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) { 1962 return isBlurEvent; 1963 } 1964 return true; 1965}; 1966var unsetEmptyArray = (ref, name)=>{ 1967 const array = get(ref, name); 1968 !compact(array).length && !(array === null || array === void 0 ? void 0 : array.root) && unset(ref, name); 1969}; 1970const defaultOptions = { 1971 mode: VALIDATION_MODE.onSubmit,
1972 reValidateMode: VALIDATION_MODE.onChange, 1973 shouldFocusError: true 1974}; 1975const FORM_ERROR_TYPE = 'form'; 1976const updateDirtyFields = (dirtyFields, nextDirtyFields)=>{ 1977 for(const key in dirtyFields){ 1978 if (!(key in nextDirtyFields)) { 1979 delete dirtyFields[key]; 1980 } 1981 } 1982 Object.assign(dirtyFields, nextDirtyFields); 1983}; 1984const DEFAULT_FORM_STATE = { 1985 submitCount: 0, 1986 isDirty: false, 1987 isReady: false, 1988 isValidating: false, 1989 isSubmitted: false, 1990 isSubmitting: false, 1991 isSubmitSuccessful: false, 1992 isValid: false, 1993 touchedFields: {}, 1994 dirtyFields: {}, 1995 validatingFields: {} 1996}; 1997function createFormControl() { 1998 let props = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; 1999 let _options = { 2000 ...defaultOptions, 2001 ...props 2002 }; 2003 let _formState = { 2004 ...cloneObject(DEFAULT_FORM_STATE), 2005 isLoading: isFunction(_options.defaultValues), 2006 errors: _options.errors || {}, 2007 disabled: _options.disabled || false 2008 }; 2009 let _fields = {}; 2010 let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values) ? cloneObject(_options.defaultValues || _options.values) || {} : {}; 2011 let _formValues = _options.shouldUnregister ? {} : cloneObject(_defaultValues); 2012 let _state = { 2013 action: false, 2014 actionArrayLengths: new Map(), 2015 mount: false, 2016 watch: false, 2017 keepIsValid: false 2018 }; 2019 let _names = { 2020 mount: new Set(), 2021 disabled: new Set(), 2022 unMount: new Set(), 2023 array: new Set(), 2024 watch: new Set(), 2025 registerName: new Set() 2026 }; 2027 const delayErrorCallbacks = {}; 2028 const timers = {}; 2029 let _valuesSubscriberCount = 0; 2030 let _validationModeBeforeSubmit = getValidationModes(_options.mode); 2031 let _validationModeAfterSubmit = getValidationModes(_options.reValidateMode); 2032 const defaultProxyFormState = { 2033 isDirty: false, 2034 dirtyFields: false, 2035 validatingFields: false, 2036 touchedFields: false, 2037 isValidating: false, 2038 isValid: false, 2039 errors: false 2040 }; 2041 const _proxyFormState = { 2042 ...defaultProxyFormState 2043 }; 2044 let _proxySubscribeFormState = { 2045 ..._proxyFormState 2046 }; 2047 const _isTracked = function() { 2048 for(var _len = arguments.length, keys = new Array(_len), _key = 0; _key < _len; _key++){ 2049 keys[_key] = arguments[_key]; 2050 } 2051 return keys.some((key)=>_proxyFormState[key] || _proxySubscribeFormState[key]); 2052 }; 2053 const _subjects = { 2054 array: createSubject(), 2055 state: createSubject() 2056 }; 2057 let _setValidCallId = 0; 2058 let _resetCallId = 0; 2059 let shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all; 2060 const debounce = (name, callback)=>(wait)=>{ 2061 clearTimeout(timers[name]); 2062 timers[name] = setTimeout(callback, wait); 2063 }; 2064 const cancelDelayedError = (name)=>{ 2065 clearTimeout(timers[name]); 2066 delete timers[name]; 2067 delete delayErrorCallbacks[name]; 2068 }; 2069 const cancelDelayedErrorTree = (name)=>{ 2070 cancelDelayedError(name); 2071 const prefix = "".concat(name, "."); 2072 for (const key of Object.keys(delayErrorCallbacks)){ 2073 key.startsWith(prefix) && cancelDelayedError(key); 2074 } 2075 }; 2076 const _setValid = async (shouldUpdateValid)=>{ 2077 if (_state.keepIsValid) { 2078 return; 2079 } 2080 if (!_options.disabled && (_isTracked('isValid') || shouldUpdateValid)) { 2081 const callId = ++_setValidCallId; 2082 let isValid; 2083 if (_options.resolver) { 2084 isValid = isEmptyObject((await _runSchema()).errors); 2085 callId === _setValidCallId && _updateIsValidating(); 2086 } else { 2087 isValid = await executeBuiltInValidation({ 2088 fields: _fields, 2089 onlyCheckValid: true, 2090 eventType: EVENTS.VALID 2091 }); 2092 } 2093 if (callId === _setValidCallId && isValid !== _formState.isValid) { 2094 _subjects.state.next({ 2095 isValid 2096 }); 2097 } 2098 } 2099 }; 2100 const _updateIsValidating = (names, isValidating)=>{ 2101 if (!_options.disabled && _isTracked('isValidating', 'validatingFields')) { 2102 (names || _names.mount).forEach((name)=>{ 2103 if (name) { 2104 isValidating ? set(_formState.validatingFields, name, isValidating) : unset(_formState.validatingFields, name); 2105 } 2106 }); 2107 _subjects.state.next({ 2108 validatingFields: _formState.validatingFields, 2109 isValidating: !isEmptyObject(_formState.validatingFields) 2110 }); 2111 } 2112 }; 2113 const _updateDirtyFields = ()=>{ 2114 _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues, undefined, _fields); 2115 }; 2116 const _setFieldArray = function(name) { 2117 let values = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [], method = arguments.length > 2 ? arguments[2] : void 0, args = arguments.length > 3 ? arguments[3] : void 0, shouldSetValues = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true, shouldUpdateFieldsAndState = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : true; 2118 if (args && method && !_options.disabled) { 2119 _state.action = true; 2120 const fields = get(_fields, name); 2121 if (!_state.actionArrayLengths.has(name)) { 2122 _state.actionArrayLengths.set(name, Array.isArray(fields) ? fields.length : 0); 2123 } 2124 if (shouldUpdateFieldsAndState && Array.isArray(fields)) { 2125 const fieldValues = method(fields, args.argA, args.argB); 2126 shouldSetValues && set(_fields, name, fieldValues); 2127 } 2128 const fieldArrayErrors = get(_formState.errors, name); 2129 if (shouldUpdateFieldsAndState && Array.isArray(fieldArrayErrors)) { 2130 const rootError = fieldArrayErrors.root; 2131 const errors = method(fieldArrayErrors, args.argA, args.argB) || fieldArrayErrors; 2132 if (rootError) { 2133 errors.root = rootError; 2134 } 2135 shouldSetValues && set(_formState.errors, name, errors); 2136 unsetEmptyArray(_formState.errors, name); 2137 } 2138 const touchedFieldsArray = get(_formState.touchedFields, name); 2139 if (_isTracked('touchedFields') && shouldUpdateFieldsAndState && Array.isArray(touchedFieldsArray)) { 2140 const touchedFields = method(touchedFieldsArray, args.argA, args.argB); 2141 shouldSetValues && set(_formState.touchedFields, name, touchedFields); 2142 } 2143 if (_isTracked('dirtyFields')) { 2144 _updateDirtyFields(); 2145 } 2146 _subjects.state.next({ 2147 name, 2148 isDirty: _getDirty(name, values), 2149 dirtyFields: _formState.dirtyFields, 2150 errors: _formState.errors, 2151 isValid: _formState.isValid 2152 }); 2153 } else { 2154 set(_formValues, name, values); 2155 } 2156 }; 2157 const updateErrors = (name, error)=>{ 2158 set(_formState.errors, name, error); 2159 _formState.errors = { 2160 ..._formState.errors 2161 }; 2162 _subjects.state.next({ 2163 errors: _formState.errors 2164 }); 2165 }; 2166 const _setErrors = (errors)=>{
2167 Object.keys(delayErrorCallbacks).forEach(cancelDelayedError); 2168 _formState.errors = errors; 2169 _subjects.state.next({ 2170 errors: _formState.errors, 2171 isValid: false 2172 }); 2173 }; 2174 const hasExplicitNullIntermediate = (name)=>{ 2175 const segments = isKey(name) ? [ 2176 name 2177 ] : stringToPath(name); 2178 let formValues = _formValues; 2179 let defaultValues = _defaultValues; 2180 for(let i = 0; i < segments.length - 1; i++){ 2181 const key = segments[i]; 2182 formValues = isNullOrUndefined(formValues) ? formValues : formValues[key]; 2183 defaultValues = isNullOrUndefined(defaultValues) ? defaultValues : defaultValues[key]; 2184 if (formValues === null && defaultValues !== null) { 2185 return true; 2186 } 2187 } 2188 return false; 2189 }; 2190 const isStaleArrayField = (name)=>{ 2191 if (!_state.actionArrayLengths.size) { 2192 return false; 2193 } 2194 const segments = isKey(name) ? [ 2195 name 2196 ] : stringToPath(name); 2197 let node = _formValues; 2198 let path = ''; 2199 let ownerDepth = -1; 2200 let ownerPreActionLength = 0; 2201 for(let i = 0; i < segments.length; i++){ 2202 if (isNullOrUndefined(node)) { 2203 return false; 2204 } 2205 const key = segments[i]; 2206 path = path ? "".concat(path, ".").concat(key) : key; 2207 if (Array.isArray(node) && +key >= node.length) { 2208 return ownerDepth === -1 ? false : i === ownerDepth ? +key < ownerPreActionLength : true; 2209 } 2210 if (_state.actionArrayLengths.has(path)) { 2211 ownerDepth = i + 1; 2212 ownerPreActionLength = _state.actionArrayLengths.get(path); 2213 } 2214 node = node[key]; 2215 if (isUndefined(node) && ownerDepth !== -1 && i > ownerDepth && +segments[ownerDepth] < ownerPreActionLength) { 2216 return true; 2217 } 2218 } 2219 return false; 2220 }; 2221 const updateValidAndValue = (name, shouldSkipSetValueAs, value1, ref)=>{ 2222 const field = get(_fields, name); 2223 if (field) { 2224 if (hasExplicitNullIntermediate(name) || isStaleArrayField(name)) { 2225 return; 2226 } 2227 const wasUnsetInFormValues = isUndefined(get(_formValues, name)); 2228 const defaultValue = get(_formValues, name, isUndefined(value1) ? get(_defaultValues, name) : value1); 2229 isUndefined(defaultValue) || ref && ref.defaultChecked || shouldSkipSetValueAs ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f)) : setFieldValue(name, defaultValue); 2230 if (_state.mount && !_state.action) { 2231 _setValid(); 2232 if (wasUnsetInFormValues && _formState.isDirty && _isTracked('isDirty')) { 2233 const isDirty = _getDirty(); 2234 if (!isDirty) { 2235 _formState.isDirty = false; 2236 _subjects.state.next({ 2237 ..._formState 2238 }); 2239 } 2240 } 2241 if (props.shouldUnregister && wasUnsetInFormValues && !isUndefined(get(_formValues, name)) && isWatched(name, _names)) { 2242 _state.watch = true; 2243 } 2244 } 2245 } 2246 }; 2247 const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender)=>{ 2248 let shouldUpdateField = false; 2249 let isPreviousDirty = false; 2250 const output = { 2251 name 2252 }; 2253 // an explicit programmatic update (e.g. setValue with shouldDirty: true) 2254 // opts into dirty tracking even when the form is disabled 2255 if (!_options.disabled || shouldDirty === true) { 2256 if (!isBlurEvent || shouldDirty) { 2257 const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue); 2258 if (_isTracked('isDirty')) { 2259 isPreviousDirty = _formState.isDirty; 2260 _formState.isDirty = output.isDirty = !isCurrentFieldPristine || _getDirty(); 2261 shouldUpdateField = isPreviousDirty !== output.isDirty; 2262 } 2263 isPreviousDirty = !!get(_formState.dirtyFields, name); 2264 if (isCurrentFieldPristine !== _formState.isDirty) { 2265 updateDirtyFields(_formState.dirtyFields, getDirtyFields(_defaultValues, _formValues, undefined, _fields)); 2266 } else { 2267 isCurrentFieldPristine ? unset(_formState.dirtyFields, name) : set(_formState.dirtyFields, name, true); 2268 } 2269 output.dirtyFields = _formState.dirtyFields; 2270 shouldUpdateField = shouldUpdateField || _isTracked('dirtyFields') && isPreviousDirty !== !isCurrentFieldPristine; 2271 } 2272 if (isBlurEvent) { 2273 const isPreviousFieldTouched = get(_formState.touchedFields, name); 2274 if (!isPreviousFieldTouched) { 2275 set(_formState.touchedFields, name, isBlurEvent); 2276 output.touchedFields = _formState.touchedFields; 2277 shouldUpdateField = shouldUpdateField || _isTracked('touchedFields') && isPreviousFieldTouched !== isBlurEvent; 2278 } 2279 } 2280 shouldUpdateField && shouldRender && _subjects.state.next(output); 2281 } 2282 return shouldUpdateField ? output : {}; 2283 }; 2284 const shouldRenderByError = (name, isValid, error, fieldState)=>{ 2285 const previousFieldError = get(_formState.errors, name); 2286 const shouldUpdateValid = _isTracked('isValid') && isBoolean(isValid) && _formState.isValid !== isValid; 2287 if (_options.delayError && error) { 2288 delayErrorCallbacks[name] = debounce(name, ()=>updateErrors(name, error)); 2289 delayErrorCallbacks[name](_options.delayError); 2290 } else { 2291 cancelDelayedError(name); 2292 error ? set(_formState.errors, name, error) : unset(_formState.errors, name); 2293 _formState.errors = { 2294 ..._formState.errors 2295 }; 2296 } 2297 if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) || !isEmptyObject(fieldState) || shouldUpdateValid) { 2298 const updatedFormState = { 2299 ...fieldState, 2300 ...shouldUpdateValid && isBoolean(isValid) ? { 2301 isValid 2302 } : {}, 2303 errors: _formState.errors, 2304 name 2305 }; 2306 _subjects.state.next(updatedFormState); 2307 } 2308 }; 2309 const _runSchema = async (name)=>{ 2310 _updateIsValidating(name, true); 2311 return await _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation)); 2312 }; 2313 const executeSchemaAndUpdateState = async (names)=>{ 2314 const resetCallId = _resetCallId; 2315 const { errors } = await _runSchema(names); 2316 if (resetCallId !== _resetCallId) { 2317 return errors; 2318 } 2319 _updateIsValidating(names); 2320 if (names) { 2321 for (const name of names){ 2322 const error = get(errors, name); 2323 cancelDelayedError(name); 2324 const isFieldArrayRootError = _names.array.has(name) && isObject(error) && !Object.keys(error).some((key)=>!Number.isNaN(Number(key))); 2325 const field = get(_fields, name); 2326 const hasNestedFields = isObject(field) && Object.keys(field).some((key)=>key !== '_f'); 2327 isFieldArrayRootError ? updateFieldArrayRootError(_formState.errors, { 2328 [name]: error 2329 }, name) : (error === null || error === void 0 ? void 0 : error.type) || (error === null || error === void 0 ? void 0 : error.message) || Array.isArray(error) || isObject(error) && hasNestedFields ? set(_formState.errors, name, error) : unset(_formState.errors, name); 2330 } 2331 _formState.errors = { 2332 ..._formState.errors 2333 }; 2334 } else {
2335 Object.keys(delayErrorCallbacks).forEach(cancelDelayedError); 2336 _formState.errors = errors; 2337 } 2338 return errors; 2339 }; 2340 const validateForm = async (param)=>{ 2341 let { name, eventType } = param; 2342 if (props.validate) { 2343 const result = await props.validate({ 2344 formValues: _formValues, 2345 formState: _formState, 2346 name, 2347 eventType 2348 }); 2349 if (isObject(result)) { 2350 for(const key in result){ 2351 const error = result[key]; 2352 if (error) { 2353 setError("".concat(FORM_ERROR_TYPE, ".").concat(key), { 2354 message: isString(error.message) ? error.message : '', 2355 type: error.type || INPUT_VALIDATION_RULES.validate 2356 }); 2357 } 2358 } 2359 } else if (isString(result) || !result) { 2360 setError(FORM_ERROR_TYPE, { 2361 message: result || '', 2362 type: INPUT_VALIDATION_RULES.validate 2363 }); 2364 } else { 2365 clearErrors(FORM_ERROR_TYPE); 2366 } 2367 return result; 2368 } 2369 return true; 2370 }; 2371 const executeBuiltInValidation = async (param)=>{ 2372 let { fields, onlyCheckValid, name, eventType, context = { 2373 valid: true, 2374 runRootValidation: false 2375 } } = param; 2376 if (props.validate) { 2377 context.runRootValidation = true; 2378 const result = await validateForm({ 2379 name, 2380 eventType 2381 }); 2382 if (!result) { 2383 context.valid = false; 2384 if (onlyCheckValid) { 2385 return context.valid; 2386 } 2387 } 2388 } 2389 for(const name in fields){ 2390 const field = fields[name]; 2391 if (field) { 2392 const { _f, ...fieldValue } = field; 2393 if (_f) { 2394 const isFieldArrayRoot = _names.array.has(_f.name); 2395 const isPromiseFunction = field._f && hasPromiseValidation(field._f); 2396 const shouldTrackIsValidatingState = _isTracked('isValidating', 'validatingFields'); 2397 if (isPromiseFunction && shouldTrackIsValidatingState) { 2398 _updateIsValidating([ 2399 _f.name 2400 ], true); 2401 } 2402 const fieldError = await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !onlyCheckValid, isFieldArrayRoot); 2403 if (isPromiseFunction && shouldTrackIsValidatingState) { 2404 _updateIsValidating([ 2405 _f.name 2406 ]); 2407 } 2408 if (fieldError[_f.name]) { 2409 context.valid = false; 2410 if (onlyCheckValid) { 2411 break; 2412 } 2413 } 2414 if (!onlyCheckValid) { 2415 cancelDelayedError(_f.name); 2416 get(fieldError, _f.name) ? isFieldArrayRoot ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name) : set(_formState.errors, _f.name, fieldError[_f.name]) : unset(_formState.errors, _f.name); 2417 } 2418 if (props.shouldUseNativeValidation && fieldError[_f.name]) { 2419 break; 2420 } 2421 } 2422 !isEmptyObject(fieldValue) && await executeBuiltInValidation({ 2423 context, 2424 onlyCheckValid, 2425 fields: fieldValue, 2426 name: name, 2427 eventType 2428 }); 2429 } 2430 } 2431 return context.valid; 2432 }; 2433 const _removeUnmounted = ()=>{ 2434 for (const name of _names.unMount){ 2435 const field = get(_fields, name); 2436 field && (field._f.refs ? field._f.refs.every((ref)=>!live(ref)) : !live(field._f.ref)) && unregister(name); 2437 } 2438 _names.unMount = new Set(); 2439 }; 2440 const _getDirty = (name, data)=>(name && data && set(_formValues, name, data), !deepEqual(_state.mount ? _formValues : _defaultValues, _defaultValues)); 2441 const _getWatch = (names, defaultValue, isGlobal)=>generateWatchOutput(names, _names, { 2442 ..._state.mount ? _formValues : isUndefined(defaultValue) || isString(names) ? _defaultValues : defaultValue 2443 }, isGlobal, defaultValue); 2444 const _getFieldArray = (name)=>compact(get(_state.mount ? _formValues : _defaultValues, name, _options.shouldUnregister ? get(_defaultValues, name, []) : [])); 2445 const setFieldValue = function(name, value1) { 2446 let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}, skipClone = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false, skipRender = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : false, skipValueRender = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : false;
2447 const field = get(_fields, name); 2448 let fieldValue = value1; 2449 if (field) { 2450 const fieldReference = field._f; 2451 if (fieldReference) { 2452 !fieldReference.disabled && set(_formValues, name, getFieldValueAs(value1, fieldReference)); 2453 fieldValue = isHTMLElement(fieldReference.ref) && isNullOrUndefined(value1) ? '' : value1; 2454 if (isMultipleSelect(fieldReference.ref)) { 2455 [ 2456 ...fieldReference.ref.options 2457 ].forEach((optionRef)=>optionRef.selected = fieldValue.includes(optionRef.value)); 2458 } else if (fieldReference.refs) { 2459 if (isCheckBoxInput(fieldReference.ref)) { 2460 fieldReference.refs.forEach((checkboxRef)=>{ 2461 if (!checkboxRef.defaultChecked || !checkboxRef.disabled) { 2462 if (Array.isArray(fieldValue)) { 2463 checkboxRef.checked = !!fieldValue.find((data)=>data === checkboxRef.value); 2464 } else { 2465 checkboxRef.checked = fieldValue === checkboxRef.value || !!fieldValue; 2466 } 2467 } 2468 }); 2469 } else { 2470 fieldReference.refs.forEach((radioRef)=>radioRef.checked = radioRef.value === fieldValue); 2471 } 2472 } else if (isFileInput(fieldReference.ref)) { 2473 fieldReference.ref.value = ''; 2474 } else { 2475 fieldReference.ref.value = fieldValue; 2476 if (!fieldReference.ref.type && !skipRender && !skipValueRender) { 2477 _subjects.state.next({ 2478 name, 2479 values: skipClone ? _formValues : cloneObject(_formValues) 2480 }); 2481 } 2482 } 2483 } 2484 } 2485 (options.shouldDirty || options.shouldTouch) && updateTouchAndDirty(name, field && field._f && !field._f.disabled && (field._f.valueAsNumber || field._f.valueAsDate || field._f.setValueAs) ? getFieldValueAs(value1, field._f) : fieldValue, options.shouldTouch, options.shouldDirty, !skipRender); 2486 options.shouldValidate && trigger(name, { 2487 delayError: options.delayError 2488 }); 2489 }; 2490 const setFieldValues = function(name, value1, options) { 2491 let skipClone = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false, skipRender = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : false, skipValueRender = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : false; 2492 if (_names.array.has(name)) { 2493 _subjects.array.next({ 2494 name, 2495 values: skipClone ? _formValues : cloneObject(_formValues) 2496 }); 2497 } 2498 for(const fieldKey in value1){ 2499 if (!value1.hasOwnProperty(fieldKey)) { 2500 continue; 2501 } 2502 const fieldValue = value1[fieldKey]; 2503 const fieldName = name + '.' + fieldKey; 2504 const field = get(_fields, fieldName); 2505 (_names.array.has(name) || isObject(fieldValue) || field && !field._f) && !isDateObject(fieldValue) ? setFieldValues(fieldName, fieldValue, options, skipClone, skipRender, skipValueRender) : setFieldValue(fieldName, fieldValue, options, skipClone, skipRender, skipValueRender); 2506 } 2507 }; 2508 const _setValue = function(name, value1, options, skipClone) { 2509 let skipStateEmit = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : false; 2510 const field = get(_fields, name); 2511 const isFieldArray = _names.array.has(name); 2512 const cloneValue = skipClone ? value1 : cloneObject(value1); 2513 const previousValue = get(_formValues, name); 2514 const isValueUnchanged = deepEqual(previousValue, cloneValue); 2515 if (!isValueUnchanged) { 2516 set(_formValues, name, cloneValue); 2517 } 2518 if (isFieldArray) { 2519 _subjects.array.next({ 2520 name, 2521 values: skipClone ? _formValues : cloneObject(_formValues) 2522 }); 2523 if (_isTracked('isDirty', 'dirtyFields') && options.shouldDirty) { 2524 _updateDirtyFields(); 2525 if (!skipStateEmit) { 2526 _subjects.state.next({ 2527 name, 2528 dirtyFields: _formState.dirtyFields, 2529 isDirty: _getDirty(name, cloneValue) 2530 }); 2531 } 2532 } 2533 } else { 2534 const isEmpty = Array.isArray(cloneValue) && !cloneValue.length || isEmptyObject(cloneValue); 2535 const skipValueRender = !isValueUnchanged && !skipStateEmit; 2536 if (!field || field._f || isNullOrUndefined(cloneValue) || isEmpty) { 2537 setFieldValue(name, cloneValue, options, skipClone, skipStateEmit, skipValueRender); 2538 } else { 2539 setFieldValues(name, cloneValue, options, skipClone, skipStateEmit, skipValueRender); 2540 } 2541 } 2542 if (!isValueUnchanged && !skipStateEmit) { 2543 const watched = isWatched(name, _names); 2544 const values = skipClone ? _formValues : cloneObject(_formValues); 2545 _subjects.state.next({ 2546 ...watched && _formState, 2547 name: _state.mount || watched ? name : undefined, 2548 values 2549 }); 2550 if (!isFieldArray) { 2551 for (const itemName of getFieldArrayItemNames(_names.array, name)){ 2552 _subjects.state.next({ 2553 name: itemName, 2554 values 2555 }); 2556 } 2557 } 2558 } 2559 }; 2560 const setValue = function(name, value1) { 2561 let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; 2562 return _setValue(name, value1, options, false); 2563 }; 2564 const setValues = function(formValues) { 2565 let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; 2566 const updatedFormValues = isFunction(formValues) ? formValues(_formValues) : formValues; 2567 if (!deepEqual(_formValues, updatedFormValues)) { 2568 _formValues = { 2569 ..._formValues, 2570 ...updatedFormValues 2571 }; 2572 for (const fieldName of _names.mount){ 2573 if (has(updatedFormValues, fieldName)) { 2574 _setValue(fieldName, get(updatedFormValues, fieldName), options, true, true); 2575 } 2576 } 2577 _subjects.state.next({ 2578 ..._formState, 2579 name: undefined, 2580 type: undefined, 2581 ..._valuesSubscriberCount ? { 2582 values: _formValues 2583 } : {} 2584 }); 2585 if (options.shouldValidate) { 2586 _setValid(); 2587 } 2588 } 2589 }; 2590 const onChange = async (event)=>{ 2591 _state.mount = true; 2592 const target = event.target; 2593 let name = target.name; 2594 let isFieldValueUpdated = true; 2595 const field = get(_fields, name); 2596 const _updateIsFieldValueUpdated = (fieldValue)=>{ 2597 isFieldValueUpdated = Number.isNaN(fieldValue) || isDateObject(fieldValue) && isNaN(fieldValue.getTime()) || deepEqual(fieldValue, get(_formValues, name, fieldValue)); 2598 }; 2599 if (field) { 2600 let error; 2601 let isValid; 2602 const fieldValue = target.type ? getFieldValue(field._f) : getEventValue(event); 2603 const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT; 2604 const hasNoValidationEffect = !hasValidation(field._f) && !props.validate && !_options.resolver && !get(_formState.errors, name) && !field._f.deps; 2605 const shouldSkipValidation = hasNoValidationEffect || skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, _validationModeAfterSubmit, _validationModeBeforeSubmit); 2606 const watched = isWatched(name, _names, isBlurEvent); 2607 set(_formValues, name, cloneObject(fieldValue)); 2608 if (isBlurEvent) { 2609 if (!target || !target.readOnly) { 2610 field._f.onBlur && field._f.onBlur(event); 2611 const pendingDelayError = delayErrorCallbacks[name]; 2612 pendingDelayError && pendingDelayError(0); 2613 } 2614 } else if (field._f.onChange) { 2615 field._f.onChange(event); 2616 } 2617 const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent); 2618 const shouldRender = !isEmptyObject(fieldState) || watched; 2619 !isBlurEvent && _subjects.state.next({ 2620 name, 2621 type: event.type, 2622 ..._valuesSubscriberCount ? { 2623 values: cloneObject(_formValues) 2624 } : {} 2625 }); 2626 if (shouldSkipValidation) { 2627 if ((!hasNoValidationEffect || !_formState.isValid) && _isTracked('isValid')) { 2628 if (_options.mode === 'onBlur') { 2629 if (isBlurEvent) { 2630 _setValid(); 2631 } 2632 } else if (!isBlurEvent) { 2633 _setValid(); 2634 } 2635 } 2636 return shouldRender && _subjects.state.next({ 2637 name, 2638 ...watched ? {} : fieldState 2639 }); 2640 } 2641 if (!_options.resolver && props.validate) { 2642 await validateForm({ 2643 name: name, 2644 eventType: event.type 2645 }); 2646 } 2647 !isBlurEvent && watched && _subjects.state.next({ 2648 ..._formState 2649 }); 2650 if (_options.resolver) { 2651 const { errors } = await _runSchema([ 2652 name 2653 ]); 2654 _updateIsValidating([ 2655 name 2656 ]); 2657 _updateIsFieldValueUpdated(fieldValue); 2658 if (!isFieldValueUpdated) { 2659 !isEmptyObject(fieldState) && _subjects.state.next(fieldState); 2660 return; 2661 } 2662 const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name); 2663 const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name); 2664 error = errorLookupResult.error; 2665 name = errorLookupResult.name; 2666 isValid = isEmptyObject(errors); 2667 } else { 2668 _updateIsValidating([ 2669 name 2670 ], true); 2671 error = (await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name]; 2672 _updateIsValidating([ 2673 name 2674 ]); 2675 _updateIsFieldValueUpdated(fieldValue); 2676 if (isFieldValueUpdated) { 2677 if (error) { 2678 isValid = false;
2679 } else if (_isTracked('isValid')) { 2680 isValid = await executeBuiltInValidation({ 2681 fields: _fields, 2682 onlyCheckValid: true, 2683 name: name, 2684 eventType: event.type 2685 }); 2686 } 2687 } 2688 } 2689 if (isFieldValueUpdated) { 2690 field._f.deps && (!Array.isArray(field._f.deps) || field._f.deps.length > 0) && trigger(field._f.deps); 2691 shouldRenderByError(name, isValid, error, fieldState); 2692 } 2693 } 2694 }; 2695 const _focusInput = (ref, key)=>{ 2696 if (get(_formState.errors, key) && ref.focus) { 2697 ref.focus(); 2698 return 1; 2699 } 2700 return; 2701 }; 2702 const trigger = async function(name) { 2703 let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; 2704 let isValid; 2705 let validationResult; 2706 const fieldNames = convertToArrayPayload(name); 2707 if (_options.resolver) { 2708 const resetCallId = _resetCallId; 2709 const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames); 2710 isValid = isEmptyObject(errors); 2711 validationResult = name ? !fieldNames.some((name)=>get(errors, name)) : isValid; 2712 if (resetCallId !== _resetCallId) { 2713 return validationResult; 2714 } 2715 } else if (name) { 2716 validationResult = (await Promise.all(fieldNames.map(async (fieldName)=>{ 2717 const field = get(_fields, fieldName); 2718 return await executeBuiltInValidation({ 2719 fields: field && field._f ? { 2720 [fieldName]: field 2721 } : field, 2722 eventType: EVENTS.TRIGGER 2723 }); 2724 }))).every(Boolean); 2725 !(!validationResult && !_formState.isValid) && _setValid(); 2726 } else { 2727 validationResult = isValid = await executeBuiltInValidation({ 2728 fields: _fields, 2729 name, 2730 eventType: EVENTS.TRIGGER 2731 }); 2732 } 2733 if (options.delayError && _options.delayError && isString(name)) { 2734 const error = get(_formState.errors, name); 2735 if (error) { 2736 unset(_formState.errors, name); 2737 delayErrorCallbacks[name] = debounce(name, ()=>updateErrors(name, error)); 2738 delayErrorCallbacks[name](_options.delayError); 2739 } else { 2740 cancelDelayedError(name); 2741 } 2742 } 2743 if (options.shouldTouch) { 2744 for (const fieldName of name ? fieldNames : _names.mount){ 2745 !_names.array.has(fieldName) && set(_formState.touchedFields, fieldName, true); 2746 } 2747 } 2748 _subjects.state.next({ 2749 ...!isString(name) || _isTracked('isValid') && isValid !== _formState.isValid ? {} : { 2750 name 2751 }, 2752 ..._options.resolver || !name ? { 2753 isValid 2754 } : {}, 2755 ...options.shouldTouch && _isTracked('touchedFields') ? { 2756 touchedFields: _formState.touchedFields 2757 } : {}, 2758 errors: _formState.errors 2759 }); 2760 options.shouldFocus && !validationResult && iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount); 2761 return validationResult; 2762 }; 2763 const getValues = (fieldNames, config)=>{ 2764 let values = { 2765 ..._state.mount ? _formValues : _defaultValues 2766 }; 2767 if (config) { 2768 values = extractFormValues(config.dirtyFields ? _formState.dirtyFields : _formState.touchedFields, values); 2769 } 2770 return isUndefined(fieldNames) ? values : isString(fieldNames) ? get(values, fieldNames) : fieldNames.map((name)=>get(values, name)); 2771 }; 2772 const getErrors = (fieldNames)=>isUndefined(fieldNames) ? { 2773 ..._formState.errors 2774 } : isString(fieldNames) ? get(_formState.errors, fieldNames) : fieldNames.map((name)=>get(_formState.errors, name)); 2775 const getFieldState = (name, formState)=>{ 2776 const targetFormState = formState || _formState; 2777 const error = get(targetFormState.errors, name); 2778 return { 2779 invalid: !!error, 2780 isDirty: !!get(targetFormState.dirtyFields, name), 2781 error, 2782 isValidating: !!get(targetFormState.validatingFields, name), 2783 isTouched: !!get(targetFormState.touchedFields, name) 2784 }; 2785 }; 2786 const clearErrors = (name)=>{ 2787 const names = name ? convertToArrayPayload(name) : undefined; 2788 if (names) {
2789 names.forEach((inputName)=>{ 2790 cancelDelayedErrorTree(inputName); 2791 unset(_formState.errors, inputName); 2792 _subjects.state.next({ 2793 name: inputName, 2794 errors: _formState.errors 2795 }); 2796 }); 2797 } else { 2798 Object.keys(delayErrorCallbacks).forEach(cancelDelayedError); 2799 _formState.errors = {}; 2800 _subjects.state.next({ 2801 errors: _formState.errors 2802 }); 2803 } 2804 }; 2805 const setError = (name, error, options)=>{ 2806 cancelDelayedError(name); 2807 const ref = (get(_fields, name, { 2808 _f: {} 2809 })._f || {}).ref; 2810 const currentError = get(_formState.errors, name) || {}; 2811 const { ref: currentRef, message, type, types, ...restOfErrorTree } = currentError; 2812 set(_formState.errors, name, { 2813 ...restOfErrorTree, 2814 ...error, 2815 ref 2816 }); 2817 _subjects.state.next({ 2818 name, 2819 errors: _formState.errors, 2820 isValid: false 2821 }); 2822 options && options.shouldFocus && ref && ref.focus && ref.focus(); 2823 }; 2824 const watch = (name, defaultValue)=>{ 2825 if (isFunction(name)) { 2826 _valuesSubscriberCount++; 2827 const { unsubscribe } = _subjects.state.subscribe({ 2828 next: (payload)=>'values' in payload && name(payload.values || _getWatch(undefined, defaultValue), payload) 2829 }); 2830 let called = false; 2831 return { 2832 unsubscribe: ()=>{ 2833 if (called) { 2834 return; 2835 } 2836 called = true; 2837 _valuesSubscriberCount--; 2838 unsubscribe(); 2839 } 2840 }; 2841 } 2842 return _getWatch(name, defaultValue, true); 2843 }; 2844 const _subscribe = (props)=>{ 2845 var _a; 2846 const needsValues = !!((_a = props.formState) === null || _a === void 0 ? void 0 : _a.values); 2847 if (needsValues) { 2848 _valuesSubscriberCount++; 2849 } 2850 const { unsubscribe } = _subjects.state.subscribe({ 2851 next: (formState)=>{ 2852 if (shouldSubscribeByName(props.name, formState.name, props.exact) && shouldRenderFormState(formState, props.formState || _proxyFormState, _setFormState, props.reRenderRoot)) { 2853 const snapshot = { 2854 ..._formValues 2855 }; 2856 props.callback({ 2857 values: snapshot, 2858 ..._formState, 2859 ...formState, 2860 defaultValues: _defaultValues 2861 }); 2862 } 2863 } 2864 }); 2865 if (!needsValues) { 2866 return unsubscribe; 2867 } 2868 let called = false; 2869 return ()=>{ 2870 if (called) { 2871 return; 2872 } 2873 called = true; 2874 _valuesSubscriberCount--; 2875 unsubscribe(); 2876 }; 2877 }; 2878 const subscribe = (props)=>{ 2879 _state.mount = true; 2880 _proxySubscribeFormState = { 2881 ..._proxySubscribeFormState, 2882 ...props.formState 2883 }; 2884 return _subscribe({ 2885 ...props, 2886 formState: { 2887 ...defaultProxyFormState, 2888 ...props.formState 2889 } 2890 }); 2891 }; 2892 const unregister = function(name) { 2893 let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; 2894 for (const fieldName of name ? convertToArrayPayload(name) : _names.mount){ 2895 _names.mount.delete(fieldName); 2896 _names.array.delete(fieldName); 2897 _names.disabled.delete(fieldName); 2898 if (!options.keepValue) { 2899 unset(_fields, fieldName); 2900 unset(_formValues, fieldName); 2901 } 2902 if (!options.keepError) { 2903 cancelDelayedErrorTree(fieldName); 2904 unset(_formState.errors, fieldName); 2905 } 2906 !options.keepDirty && unset(_formState.dirtyFields, fieldName); 2907 !options.keepTouched && unset(_formState.touchedFields, fieldName); 2908 !options.keepIsValidating && unset(_formState.validatingFields, fieldName); 2909 !_options.shouldUnregister && !options.keepDefaultValue && unset(_defaultValues, fieldName); 2910 } 2911 _valuesSubscriberCount && _subjects.state.next({ 2912 values: cloneObject(_formValues) 2913 }); 2914 _subjects.state.next({ 2915 ..._formState, 2916 ...options.keepDirty ? {} : { 2917 isDirty: _getDirty() 2918 }, 2919 ...options.keepIsValidating ? {} : { 2920 isValidating: !isEmptyObject(_formState.validatingFields) 2921 } 2922 }); 2923 !options.keepIsValid && _setValid(); 2924 }; 2925 const _setDisabledField = (param)=>{ 2926 let { disabled, name } = param; 2927 if (isBoolean(disabled) && _state.mount || !!disabled || _names.disabled.has(name)) { 2928 const wasDisabled = _names.disabled.has(name); 2929 const isDisabled = !!disabled; 2930 const disabledStateChanged = wasDisabled !== isDisabled; 2931 disabled ? _names.disabled.add(name) : _names.disabled.delete(name); 2932 disabledStateChanged && _state.mount && !_state.action && _setValid(); 2933 } 2934 }; 2935 const register = function(name) { 2936 let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; 2937 let field = get(_fields, name); 2938 const disabledIsDefined = isBoolean(options.disabled) || isBoolean(_options.disabled); 2939 const shouldRevalidateRemount = !_names.registerName.has(name) && field && field._f && !field._f.mount; 2940 set(_fields, name, { 2941 ...field || {}, 2942 _f: { 2943 ...field && field._f ? field._f : { 2944 ref: { 2945 name 2946 } 2947 }, 2948 name, 2949 mount: true, 2950 ...options 2951 } 2952 }); 2953 _names.mount.add(name); 2954 if (field && !shouldRevalidateRemount) { 2955 _setDisabledField({ 2956 disabled: isBoolean(options.disabled) ? options.disabled : _options.disabled, 2957 name 2958 }); 2959 } else {
2960 updateValidAndValue(name, true, options.value); 2961 } 2962 return { 2963 ...disabledIsDefined ? { 2964 disabled: options.disabled || _options.disabled 2965 } : {}, 2966 ..._options.progressive ? { 2967 required: !!options.required, 2968 min: getRuleValue(options.min), 2969 max: getRuleValue(options.max), 2970 minLength: getRuleValue(options.minLength), 2971 maxLength: getRuleValue(options.maxLength), 2972 pattern: getRuleValue(options.pattern) 2973 } : {}, 2974 name, 2975 onChange, 2976 onBlur: onChange, 2977 ref: (ref)=>{ 2978 if (ref) { 2979 _names.registerName.add(name); 2980 register(name, options); 2981 _names.registerName.delete(name); 2982 field = get(_fields, name); 2983 const fieldRef = isUndefined(ref.value) ? ref.querySelectorAll ? ref.querySelectorAll('input,select,textarea')[0] || ref : ref : ref; 2984 const radioOrCheckbox = isRadioOrCheckbox(fieldRef); 2985 const refs = field._f.refs || []; 2986 if (radioOrCheckbox ? refs.find((option)=>option === fieldRef) : fieldRef === field._f.ref) { 2987 return; 2988 } 2989 const newField = { 2990 ...field._f 2991 }; 2992 if (radioOrCheckbox) { 2993 newField.refs = [ 2994 ...refs.filter(live), 2995 fieldRef, 2996 ...Array.isArray(get(_defaultValues, name)) ? [ 2997 {} 2998 ] : [] 2999 ]; 3000 newField.ref = { 3001 type: fieldRef.type, 3002 name 3003 }; 3004 } else { 3005 newField.ref = fieldRef; 3006 delete newField.refs; 3007 } 3008 set(_fields, name, { 3009 _f: newField 3010 }); 3011 updateValidAndValue(name, false, undefined, fieldRef); 3012 } else { 3013 field = get(_fields, name, {}); 3014 if (field._f) { 3015 field._f.mount = false; 3016 } 3017 (_options.shouldUnregister || options.shouldUnregister) && !(isNameInFieldArray(_names.array, name) && _state.action) && _names.unMount.add(name); 3018 } 3019 } 3020 }; 3021 }; 3022 const _focusError = ()=>_options.shouldFocusError && !_options.shouldUseNativeValidation && iterateFieldsByAction(_fields, _focusInput, _names.mount); 3023 const _disableForm = (disabled)=>{ 3024 if (isBoolean(disabled)) { 3025 _subjects.state.next({ 3026 disabled 3027 }); 3028 iterateFieldsByAction(_fields, (ref, name)=>{ 3029 const currentField = get(_fields, name); 3030 if (currentField) { 3031 ref.disabled = currentField._f.disabled || disabled; 3032 if (Array.isArray(currentField._f.refs)) { 3033 currentField._f.refs.forEach((inputRef)=>{ 3034 inputRef.disabled = currentField._f.disabled || disabled; 3035 }); 3036 } 3037 } 3038 }, 0); 3039 } 3040 }; 3041 const handleSubmit = (onValid, onInvalid)=>async (e)=>{ 3042 let result = undefined; 3043 let onValidError = undefined; 3044 if (e) { 3045 e.preventDefault && e.preventDefault(); 3046 e.persist && e.persist(); 3047 } 3048 let fieldValues = cloneObject(_formValues); 3049 _subjects.state.next({ 3050 isSubmitting: true 3051 }); 3052 if (_options.resolver) { 3053 const resetCallId = _resetCallId; 3054 const { errors, values } = await _runSchema(); 3055 if (resetCallId !== _resetCallId) { 3056 return; 3057 } 3058 _updateIsValidating();
3059 Object.keys(delayErrorCallbacks).forEach(cancelDelayedError); 3060 _formState.errors = errors; 3061 fieldValues = cloneObject(values); 3062 } else { 3063 await executeBuiltInValidation({ 3064 fields: _fields, 3065 eventType: EVENTS.SUBMIT 3066 }); 3067 unset(_formState.errors, ROOT_ERROR_TYPE); 3068 } 3069 if (_names.disabled.size) { 3070 for (const name of _names.disabled){ 3071 unset(fieldValues, name); 3072 } 3073 } 3074 if (isEmptyObject(_formState.errors)) { 3075 _subjects.state.next({ 3076 errors: {} 3077 }); 3078 try { 3079 result = await onValid(fieldValues, e); 3080 } catch (error) { 3081 onValidError = error; 3082 } 3083 } else { 3084 if (onInvalid) { 3085 await onInvalid({ 3086 ..._formState.errors 3087 }, e); 3088 } 3089 _focusError(); 3090 setTimeout(_focusError); 3091 } 3092 _subjects.state.next({ 3093 isSubmitted: true, 3094 isSubmitting: false, 3095 isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError, 3096 submitCount: _formState.submitCount + 1, 3097 errors: _formState.errors 3098 }); 3099 if (onValidError) { 3100 throw onValidError; 3101 } 3102 return result; 3103 }; 3104 const resetField = function(name) { 3105 let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; 3106 if (get(_fields, name)) { 3107 unset(_formState.validatingFields, name); 3108 if (isUndefined(options.defaultValue)) { 3109 setValue(name, cloneObject(get(_defaultValues, name))); 3110 } else { 3111 setValue(name, options.defaultValue); 3112 set(_defaultValues, name, cloneObject(options.defaultValue)); 3113 } 3114 if (!options.keepTouched) { 3115 unset(_formState.touchedFields, name); 3116 } 3117 if (!options.keepDirty) { 3118 unset(_formState.dirtyFields, name); 3119 _formState.isDirty = options.defaultValue ? _getDirty(name, cloneObject(get(_defaultValues, name))) : _getDirty(); 3120 } 3121 if (!options.keepError) { 3122 cancelDelayedError(name); 3123 unset(_formState.errors, name); 3124 _setValid(); 3125 } 3126 _subjects.state.next({ 3127 ..._formState, 3128 isValidating: !isEmptyObject(_formState.validatingFields) 3129 }); 3130 } 3131 }; 3132 const _reset = function(formValues) { 3133 let keepStateOptions = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; 3134 _resetCallId++; 3135 const updatedValues = formValues ? cloneObject(formValues) : _defaultValues; 3136 const cloneUpdatedValues = cloneObject(updatedValues); 3137 const isEmptyResetValues = isEmptyObject(formValues); 3138 const values = cloneUpdatedValues; 3139 const fieldRefs = _fields;
3140 Object.keys(delayErrorCallbacks).forEach(cancelDelayedError); 3141 if (!keepStateOptions.keepDefaultValues) { 3142 _defaultValues = updatedValues; 3143 } 3144 if (!keepStateOptions.keepValues) { 3145 if (keepStateOptions.keepDirtyValues) { 3146 const fieldsToCheck = new Set([ 3147 ..._names.mount, 3148 ...collectDirtyFieldNames(getDirtyFields(_defaultValues, _formValues, undefined, fieldRefs), _formState.dirtyFields) 3149 ]); 3150 for (const fieldName of fieldsToCheck){ 3151 const isDirty = get(_formState.dirtyFields, fieldName); 3152 const existingValue = get(_formValues, fieldName); 3153 const newValue = get(values, fieldName); 3154 if (isDirty && !isUndefined(existingValue)) { 3155 set(values, fieldName, existingValue); 3156 } else if (!isDirty && !isUndefined(newValue)) { 3157 setValue(fieldName, newValue); 3158 } 3159 } 3160 } else { 3161 if (isWeb && isUndefined(formValues)) { 3162 for (const name of _names.mount){ 3163 const field = get(_fields, name); 3164 if (field && field._f) { 3165 const fieldReference = Array.isArray(field._f.refs) ? field._f.refs[0] : field._f.ref; 3166 if (isHTMLElement(fieldReference)) { 3167 const form = fieldReference.closest('form'); 3168 if (form) { 3169 form.reset(); 3170 break; 3171 } 3172 } 3173 } 3174 } 3175 } 3176 if (keepStateOptions.keepFieldsRef) { 3177 for (const fieldName of _names.mount){ 3178 setValue(fieldName, get(values, fieldName)); 3179 } 3180 } else { 3181 _fields = {}; 3182 } 3183 } 3184 if (_options.shouldUnregister) { 3185 _formValues = keepStateOptions.keepDefaultValues ? cloneObject(_defaultValues) : {}; 3186 if (keepStateOptions.keepFieldsRef) { 3187 for (const fieldName of _names.mount){ 3188 set(_formValues, fieldName, get(values, fieldName)); 3189 } 3190 } 3191 } else { 3192 _formValues = cloneObject(values); 3193 } 3194 _subjects.array.next({ 3195 values: { 3196 ...values 3197 } 3198 }); 3199 _subjects.state.next({ 3200 name: undefined, 3201 type: undefined, 3202 values: { 3203 ...values 3204 } 3205 }); 3206 } 3207 _names = { 3208 mount: keepStateOptions.keepDirtyValues ? _names.mount : new Set(), 3209 unMount: new Set(), 3210 array: new Set(), 3211 registerName: new Set(), 3212 disabled: new Set(), 3213 watch: new Set(), 3214 watchAll: false, 3215 focus: '' 3216 }; 3217 _state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid || !!keepStateOptions.keepDirtyValues || !_options.shouldUnregister && !isEmptyObject(values); 3218 _state.watch = !!_options.shouldUnregister; 3219 _state.keepIsValid = !!keepStateOptions.keepIsValid; 3220 _state.action = false; 3221 _state.actionArrayLengths.clear(); 3222 if (!keepStateOptions.keepErrors) { 3223 _formState.errors = {}; 3224 } 3225 _subjects.state.next({ 3226 submitCount: keepStateOptions.keepSubmitCount ? _formState.submitCount : 0, 3227 isDirty: isEmptyResetValues ? false : keepStateOptions.keepDirty ? _formState.isDirty : keepStateOptions.keepValues ? _getDirty() : !!(keepStateOptions.keepDefaultValues && !deepEqual(formValues, _defaultValues)), 3228 isSubmitted: keepStateOptions.keepIsSubmitted ? _formState.isSubmitted : false, 3229 dirtyFields: isEmptyResetValues ? {}
3229 : keepStateOptions.keepDirtyValues ? keepStateOptions.keepDefaultValues && _formValues ? getDirtyFields(_defaultValues, _formValues, undefined, fieldRefs) : _formState.dirtyFields : keepStateOptions.keepDefaultValues && formValues ? getDirtyFields(_defaultValues, formValues, undefined, fieldRefs) : keepStateOptions.keepDirty ? _formState.dirtyFields : keepStateOptions.keepValues ? getDirtyFields(_defaultValues, _formValues, undefined, fieldRefs) : {}, 3230 touchedFields: keepStateOptions.keepTouched ? _formState.touchedFields : {}, 3231 ...!keepStateOptions.keepIsValidating && (_formState.isValidating || !isEmptyObject(_formState.validatingFields)) ? { 3232 validatingFields: {}, 3233 isValidating: false 3234 } : null, 3235 errors: keepStateOptions.keepErrors ? _formState.errors : {}, 3236 isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful ? _formState.isSubmitSuccessful : false, 3237 isSubmitting: false, 3238 defaultValues: _defaultValues 3239 }); 3240 }; 3241 const reset = (formValues, keepStateOptions)=>_reset(isFunction(formValues) ? formValues(_formValues) : formValues, { 3242 ..._options.resetOptions, 3243 ...keepStateOptions 3244 }); 3245 const setFocus = function(name) { 3246 let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; 3247 const field = get(_fields, name); 3248 const fieldReference = field && field._f; 3249 if (fieldReference) { 3250 const fieldRef = fieldReference.refs ? fieldReference.refs[0] : fieldReference.ref; 3251 if (fieldRef.focus) { 3252 setTimeout(()=>{ 3253 fieldRef.focus(); 3254 options.shouldSelect && isFunction(fieldRef.select) && fieldRef.select(); 3255 }); 3256 } 3257 } 3258 }; 3259 const _setFormState = (updatedFormState)=>{ 3260 // `name`, `type`, and `values` describe the event that produced this 3261 // update, not the form's persisted state (they aren't part of 3262 // `FormState`). Merging them in would leak a stale `name`/`type` from 3263 // one event into a later, unrelated notification that doesn't specify 3264 // its own. 3265 const { name, type, values, ...formState } = updatedFormState; 3266 _formState = { 3267 ..._formState, 3268 ...formState 3269 }; 3270 }; 3271 _subjects.state.subscribe({ 3272 next: _setFormState 3273 }); 3274 const _resetDefaultValues = ()=>isFunction(_options.defaultValues) && _options.defaultValues().then((values)=>{ 3275 reset(values, _options.resetOptions); 3276 _subjects.state.next({ 3277 isLoading: false 3278 }); 3279 }); 3280 const resetDefaultValues = function(values) { 3281 let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; 3282 _defaultValues = cloneObject(values); 3283 if (!options.keepDirty) { 3284 const newDirtyFields = getDirtyFields(_defaultValues, _formValues, undefined, _fields); 3285 _formState.dirtyFields = newDirtyFields; 3286 _formState.isDirty = !isEmptyObject(newDirtyFields); 3287 } 3288 if (!options.keepIsValid) { 3289 _setValid(); 3290 } 3291 _subjects.state.next({ 3292 ..._formState, 3293 defaultValues: _defaultValues 3294 }); 3295 }; 3296 const methods = { 3297 control: { 3298 register, 3299 unregister, 3300 getFieldState, 3301 handleSubmit, 3302 setError, 3303 _subscribe, 3304 _runSchema, 3305 _updateIsValidating, 3306 _focusError, 3307 _getWatch, 3308 _getDirty, 3309 _setValid, 3310 _setFieldArray, 3311 _setDisabledField, 3312 _setErrors, 3313 _getFieldArray, 3314 _reset, 3315 _resetDefaultValues, 3316 _removeUnmounted, 3317 _disableForm, 3318 _subjects, 3319 _proxyFormState, 3320 get _fields () { 3321 return _fields; 3322 }, 3323 get _formValues () { 3324 return _formValues; 3325 }, 3326 get _state () { 3327 return _state; 3328 }, 3329 set _state (value){ 3330 _state = value; 3331 }, 3332 get _defaultValues () { 3333 return _defaultValues; 3334 }, 3335 get _names () { 3336 return _names; 3337 }, 3338 set _names (value){ 3339 _names = value; 3340 }, 3341 get _formState () { 3342 return _formState; 3343 }, 3344 get _options () { 3345 return _options; 3346 }, 3347 set _options (value){ 3348 _options = { 3349 ..._options, 3350 ...value 3351 }; 3352 _validationModeBeforeSubmit = getValidationModes(_options.mode); 3353 _validationModeAfterSubmit = getValidationModes(_options.reValidateMode); 3354 shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all; 3355 } 3356 }, 3357 subscribe, 3358 trigger, 3359 register, 3360 handleSubmit, 3361 watch, 3362 setValue, 3363 setValues, 3364 getValues, 3365 getErrors, 3366 reset, 3367 resetField, 3368 resetDefaultValues, 3369 clearErrors, 3370 unregister, 3371 setError, 3372 setFocus, 3373 getFieldState 3374 }; 3375 return { 3376 ...methods, 3377 formControl: methods 3378 }; 3379} 3380/** 3381 * Core hook for managing a form. Returns all methods and state for 3382 * registration, validation, and submission. 3383 * 3384 * @see [API](https://react-hook-form.com/docs/useform) 3385 * 3386 * @example 3387 * ```tsx 3388 * const { register, handleSubmit, formState: { errors } } = useForm<FormValues>(); 3389 * <form onSubmit={handleSubmit(onSubmit)}> 3390 * <input {...register("email", { required: true })} /> 3391 * </form> 3392 * ``` 3393 */ function useForm() { 3394 let props = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; 3395 const _formControl = __TURBOPACK__imported__module__271645__["default"].useRef(undefined); 3396 const _values = __TURBOPACK__imported__module__271645__["default"].useRef(undefined); 3397 const _formControlProp = __TURBOPACK__imported__module__271645__["default"].useRef(props.formControl); 3398 const [formState, updateFormState] = __TURBOPACK__imported__module__271645__["default"].useState(()=>({ 3399 ...cloneObject(DEFAULT_FORM_STATE), 3400 isLoading: isFunction(props.defaultValues), 3401 errors: props.errors || {}, 3402 disabled: props.disabled || false, 3403 defaultValues: isFunction(props.defaultValues) ? undefined : props.defaultValues 3404 })); 3405 if (!_formControl.current || props.formControl && _formControlProp.current !== props.formControl) { 3406 _formControlProp.current = props.formControl; 3407 if (props.formControl) { 3408 _formControl.current = { 3409 ...props.formControl, 3410 formState 3411 }; 3412 if (props.defaultValues && !isFunction(props.defaultValues)) { 3413 props.formControl.reset(props.defaultValues, props.resetOptions); 3414 } 3415 } else { 3416 const { formControl, ...rest } = createFormControl(props); 3417 _formControl.current = { 3418 ...rest, 3419 formState 3420 }; 3421 } 3422 } 3423 const control = _formControl.current.control; 3424 control._options = props; 3425 const getCurrentFormState = ()=>({ 3426 ...control._formState, 3427 defaultValues: control._defaultValues 3428 }); 3429 const { resyncIfNeeded, snapshot } = useResyncOnReconnect(getCurrentFormState); 3430 useIsomorphicLayoutEffect(()=>{ 3431 resyncIfNeeded(true, getCurrentFormState, updateFormState); 3432 const unsubscribe = control._subscribe({ 3433 formState: control._proxyFormState, 3434 callback: ()=>updateFormState({ 3435 ...control._formState, 3436 defaultValues: control._defaultValues 3437 }),
3438 reRenderRoot: true 3439 }); 3440 updateFormState((data)=>({ 3441 ...data, 3442 isReady: true 3443 })); 3444 control._formState.isReady = true; 3445 return ()=>{ 3446 unsubscribe(); 3447 snapshot(true, getCurrentFormState); 3448 }; 3449 }, [ 3450 control, 3451 resyncIfNeeded, 3452 snapshot 3453 ]); 3454 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>control._disableForm(props.disabled), [ 3455 control, 3456 props.disabled 3457 ]); 3458 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 3459 if (props.mode) { 3460 control._options.mode = props.mode; 3461 } 3462 if (props.reValidateMode) { 3463 control._options.reValidateMode = props.reValidateMode; 3464 } 3465 }, [ 3466 control, 3467 props.mode, 3468 props.reValidateMode 3469 ]); 3470 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 3471 if (props.errors) { 3472 control._setErrors(props.errors); 3473 control._focusError(); 3474 } 3475 }, [ 3476 control, 3477 props.errors 3478 ]); 3479 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 3480 props.shouldUnregister && control._subjects.state.next({ 3481 values: control._getWatch() 3482 }); 3483 }, [ 3484 control, 3485 props.shouldUnregister 3486 ]); 3487 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 3488 if (control._proxyFormState.isDirty) { 3489 const isDirty = control._getDirty(); 3490 if (isDirty !== formState.isDirty) { 3491 control._subjects.state.next({ 3492 isDirty 3493 }); 3494 } 3495 } 3496 }, [ 3497 control, 3498 formState.isDirty 3499 ]); 3500 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 3501 var _a; 3502 if (props.values && !deepEqual(props.values, _values.current)) { 3503 control._reset(props.values, { 3504 keepFieldsRef: true, 3505 ...control._options.resetOptions 3506 }); 3507 if (!((_a = control._options.resetOptions) === null || _a === void 0 ? void 0 : _a.keepIsValid)) { 3508 control._setValid(); 3509 } 3510 _values.current = props.values; 3511 updateFormState((state)=>({ 3512 ...state 3513 })); 3514 } else { 3515 control._resetDefaultValues(); 3516 } 3517 }, [ 3518 control, 3519 props.values 3520 ]); 3521 __TURBOPACK__imported__module__271645__["default"].useEffect(()=>{ 3522 if (!control._state.mount) { 3523 control._setValid(); 3524 control._state.mount = true; 3525 } 3526 if (control._state.watch) { 3527 control._state.watch = false; 3528 control._subjects.state.next({ 3529 ...control._formState 3530 }); 3531 } 3532 control._removeUnmounted(); 3533 }); 3534 _formControl.current.formState = __TURBOPACK__imported__module__271645__["default"].useMemo(()=>getProxyFormState(formState, control), [ 3535 control, 3536 formState 3537 ]); 3538 return _formControl.current; 3539} 3540/** 3541 * Component wrapper around `useWatch`. Re-renders only when watched fields change. 3542 * 3543 * @see [API](https://react-hook-form.com/docs/usewatch) 3544 * 3545 * @example 3546 * ```tsx 3547 * <Watch 3548 * control={control} 3549 * names={["foo", "bar"]} 3550 * render={([foo, bar]) => <span>{foo} {bar}</span>} 3551 * /> 3552 * ``` 3553 */ const Watch = (props)=>props.render(useWatch({ 3554 name: props.names, 3555 ...props 3556 })); 3557; 3558__turbopack_context__.s([ 3559 "Controller", 3560 0, 3561 Controller, 3562 "FormProvider", 3563 0, 3564 FormProvider, 3565 "appendErrors", 3566 0, 3567 appendErrors, 3568 "get", 3569 0, 3570 get, 3571 "set", 3572 0, 3573 set, 3574 "useForm", 3575 0, 3576 useForm, 3577 "useFormContext", 3578 0, 3579 useFormContext 3580]); 3581}), 3582]); 3583 3584//# debugId=59a54a1a-7878-b360-da24-54d6d600bebc
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.