@connect-soft/mui-hook-form
Version:
1,467 lines (1,375 loc) • 363 kB
JavaScript
'use strict';
var React = require('react');
var jsxRuntime = require('react/jsx-runtime');
var Box$1 = require('@mui/material/Box');
var styles = require('@mui/material/styles');
var Typography = require('@mui/material/Typography');
var MuiTab = require('@mui/material/Tab');
var MuiTabs = require('@mui/material/Tabs');
var FormControl = require('@mui/material/FormControl');
var iconsMaterial = require('@mui/icons-material');
var Collapse = require('@mui/material/Collapse');
var s$3 = require('dayjs');
var p$1 = require('dayjs/plugin/isBetween');
var b$1 = require('dayjs/plugin/timezone');
var g$1 = require('dayjs/plugin/utc');
var FormControlLabel = require('@mui/material/FormControlLabel');
var MuiCheckbox = require('@mui/material/Checkbox');
var Add = require('@mui/icons-material/Add');
var Stack = require('@mui/material/Stack');
var MuiChip = require('@mui/material/Chip');
var Popover = require('@mui/material/Popover');
var MuiButton = require('@mui/material/Button');
var MuiTextField = require('@mui/material/TextField');
var DatePicker$1 = require('@mui/x-date-pickers/DatePicker');
var FormHelperText = require('@mui/material/FormHelperText');
var FormLabel = require('@mui/material/FormLabel');
var Autocomplete = require('@mui/material/Autocomplete');
var VisibilityIcon = require('@mui/icons-material/Visibility');
var VisibilityOffIcon = require('@mui/icons-material/VisibilityOff');
var InputAdornment = require('@mui/material/InputAdornment');
var InputLabel = require('@mui/material/InputLabel');
var MuiOutlinedInput = require('@mui/material/OutlinedInput');
var MuiIconButton = require('@mui/material/IconButton');
var MuiSwitch = require('@mui/material/Switch');
var Tooltip$1 = require('@mui/material/Tooltip');
var xDatePickers = require('@mui/x-date-pickers');
var KeyboardArrowLeftIcon = require('@mui/icons-material/KeyboardArrowLeft');
var KeyboardArrowRightIcon = require('@mui/icons-material/KeyboardArrowRight');
var KeyboardDoubleArrowLeftIcon = require('@mui/icons-material/KeyboardDoubleArrowLeft');
var KeyboardDoubleArrowRightIcon = require('@mui/icons-material/KeyboardDoubleArrowRight');
var Grid = require('@mui/material/Grid');
var Divider = require('@mui/material/Divider');
var List = require('@mui/material/List');
var ListItemButton = require('@mui/material/ListItemButton');
var ListItemIcon = require('@mui/material/ListItemIcon');
var ListItemText = require('@mui/material/ListItemText');
var Paper = require('@mui/material/Paper');
var FormGroup = require('@mui/material/FormGroup');
var MuiRadioGroup = require('@mui/material/RadioGroup');
var MuiRadio = require('@mui/material/Radio');
var react = require('@emotion/react');
var AdapterDayjs = require('@mui/x-date-pickers/AdapterDayjs');
var emStyled = require('@emotion/styled');
var EditIcon = require('@mui/icons-material/EditOutlined');
var n$1 = require('zod/v4/core');
var MuiDialogActions = require('@mui/material/DialogActions');
var MuiDialog = require('@mui/material/Dialog');
var MuiDialogContent = require('@mui/material/DialogContent');
var MuiDialogTitle = require('@mui/material/DialogTitle');
var CircularProgress = require('@mui/material/CircularProgress');
var MuiDrawer = require('@mui/material/Drawer');
var MuiLinearProgress = require('@mui/material/LinearProgress');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
var n__namespace = /*#__PURE__*/_interopNamespaceDefault(n$1);
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var classnames = {exports: {}};
/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
var hasRequiredClassnames;
function requireClassnames () {
if (hasRequiredClassnames) return classnames.exports;
hasRequiredClassnames = 1;
(function (module) {
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = '';
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
classes = appendClass(classes, parseValue(arg));
}
}
return classes;
}
function parseValue (arg) {
if (typeof arg === 'string' || typeof arg === 'number') {
return arg;
}
if (typeof arg !== 'object') {
return '';
}
if (Array.isArray(arg)) {
return classNames.apply(null, arg);
}
if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
return arg.toString();
}
var classes = '';
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes = appendClass(classes, key);
}
}
return classes;
}
function appendClass (value, newClass) {
if (!newClass) {
return value;
}
if (value) {
return value + ' ' + newClass;
}
return value + newClass;
}
if (module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else {
window.classNames = classNames;
}
}());
} (classnames));
return classnames.exports;
}
var classnamesExports = requireClassnames();
var classNames = /*@__PURE__*/getDefaultExportFromCjs(classnamesExports);
var isCheckBoxInput = (element) => element.type === 'checkbox';
var isDateObject = (value) => value instanceof Date;
var isNullOrUndefined = (value) => value == null;
const isObjectType = (value) => typeof value === 'object';
var isObject = (value) => !isNullOrUndefined(value) &&
!Array.isArray(value) &&
isObjectType(value) &&
!isDateObject(value);
var getEventValue = (event) => isObject(event) && event.target
? isCheckBoxInput(event.target)
? event.target.checked
: event.target.value
: event;
var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
var isPlainObject$1 = (tempObject) => {
const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
return (isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'));
};
var isWeb = typeof window !== 'undefined' &&
typeof window.HTMLElement !== 'undefined' &&
typeof document !== 'undefined';
function cloneObject(data) {
let copy;
const isArray = Array.isArray(data);
const isFileListInstance = typeof FileList !== 'undefined' ? data instanceof FileList : false;
if (data instanceof Date) {
copy = new Date(data);
}
else if (!(isWeb && (data instanceof Blob || isFileListInstance)) &&
(isArray || isObject(data))) {
copy = isArray ? [] : Object.create(Object.getPrototypeOf(data));
if (!isArray && !isPlainObject$1(data)) {
copy = data;
}
else {
for (const key in data) {
if (data.hasOwnProperty(key)) {
copy[key] = cloneObject(data[key]);
}
}
}
}
else {
return data;
}
return copy;
}
var isKey = (value) => /^\w*$/.test(value);
var isUndefined = (val) => val === undefined;
var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));
var get = (object, path, defaultValue) => {
if (!path || !isObject(object)) {
return defaultValue;
}
const result = (isKey(path) ? [path] : stringToPath(path)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], object);
return isUndefined(result) || result === object
? isUndefined(object[path])
? defaultValue
: object[path]
: result;
};
var isBoolean = (value) => typeof value === 'boolean';
var set = (object, path, value) => {
let index = -1;
const tempPath = isKey(path) ? [path] : stringToPath(path);
const length = tempPath.length;
const lastIndex = length - 1;
while (++index < length) {
const key = tempPath[index];
let newValue = value;
if (index !== lastIndex) {
const objValue = object[key];
newValue =
isObject(objValue) || Array.isArray(objValue)
? objValue
: !isNaN(+tempPath[index + 1])
? []
: {};
}
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return;
}
object[key] = newValue;
object = object[key];
}
};
const EVENTS = {
BLUR: 'blur',
FOCUS_OUT: 'focusout',
CHANGE: 'change',
};
const VALIDATION_MODE = {
onBlur: 'onBlur',
onChange: 'onChange',
onSubmit: 'onSubmit',
onTouched: 'onTouched',
all: 'all',
};
const INPUT_VALIDATION_RULES = {
max: 'max',
min: 'min',
maxLength: 'maxLength',
minLength: 'minLength',
pattern: 'pattern',
required: 'required',
validate: 'validate',
};
const HookFormContext = React.createContext(null);
HookFormContext.displayName = 'HookFormContext';
/**
* This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. To be used with {@link FormProvider}.
*
* @remarks
* [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
*
* @returns return all useForm methods
*
* @example
* ```tsx
* function App() {
* const methods = useForm();
* const onSubmit = data => console.log(data);
*
* return (
* <FormProvider {...methods} >
* <form onSubmit={methods.handleSubmit(onSubmit)}>
* <NestedInput />
* <input type="submit" />
* </form>
* </FormProvider>
* );
* }
*
* function NestedInput() {
* const { register } = useFormContext(); // retrieve all hook methods
* return <input {...register("test")} />;
* }
* ```
*/
const useFormContext$1 = () => React.useContext(HookFormContext);
/**
* A provider component that propagates the `useForm` methods to all children components via [React Context](https://react.dev/reference/react/useContext) API. To be used with {@link useFormContext}.
*
* @remarks
* [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
*
* @param props - all useForm methods
*
* @example
* ```tsx
* function App() {
* const methods = useForm();
* const onSubmit = data => console.log(data);
*
* return (
* <FormProvider {...methods} >
* <form onSubmit={methods.handleSubmit(onSubmit)}>
* <NestedInput />
* <input type="submit" />
* </form>
* </FormProvider>
* );
* }
*
* function NestedInput() {
* const { register } = useFormContext(); // retrieve all hook methods
* return <input {...register("test")} />;
* }
* ```
*/
const FormProvider = (props) => {
const { children, ...data } = props;
return (React.createElement(HookFormContext.Provider, { value: data }, children));
};
var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
const result = {
defaultValues: control._defaultValues,
};
for (const key in formState) {
Object.defineProperty(result, key, {
get: () => {
const _key = key;
if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
}
localProxyFormState && (localProxyFormState[_key] = true);
return formState[_key];
},
});
}
return result;
};
const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
/**
* This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.
*
* @remarks
* [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
*
* @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
*
* @example
* ```tsx
* function App() {
* const { register, handleSubmit, control } = useForm({
* defaultValues: {
* firstName: "firstName"
* }});
* const { dirtyFields } = useFormState({
* control
* });
* const onSubmit = (data) => console.log(data);
*
* return (
* <form onSubmit={handleSubmit(onSubmit)}>
* <input {...register("firstName")} placeholder="First Name" />
* {dirtyFields.firstName && <p>Field is dirty.</p>}
* <input type="submit" />
* </form>
* );
* }
* ```
*/
function useFormState(props) {
const methods = useFormContext$1();
const { control = methods.control, disabled, name, exact } = props || {};
const [formState, updateFormState] = React.useState(control._formState);
const _localProxyFormState = React.useRef({
isDirty: false,
isLoading: false,
dirtyFields: false,
touchedFields: false,
validatingFields: false,
isValidating: false,
isValid: false,
errors: false,
});
useIsomorphicLayoutEffect(() => control._subscribe({
name,
formState: _localProxyFormState.current,
exact,
callback: (formState) => {
!disabled &&
updateFormState({
...control._formState,
...formState,
});
},
}), [name, disabled, exact]);
React.useEffect(() => {
_localProxyFormState.current.isValid && control._setValid(true);
}, [control]);
return React.useMemo(() => getProxyFormState(formState, control, _localProxyFormState.current, false), [formState, control]);
}
var isString = (value) => typeof value === 'string';
var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
if (isString(names)) {
isGlobal && _names.watch.add(names);
return get(formValues, names, defaultValue);
}
if (Array.isArray(names)) {
return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName),
get(formValues, fieldName)));
}
isGlobal && (_names.watchAll = true);
return formValues;
};
var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
function deepEqual(object1, object2, _internal_visited = new WeakSet()) {
if (isPrimitive(object1) || isPrimitive(object2)) {
return Object.is(object1, object2);
}
if (isDateObject(object1) && isDateObject(object2)) {
return object1.getTime() === object2.getTime();
}
const keys1 = Object.keys(object1);
const keys2 = Object.keys(object2);
if (keys1.length !== keys2.length) {
return false;
}
if (_internal_visited.has(object1) || _internal_visited.has(object2)) {
return true;
}
_internal_visited.add(object1);
_internal_visited.add(object2);
for (const key of keys1) {
const val1 = object1[key];
if (!keys2.includes(key)) {
return false;
}
if (key !== 'ref') {
const val2 = object2[key];
if ((isDateObject(val1) && isDateObject(val2)) ||
(isObject(val1) && isObject(val2)) ||
(Array.isArray(val1) && Array.isArray(val2))
? !deepEqual(val1, val2, _internal_visited)
: !Object.is(val1, val2)) {
return false;
}
}
}
return true;
}
/**
* Custom hook to subscribe to field change and isolate re-rendering at the component level.
*
* @remarks
*
* [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
*
* @example
* ```tsx
* const { control } = useForm();
* const values = useWatch({
* name: "fieldName"
* control,
* })
* ```
*/
function useWatch(props) {
const methods = useFormContext$1();
const { control = methods.control, name, defaultValue, disabled, exact, compute, } = props || {};
const _defaultValue = React.useRef(defaultValue);
const _compute = React.useRef(compute);
const _computeFormValues = React.useRef(undefined);
const _prevControl = React.useRef(control);
const _prevName = React.useRef(name);
_compute.current = compute;
const [value, updateValue] = React.useState(() => {
const defaultValue = control._getWatch(name, _defaultValue.current);
return _compute.current ? _compute.current(defaultValue) : defaultValue;
});
const getCurrentOutput = React.useCallback((values) => {
const formValues = generateWatchOutput(name, control._names, values || control._formValues, false, _defaultValue.current);
return _compute.current ? _compute.current(formValues) : formValues;
}, [control._formValues, control._names, name]);
const refreshValue = React.useCallback((values) => {
if (!disabled) {
const formValues = generateWatchOutput(name, control._names, values || control._formValues, false, _defaultValue.current);
if (_compute.current) {
const computedFormValues = _compute.current(formValues);
if (!deepEqual(computedFormValues, _computeFormValues.current)) {
updateValue(computedFormValues);
_computeFormValues.current = computedFormValues;
}
}
else {
updateValue(formValues);
}
}
}, [control._formValues, control._names, disabled, name]);
useIsomorphicLayoutEffect(() => {
if (_prevControl.current !== control ||
!deepEqual(_prevName.current, name)) {
_prevControl.current = control;
_prevName.current = name;
refreshValue();
}
return control._subscribe({
name,
formState: {
values: true,
},
exact,
callback: (formState) => {
refreshValue(formState.values);
},
});
}, [control, exact, name, refreshValue]);
React.useEffect(() => control._removeUnmounted());
// If name or control changed for this render, synchronously reflect the
// latest value so callers (like useController) see the correct value
// immediately on the same render.
// Optimize: Check control reference first before expensive deepEqual
const controlChanged = _prevControl.current !== control;
const prevName = _prevName.current;
// Cache the computed output to avoid duplicate calls within the same render
// We include shouldReturnImmediate in deps to ensure proper recomputation
const computedOutput = React.useMemo(() => {
if (disabled) {
return null;
}
const nameChanged = !controlChanged && !deepEqual(prevName, name);
const shouldReturnImmediate = controlChanged || nameChanged;
return shouldReturnImmediate ? getCurrentOutput() : null;
}, [disabled, controlChanged, name, prevName, getCurrentOutput]);
return computedOutput !== null ? computedOutput : value;
}
/**
* Custom hook to work with controlled component, this function provide you with both form and field level state. Re-render is isolated at the hook level.
*
* @remarks
* [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
*
* @param props - the path name to the form field value, and validation rules.
*
* @returns field properties, field and form state. {@link UseControllerReturn}
*
* @example
* ```tsx
* function Input(props) {
* const { field, fieldState, formState } = useController(props);
* return (
* <div>
* <input {...field} placeholder={props.name} />
* <p>{fieldState.isTouched && "Touched"}</p>
* <p>{formState.isSubmitted ? "submitted" : ""}</p>
* </div>
* );
* }
* ```
*/
function useController(props) {
const methods = useFormContext$1();
const { name, disabled, control = methods.control, shouldUnregister, defaultValue, exact = true, } = props;
const isArrayField = isNameInFieldArray(control._names.array, name);
const defaultValueMemo = React.useMemo(() => get(control._formValues, name, get(control._defaultValues, name, defaultValue)), [control, name, defaultValue]);
const value = useWatch({
control,
name,
defaultValue: defaultValueMemo,
exact,
});
const formState = useFormState({
control,
name,
exact,
});
const _props = React.useRef(props);
const _previousNameRef = React.useRef(undefined);
const _registerProps = React.useRef(control.register(name, {
...props.rules,
value,
...(isBoolean(props.disabled) ? { disabled: props.disabled } : {}),
}));
_props.current = props;
const fieldState = React.useMemo(() => Object.defineProperties({}, {
invalid: {
enumerable: true,
get: () => !!get(formState.errors, name),
},
isDirty: {
enumerable: true,
get: () => !!get(formState.dirtyFields, name),
},
isTouched: {
enumerable: true,
get: () => !!get(formState.touchedFields, name),
},
isValidating: {
enumerable: true,
get: () => !!get(formState.validatingFields, name),
},
error: {
enumerable: true,
get: () => get(formState.errors, name),
},
}), [formState, name]);
const onChange = React.useCallback((event) => _registerProps.current.onChange({
target: {
value: getEventValue(event),
name: name,
},
type: EVENTS.CHANGE,
}), [name]);
const onBlur = React.useCallback(() => _registerProps.current.onBlur({
target: {
value: get(control._formValues, name),
name: name,
},
type: EVENTS.BLUR,
}), [name, control._formValues]);
const ref = React.useCallback((elm) => {
const field = get(control._fields, name);
if (field && elm) {
field._f.ref = {
focus: () => elm.focus && elm.focus(),
select: () => elm.select && elm.select(),
setCustomValidity: (message) => elm.setCustomValidity(message),
reportValidity: () => elm.reportValidity(),
};
}
}, [control._fields, name]);
const field = React.useMemo(() => ({
name,
value,
...(isBoolean(disabled) || formState.disabled
? { disabled: formState.disabled || disabled }
: {}),
onChange,
onBlur,
ref,
}), [name, disabled, formState.disabled, onChange, onBlur, ref, value]);
React.useEffect(() => {
const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
const previousName = _previousNameRef.current;
if (previousName && previousName !== name && !isArrayField) {
control.unregister(previousName);
}
control.register(name, {
..._props.current.rules,
...(isBoolean(_props.current.disabled)
? { disabled: _props.current.disabled }
: {}),
});
const updateMounted = (name, value) => {
const field = get(control._fields, name);
if (field && field._f) {
field._f.mount = value;
}
};
updateMounted(name, true);
if (_shouldUnregisterField) {
const value = cloneObject(get(control._options.defaultValues, name, _props.current.defaultValue));
set(control._defaultValues, name, value);
if (isUndefined(get(control._formValues, name))) {
set(control._formValues, name, value);
}
}
!isArrayField && control.register(name);
_previousNameRef.current = name;
return () => {
(isArrayField
? _shouldUnregisterField && !control._state.action
: _shouldUnregisterField)
? control.unregister(name)
: updateMounted(name, false);
};
}, [name, control, isArrayField, shouldUnregister]);
React.useEffect(() => {
control._setDisabledField({
disabled,
name,
});
}, [disabled, name, control]);
return React.useMemo(() => ({
field,
formState,
fieldState,
}), [field, formState, fieldState]);
}
/**
* Component based on `useController` hook to work with controlled component.
*
* @remarks
* [API](https://react-hook-form.com/docs/usecontroller/controller) • [Demo](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) • [Video](https://www.youtube.com/watch?v=N2UNk_UCVyA)
*
* @param props - the path name to the form field value, and validation rules.
*
* @returns provide field handler functions, field and form state.
*
* @example
* ```tsx
* function App() {
* const { control } = useForm<FormValues>({
* defaultValues: {
* test: ""
* }
* });
*
* return (
* <form>
* <Controller
* control={control}
* name="test"
* render={({ field: { onChange, onBlur, value, ref }, formState, fieldState }) => (
* <>
* <input
* onChange={onChange} // send value to hook form
* onBlur={onBlur} // notify when input is touched
* value={value} // return updated value
* ref={ref} // set ref for focus management
* />
* <p>{formState.isSubmitted ? "submitted" : ""}</p>
* <p>{fieldState.isTouched ? "touched" : ""}</p>
* </>
* )}
* />
* </form>
* );
* }
* ```
*/
const Controller = (props) => props.render(useController(props));
var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria
? {
...errors[name],
types: {
...(errors[name] && errors[name].types ? errors[name].types : {}),
[type]: message || true,
},
}
: {};
var convertToArrayPayload = (value) => (Array.isArray(value) ? value : [value]);
var createSubject = () => {
let _observers = [];
const next = (value) => {
for (const observer of _observers) {
observer.next && observer.next(value);
}
};
const subscribe = (observer) => {
_observers.push(observer);
return {
unsubscribe: () => {
_observers = _observers.filter((o) => o !== observer);
},
};
};
const unsubscribe = () => {
_observers = [];
};
return {
get observers() {
return _observers;
},
next,
subscribe,
unsubscribe,
};
};
function extractFormValues(fieldsState, formValues) {
const values = {};
for (const key in fieldsState) {
if (fieldsState.hasOwnProperty(key)) {
const fieldState = fieldsState[key];
const fieldValue = formValues[key];
if (fieldState && isObject(fieldState) && fieldValue) {
const nestedFieldsState = extractFormValues(fieldState, fieldValue);
if (isObject(nestedFieldsState)) {
values[key] = nestedFieldsState;
}
}
else if (fieldsState[key]) {
values[key] = fieldValue;
}
}
}
return values;
}
var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
var isFileInput = (element) => element.type === 'file';
var isFunction = (value) => typeof value === 'function';
var isHTMLElement = (value) => {
if (!isWeb) {
return false;
}
const owner = value ? value.ownerDocument : 0;
return (value instanceof
(owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement));
};
var isMultipleSelect = (element) => element.type === `select-multiple`;
var isRadioInput = (element) => element.type === 'radio';
var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
var live = (ref) => isHTMLElement(ref) && ref.isConnected;
function baseGet(object, updatePath) {
const length = updatePath.slice(0, -1).length;
let index = 0;
while (index < length) {
object = isUndefined(object) ? index++ : object[updatePath[index++]];
}
return object;
}
function isEmptyArray(obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
return false;
}
}
return true;
}
function unset(object, path) {
const paths = Array.isArray(path)
? path
: isKey(path)
? [path]
: stringToPath(path);
const childObject = paths.length === 1 ? object : baseGet(object, paths);
const index = paths.length - 1;
const key = paths[index];
if (childObject) {
delete childObject[key];
}
if (index !== 0 &&
((isObject(childObject) && isEmptyObject(childObject)) ||
(Array.isArray(childObject) && isEmptyArray(childObject)))) {
unset(object, paths.slice(0, -1));
}
return object;
}
var objectHasFunction = (data) => {
for (const key in data) {
if (isFunction(data[key])) {
return true;
}
}
return false;
};
function isTraversable(value) {
return Array.isArray(value) || (isObject(value) && !objectHasFunction(value));
}
function markFieldsDirty(data, fields = {}) {
for (const key in data) {
const value = data[key];
if (isTraversable(value)) {
fields[key] = Array.isArray(value) ? [] : {};
markFieldsDirty(value, fields[key]);
}
else if (!isUndefined(value)) {
fields[key] = true;
}
}
return fields;
}
function getDirtyFields(data, formValues, dirtyFieldsFromValues) {
if (!dirtyFieldsFromValues) {
dirtyFieldsFromValues = markFieldsDirty(formValues);
}
for (const key in data) {
const value = data[key];
if (isTraversable(value)) {
if (isUndefined(formValues) || isPrimitive(dirtyFieldsFromValues[key])) {
dirtyFieldsFromValues[key] = markFieldsDirty(value, Array.isArray(value) ? [] : {});
}
else {
getDirtyFields(value, isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
}
}
else {
const formValue = formValues[key];
dirtyFieldsFromValues[key] = !deepEqual(value, formValue);
}
}
return dirtyFieldsFromValues;
}
const defaultResult = {
value: false,
isValid: false,
};
const validResult = { value: true, isValid: true };
var getCheckboxValue = (options) => {
if (Array.isArray(options)) {
if (options.length > 1) {
const values = options
.filter((option) => option && option.checked && !option.disabled)
.map((option) => option.value);
return { value: values, isValid: !!values.length };
}
return options[0].checked && !options[0].disabled
? // @ts-expect-error expected to work in the browser
options[0].attributes && !isUndefined(options[0].attributes.value)
? isUndefined(options[0].value) || options[0].value === ''
? validResult
: { value: options[0].value, isValid: true }
: validResult
: defaultResult;
}
return defaultResult;
};
var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value)
? value
: valueAsNumber
? value === ''
? NaN
: value
? +value
: value
: valueAsDate && isString(value)
? new Date(value)
: setValueAs
? setValueAs(value)
: value;
const defaultReturn = {
isValid: false,
value: null,
};
var getRadioValue = (options) => Array.isArray(options)
? options.reduce((previous, option) => option && option.checked && !option.disabled
? {
isValid: true,
value: option.value,
}
: previous, defaultReturn)
: defaultReturn;
function getFieldValue(_f) {
const ref = _f.ref;
if (isFileInput(ref)) {
return ref.files;
}
if (isRadioInput(ref)) {
return getRadioValue(_f.refs).value;
}
if (isMultipleSelect(ref)) {
return [...ref.selectedOptions].map(({ value }) => value);
}
if (isCheckBoxInput(ref)) {
return getCheckboxValue(_f.refs).value;
}
return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
}
var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
const fields = {};
for (const name of fieldsNames) {
const field = get(_fields, name);
field && set(fields, name, field._f);
}
return {
criteriaMode,
names: [...fieldsNames],
fields,
shouldUseNativeValidation,
};
};
var isRegex = (value) => value instanceof RegExp;
var getRuleValue = (rule) => isUndefined(rule)
? rule
: isRegex(rule)
? rule.source
: isObject(rule)
? isRegex(rule.value)
? rule.value.source
: rule.value
: rule;
var getValidationModes = (mode) => ({
isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
isOnBlur: mode === VALIDATION_MODE.onBlur,
isOnChange: mode === VALIDATION_MODE.onChange,
isOnAll: mode === VALIDATION_MODE.all,
isOnTouch: mode === VALIDATION_MODE.onTouched,
});
const ASYNC_FUNCTION = 'AsyncFunction';
var hasPromiseValidation = (fieldReference) => !!fieldReference &&
!!fieldReference.validate &&
!!((isFunction(fieldReference.validate) &&
fieldReference.validate.constructor.name === ASYNC_FUNCTION) ||
(isObject(fieldReference.validate) &&
Object.values(fieldReference.validate).find((validateFunction) => validateFunction.constructor.name === ASYNC_FUNCTION)));
var hasValidation = (options) => options.mount &&
(options.required ||
options.min ||
options.max ||
options.maxLength ||
options.minLength ||
options.pattern ||
options.validate);
var isWatched = (name, _names, isBlurEvent) => !isBlurEvent &&
(_names.watchAll ||
_names.watch.has(name) ||
[..._names.watch].some((watchName) => name.startsWith(watchName) &&
/^\.\w+/.test(name.slice(watchName.length))));
const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
for (const key of fieldsNames || Object.keys(fields)) {
const field = get(fields, key);
if (field) {
const { _f, ...currentField } = field;
if (_f) {
if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) {
return true;
}
else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) {
return true;
}
else {
if (iterateFieldsByAction(currentField, action)) {
break;
}
}
}
else if (isObject(currentField)) {
if (iterateFieldsByAction(currentField, action)) {
break;
}
}
}
}
return;
};
function schemaErrorLookup(errors, _fields, name) {
const error = get(errors, name);
if (error || isKey(name)) {
return {
error,
name,
};
}
const names = name.split('.');
while (names.length) {
const fieldName = names.join('.');
const field = get(_fields, fieldName);
const foundError = get(errors, fieldName);
if (field && !Array.isArray(field) && name !== fieldName) {
return { name };
}
if (foundError && foundError.type) {
return {
name: fieldName,
error: foundError,
};
}
if (foundError && foundError.root && foundError.root.type) {
return {
name: `${fieldName}.root`,
error: foundError.root,
};
}
names.pop();
}
return {
name,
};
}
var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
updateFormState(formStateData);
const { name, ...formState } = formStateData;
return (isEmptyObject(formState) ||
Object.keys(formState).length >= Object.keys(_proxyFormState).length ||
Object.keys(formState).find((key) => _proxyFormState[key] ===
(!isRoot || VALIDATION_MODE.all)));
};
var shouldSubscribeByName = (name, signalName, exact) => !name ||
!signalName ||
name === signalName ||
convertToArrayPayload(name).some((currentName) => currentName &&
(exact
? currentName === signalName
: currentName.startsWith(signalName) ||
signalName.startsWith(currentName)));
var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
if (mode.isOnAll) {
return false;
}
else if (!isSubmitted && mode.isOnTouch) {
return !(isTouched || isBlurEvent);
}
else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
return !isBlurEvent;
}
else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
return isBlurEvent;
}
return true;
};
var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
var updateFieldArrayRootError = (errors, error, name) => {
const fieldArrayErrors = convertToArrayPayload(get(errors, name));
set(fieldArrayErrors, 'root', error[name]);
set(errors, name, fieldArrayErrors);
return errors;
};
function getValidateError(result, ref, type = 'validate') {
if (isString(result) ||
(Array.isArray(result) && result.every(isString)) ||
(isBoolean(result) && !result)) {
return {
type,
message: isString(result) ? result : '',
ref,
};
}
}
var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)
? validationData
: {
value: validationData,
message: '',
};
var validateField = async (field, disabledFieldNames, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, } = field._f;
const inputValue = get(formValues, name);
if (!mount || disabledFieldNames.has(name)) {
return {};
}
const inputRef = refs ? refs[0] : ref;
const setCustomValidity = (message) => {
if (shouldUseNativeValidation && inputRef.reportValidity) {
inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');
inputRef.reportValidity();
}
};
const error = {};
const isRadio = isRadioInput(ref);
const isCheckBox = isCheckBoxInput(ref);
const isRadioOrCheckbox = isRadio || isCheckBox;
const isEmpty = ((valueAsNumber || isFileInput(ref)) &&
isUndefined(ref.value) &&
isUndefined(inputValue)) ||
(isHTMLElement(ref) && ref.value === '') ||
inputValue === '' ||
(Array.isArray(inputValue) && !inputValue.length);
const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
const message = exceedMax ? maxLengthMessage : minLengthMessage;
error[name] = {
type: exceedMax ? maxType : minType,
message,
ref,
...appendErrorsCurry(exceedMax ? maxType : minType, message),
};
};
if (isFieldArray
? !Array.isArray(inputValue) || !inputValue.length
: required &&
((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||
(isBoolean(inputValue) && !inputValue) ||
(isCheckBox && !getCheckboxValue(refs).isValid) ||
(isRadio && !getRadioValue(refs).isValid))) {
const { value, message } = isString(required)
? { value: !!required, message: required }
: getValueAndMessage(required);
if (value) {
error[name] = {
type: INPUT_VALIDATION_RULES.required,
message,
ref: inputRef,
...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),
};
if (!validateAllFieldCriteria) {
setCustomValidity(message);
return error;
}
}
}
if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
let exceedMax;
let exceedMin;
const maxOutput = getValueAndMessage(max);
const minOutput = getValueAndMessage(min);
if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
const valueNumber = ref.valueAsNumber ||
(inputValue ? +inputValue : inputValue);
if (!isNullOrUndefined(maxOutput.value)) {
exceedMax = valueNumber > maxOutput.value;
}
if (!isNullOrUndefined(minOutput.value)) {
exceedMin = valueNumber < minOutput.value;
}
}
else {
const valueDate = ref.valueAsDate || new Date(inputValue);
const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
const isTime = ref.type == 'time';
const isWeek = ref.type == 'week';
if (isString(maxOutput.value) && inputValue) {
exceedMax = isTime
? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)
: isWeek
? inputValue > maxOutput.value
: valueDate > new Date(maxOutput.value);
}
if (isString(minOutput.value) && inputValue) {
exceedMin = isTime
? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)
: isWeek
? inputValue < minOutput.value
: valueDate < new Date(minOutput.value);
}
}
if (exceedMax || exceedMin) {
getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
if (!validateAllFieldCriteria) {
setCustomValidity(error[name].message);
return error;
}
}
}
if ((maxLength || minLength) &&
!isEmpty &&
(isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {
const maxLengthOutput = getValueAndMessage(maxLength);
const minLengthOutput = getValueAndMessage(minLength);
const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
inputValue.length > +maxLengthOutput.value;
const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
inputValue.length < +minLengthOutput.value;
if (exceedMax || exceedMin) {
getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
if (!validateAllFieldCriteria) {
setCustomValidity(error[name].message);
return error;
}
}
}
if (pattern && !isEmpty && isString(inputValue)) {
const { value: patternValue, message } = getValueAndMessage(pattern);
if (isRegex(patternValue) && !inputValue.match(patternValue)) {
error[name] = {
type: INPUT_VALIDATION_RULES.pattern,
message,
ref,
...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),
};
if (!validateAllFieldCriteria) {
setCustomValidity(message);
return error;
}
}
}
if (validate) {
if (isFunction(validate)) {
const result = await validate(inputValue, formValues);
const validateError = getValidateError(result, inputRef);
if (validateError) {
error[name] = {
...validateError,
...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),
};
if (!validateAllFieldCriteria) {
setCustomValidity(validateError.message);
return error;
}
}
}
else if (isObject(validate)) {
let validationResult = {};
for (const key in validate) {
if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
break;
}
const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
if (validateError) {
validationResult = {
...validateError,
...appendErrorsCurry(key, validateError.message),
};
setCustomValidity(validateError.message);
if (validateAllFieldCriteria) {
error[name] = validationResult;
}
}
}
if (!isEmptyObject(validationResult)) {
error[name] = {
ref: inputRef,
...validationResult,
};
if (!validateAllFieldCriteria) {
return error;
}
}
}
}
setCustomValidity(true);
return error;
};
const defaultOptions = {
mode: VALIDATION_MODE.onSubmit,
reValidateMode: VALIDATION_MODE.onChange,
shouldFocusError: true,
};
function createFormControl(props = {}) {
let _options = {
...defaultOptions,
...props,
};
let _formState = {
submitCount: 0,
isDirty: false,
isReady: false,
isLoading: isFunction(_options.defaultValues),
isValidating: false,
isSubmitted: false,
isSubmitting: false,
isSubmitSuccessful: false,
isValid: false,
touchedFields: {},
dirtyFields: {},
validatingFields: {},
errors: _options.errors || {},
disabled: _options.disabled || false,
};
let _fields = {};
let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)
? cloneObject(_options.defaultValues || _options.values) || {}
: {};
let _formValues = _options.shouldUnregister
? {}
: cloneObject(_defaultValues);
let _state = {
action: false,
mount: false,
watch: false,
};
let _names = {
mount: new Set(),
disabled: new Set(),
unMount: new Set(),
array: new Set(),
watch: new Set(),
};
let delayErrorCallback;
let timer = 0;
const _proxyFormState = {
isDirty: false,
dirtyFields: false,
validatingFields: false,
touchedFields: false,
isValidating: false,
isValid: false,
errors: false,
};
let _proxySubscribeFormState = {
..._proxyFormState,
};
const _subjects = {
array: createSubject(),
state: createSubject(),
};
const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
const debounce = (callback) => (wait) => {
clearTimeout(timer);
timer = setTimeout(callback, wait);
};
const _setValid = async (shouldUpdateValid) => {
if (!_options.disabled &&
(_proxyFormState.isValid ||
_proxySubscribeFormState.isValid ||
shouldUpdateValid)) {
const isValid = _options.resolver
? isEmptyObject((await _runSchema()).errors)
: await executeBuiltInValidation(_fields, true);
if (isValid !== _formState.isValid) {
_subjects.state.next({
isValid,
});