@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
1,219 lines (1,218 loc) • 73.7 kB
JavaScript
"use client";
import _pushInstanceProperty from "core-js-pure/stable/instance/push.js";
import React, { useRef, useEffect, useContext, useCallback, useMemo, useReducer } from 'react';
import pointer from "../utils/json-pointer/index.js";
import { ajvErrorsToOneFormError, errorChanged, overwriteErrorMessagesWithGivenAjvKeys, extendErrorMessagesWithTranslationMessages, FormError, isZodSchema, createZodValidator, zodErrorsToOneFormError, makeAjvInstance } from "../utils/index.js";
import { Context as DataContext } from "../DataContext/index.js";
import { clearedData } from "../DataContext/Provider/Provider.js";
import FieldProviderContext from "../Field/Provider/FieldProviderContext.js";
import { combineDescribedBy, convertJsxToString, warn } from "../../../shared/component-helper.js";
import useId from "../../../shared/helpers/useId.js";
import useUpdateEffect from "../../../shared/helpers/useUpdateEffect.js";
import FieldBlockContext from "../FieldBlock/FieldBlockContext.js";
import IterateItemContext from "../Iterate/IterateItemContext.js";
import SectionContext from "../Form/Section/SectionContext.js";
import FieldBoundaryContext from "../DataContext/FieldBoundary/FieldBoundaryContext.js";
import VisibilityContext from "../Form/Visibility/VisibilityContext.js";
import WizardContext from "../Wizard/Context/index.js";
import WizardStepContext from "../Wizard/Step/StepContext.js";
import SnapshotContext from "../Form/Snapshot/SnapshotContext.js";
import useProcessManager from "./useProcessManager.js";
import usePath from "./usePath.js";
import SharedContext from "../../../shared/Context.js";
import { createReferenceKey, createSharedState, useSharedState } from "../../../shared/helpers/useSharedState.js";
import { isAsync } from "../../../shared/helpers/isAsync.js";
import useTranslation from "./useTranslation.js";
import useExternalValue from "./useExternalValue.js";
import useDataValue from "./useDataValue.js";
import { useIsomorphicLayoutEffect as useLayoutEffect } from "../../../shared/helpers/useIsomorphicLayoutEffect.js";
export default function useFieldProps(localProps, {
executeOnChangeRegardlessOfError = false,
executeOnChangeRegardlessOfUnchangedValue = false,
updateContextDataInSync = false,
omitMultiplePathWarning = false,
forceUpdateWhenContextDataIsSet = false,
omitSectionPath = false
} = {}) {
var _dataContext$props, _dataContext$props$lo, _dataContext$props2, _dataContext$props4, _localErrorRef$curren, _contextErrorRef$curr, _dataContext$internal, _dataContext$props6, _props$path, _props$autoComplete;
const {
extend
} = useContext(FieldProviderContext);
const props = extend(localProps);
const {
path: pathProp,
value: valueProp,
defaultValue,
itemPath,
emptyValue,
required: requiredProp,
disabled: disabledProp,
info: infoProp,
warning: warningProp,
error: initialErrorProp = 'initial',
errorMessages,
onStatusChange,
onFocus,
onBlur,
onChange,
onBlurValidator,
validator,
onChangeValidator: onChangeValidatorProp = validator,
exportValidators,
schema,
validateInitially,
validateUnchanged,
continuousValidation,
validateContinuously = continuousValidation,
transformIn = external => external,
transformOut = internal => internal,
toInput = value => value,
fromInput = value => value,
toEvent = value => value,
transformValue = value => value,
provideAdditionalArgs = (value, additionalArgs) => additionalArgs,
fromExternal = value => value,
validateRequired = (value, {
emptyValue,
required,
error
}) => {
if (required && (value === emptyValue || typeof emptyValue === 'undefined' && value === '')) {
return error;
}
}
} = props;
const [salt, forceUpdate] = useReducer(() => ({}), {});
const isInternalRerenderRef = useRef(undefined);
useMemo(() => {
isInternalRerenderRef.current = salt;
}, [salt]);
const {
startProcess
} = useProcessManager();
const id = useId(props.id);
const dataContext = useContext(DataContext);
const {
locale: sharedLocale
} = useContext(SharedContext) || {};
const fieldBlockContext = useContext(FieldBlockContext);
const iterateItemContext = useContext(IterateItemContext);
const sectionContext = useContext(SectionContext);
const fieldBoundaryContext = useContext(FieldBoundaryContext);
const wizardContext = useContext(WizardContext);
const wizardStepContext = useContext(WizardStepContext);
const {
setMountedField: setMountedFieldSnapshot
} = useContext(SnapshotContext) || {};
const {
isVisible,
keepInDOM
} = useContext(VisibilityContext) || {};
const handleFieldAsVisible = isVisible || keepInDOM;
const {
getValueByPath,
getSourceValue
} = useDataValue();
const translation = useTranslation();
const {
formatMessage
} = translation;
const translationRef = useRef(translation);
translationRef.current = translation;
const transformers = useRef({
transformIn,
transformOut,
provideAdditionalArgs,
toInput,
fromInput,
toEvent,
fromExternal,
transformValue,
validateRequired
});
const {
handlePathChangeUnvalidated: handlePathChangeUnvalidatedDataContext,
handlePathChange: handlePathChangeDataContext,
updateDataValue: updateDataValueDataContext,
validateData: validateDataDataContext,
setFieldState: setFieldStateDataContext,
setFieldError: setFieldErrorDataContext,
setFieldInternals: setFieldInternalsDataContext,
setFieldConnection: setFieldConnectionDataContext,
revealError: revealErrorDataContext,
setMountedFieldState: setMountedFieldStateDataContext,
getAjvInstance: getAjvInstanceDataContext,
setFieldEventListener,
errors: dataContextErrors,
showAllErrors,
contextErrorMessages,
fieldDisplayValueRef,
existingFieldsRef,
fieldInternalsRef,
mountedFieldsRef,
sectionSchemaPathsRef,
prerenderFieldProps,
hasContext: hasDataContext
} = dataContext || {};
const onChangeContext = dataContext === null || dataContext === void 0 || (_dataContext$props = dataContext.props) === null || _dataContext$props === void 0 ? void 0 : _dataContext$props.onChange;
const locale = (_dataContext$props$lo = dataContext === null || dataContext === void 0 || (_dataContext$props2 = dataContext.props) === null || _dataContext$props2 === void 0 ? void 0 : _dataContext$props2.locale) !== null && _dataContext$props$lo !== void 0 ? _dataContext$props$lo : sharedLocale;
const disabled = disabledProp !== null && disabledProp !== void 0 ? disabledProp : props.readOnly;
const inFieldBlock = Boolean(fieldBlockContext && fieldBlockContext.disableStatusSummary !== true);
const resolvedSchema = useMemo(() => {
const s = schema;
if (typeof s === 'function') {
try {
return s(props);
} catch (_) {
return undefined;
}
}
return s;
}, [schema]);
const finalSchema = useMemo(() => {
const s = resolvedSchema;
if (typeof s === 'function') {
try {
return s(props);
} catch (_) {
return undefined;
}
}
return s;
}, [resolvedSchema]);
const hasZodSchema = isZodSchema(finalSchema);
const {
setBlockRecord,
setFieldState: setFieldStateFieldBlock,
showFieldError: showFieldErrorFieldBlock,
mountedFieldsRef: mountedFieldsRefFieldBlock
} = inFieldBlock ? fieldBlockContext : {};
const {
activeIndex,
activeIndexRef,
setFieldError: setFieldErrorWizard
} = wizardContext || {};
const {
index: wizardIndex
} = wizardStepContext || {};
const {
handleChange: handleChangeIterateContext,
index: iterateIndex,
arrayValue: iterateArrayValue,
nestedIteratePath
} = iterateItemContext || {};
const {
path: sectionPath,
errorPrioritization
} = sectionContext || {};
const {
setFieldError: setFieldErrorBoundary,
revealError: revealErrorBoundary,
showBoundaryErrors
} = fieldBoundaryContext || {};
const hasPath = Boolean(pathProp);
const isParentRelativePath = typeof pathProp === 'string' && pathProp.startsWith('../');
const hasItemPath = Boolean(itemPath);
const {
path,
identifier,
makeIteratePath,
joinPath,
cleanPath
} = usePath({
id,
path: pathProp,
itemPath,
omitSectionPath
});
const sectionSchemaPaths = sectionSchemaPathsRef === null || sectionSchemaPathsRef === void 0 ? void 0 : sectionSchemaPathsRef.current;
const hasSectionSchema = Boolean((sectionSchemaPaths === null || sectionSchemaPaths === void 0 ? void 0 : sectionSchemaPaths.size) && identifier && Array.from(sectionSchemaPaths).some(sectionSchemaPath => {
if (sectionSchemaPath === '/') {
return true;
}
return identifier === sectionSchemaPath || identifier.startsWith(`${sectionSchemaPath}/`);
}));
const defaultValueRef = useRef(defaultValue);
useLayoutEffect(() => {
defaultValueRef.current = defaultValue;
}, []);
const tmpValue = useExternalValue({
path: identifier,
itemPath,
value: valueProp,
transformers,
emptyValue: defaultValue ? undefined : emptyValue
});
const externalValueDeps = tmpValue;
const externalValue = transformers.current.transformIn(tmpValue !== null && tmpValue !== void 0 ? tmpValue : defaultValueRef.current);
useEffect(() => {
var _dataContext$props3;
if (finalSchema && !hasZodSchema && !omitMultiplePathWarning && hasDataContext && !(dataContext !== null && dataContext !== void 0 && (_dataContext$props3 = dataContext.props) !== null && _dataContext$props3 !== void 0 && _dataContext$props3.ajvInstance)) {
warn(`Field${identifier ? ` (${identifier})` : ''} received a JSON Schema but no ajvInstance was provided to Form.Handler. Provide "ajvInstance" on Form.Handler.`);
}
}, [finalSchema, hasZodSchema, identifier, hasDataContext, dataContext === null || dataContext === void 0 || (_dataContext$props4 = dataContext.props) === null || _dataContext$props4 === void 0 ? void 0 : _dataContext$props4.ajvInstance, omitMultiplePathWarning]);
const valueRef = useRef(externalValue);
const changedRef = useRef();
const hasFocusRef = useRef();
const revealErrorRef = useRef(null);
const required = useMemo(() => {
if (typeof requiredProp !== 'undefined') {
return requiredProp;
}
if (schema || dataContext !== null && dataContext !== void 0 && dataContext.schema) {
const paths = identifier.split('/');
if (paths.length > 0) {
const requiredInSchema = [schema === null || schema === void 0 ? void 0 : schema['required']];
if (paths.length > 1) {
const schema = dataContext.schema;
const pathWithoutLast = paths.slice(0, -1).join('/properties/');
const schemaPart = pointer.has(schema, pathWithoutLast) ? pointer.get(schema, pathWithoutLast) : schema;
const requiredSchemaList = schemaPart === null || schemaPart === void 0 ? void 0 : schemaPart['required'];
if (Array.isArray(requiredSchemaList)) {
const rootPath = pathWithoutLast.replace(/properties\//g, '');
const requiredList = requiredSchemaList.map(path => {
path = cleanPath('/' + path);
return sectionPath && path.startsWith(sectionPath) ? path : joinPath([sectionPath || rootPath, path]);
});
_pushInstanceProperty(requiredInSchema).call(requiredInSchema, requiredList);
}
}
const collected = requiredInSchema.flatMap(value => value).filter(Boolean);
if (collected.filter(Boolean).some(path => {
path = cleanPath('/' + path);
return identifier === path || sectionPath === path;
})) {
return true;
}
}
}
}, [cleanPath, dataContext.schema, identifier, joinPath, requiredProp, schema, sectionPath]);
const getFieldByPath = useCallback(path => {
var _fieldInternalsRef$cu;
return ((_fieldInternalsRef$cu = fieldInternalsRef.current) === null || _fieldInternalsRef$cu === void 0 ? void 0 : _fieldInternalsRef$cu[path]) || {
props: undefined,
id: undefined
};
}, [fieldInternalsRef]);
const errorMessageCacheRef = useRef(new Map());
const ensureErrorMessageObject = useCallback(error => {
let key = null;
let returnValue = error;
if (typeof error === 'string') {
key = error;
returnValue = new Error(error);
} else if (error && React.isValidElement(error)) {
key = error.key || convertJsxToString(error);
returnValue = new FormError('Error', {
formattedMessage: error
});
}
if (key) {
if (errorMessageCacheRef.current.has(key)) {
return errorMessageCacheRef.current.get(key);
} else {
errorMessageCacheRef.current.set(key, returnValue);
}
}
return returnValue;
}, []);
const messageCacheRef = useRef({
isSet: false,
message: undefined
});
const executeMessage = useCallback((message, forceReturnErrorMessageObject) => {
if (typeof message === 'function') {
const ALWAYS = 4;
const INITIALLY = 8;
let currentMode = ALWAYS;
const msg = message(valueRef.current, {
conditionally: (callback, options) => {
currentMode &= ~ALWAYS;
if (options !== null && options !== void 0 && options.showInitially) {
currentMode |= INITIALLY;
}
return executeMessage(callback());
},
getValueByPath,
getFieldByPath
});
if (msg === undefined) {
messageCacheRef.current.message = undefined;
return null;
}
const isError = msg instanceof Error || msg instanceof FormError || Array.isArray(msg) && checkForError(msg);
if (!messageCacheRef.current.isSet && currentMode & INITIALLY || currentMode & ALWAYS || hasFocusRef.current === false || messageCacheRef.current.message) {
if (isInternalRerenderRef.current || currentMode & ALWAYS || !messageCacheRef.current.isSet && currentMode & INITIALLY) {
if (msg) {
messageCacheRef.current.isSet = true;
}
if (msg || !hasFocusRef.current || currentMode & ALWAYS) {
messageCacheRef.current.message = msg;
}
}
message = messageCacheRef.current.message;
if (isError && message) {
revealErrorRef.current = true;
}
if (!isError && !message) {
return null;
}
} else {
return undefined;
}
}
return forceReturnErrorMessageObject ? ensureErrorMessageObject(message) : message;
}, [getFieldByPath, getValueByPath, ensureErrorMessageObject]);
const errorProp = initialErrorProp === 'initial' ? undefined : initialErrorProp;
const error = executeMessage(errorProp, true);
const warning = executeMessage(warningProp);
const info = executeMessage(infoProp);
if (revealErrorRef.current === null) {
revealErrorRef.current = validateInitially !== null && validateInitially !== void 0 ? validateInitially : Boolean(errorProp);
}
const errorMethodRef = useRef({});
const localErrorRef = useRef();
const localErrorInitiatorRef = useRef();
const contextErrorRef = useRef();
const onChangeValidator = useMemo(() => {
if (onChangeValidatorProp) {
return onChangeValidatorProp;
}
if (validateContinuously && onBlurValidator) {
return onBlurValidator;
}
return undefined;
}, [onChangeValidatorProp, validateContinuously, onBlurValidator]);
const onChangeValidatorRef = useRef(onChangeValidator);
useUpdateEffect(() => {
onChangeValidatorRef.current = onChangeValidator;
}, [onChangeValidator]);
const onBlurValidatorRef = useRef(onBlurValidator);
useUpdateEffect(() => {
onBlurValidatorRef.current = onBlurValidator;
}, [onBlurValidator]);
const getAjvInstance = useCallback(() => {
return hasDataContext ? getAjvInstanceDataContext === null || getAjvInstanceDataContext === void 0 ? void 0 : getAjvInstanceDataContext() : makeAjvInstance();
}, [hasDataContext, getAjvInstanceDataContext]);
const schemaValidatorRef = useRef();
if (!schemaValidatorRef.current && finalSchema) {
if (hasZodSchema) {
schemaValidatorRef.current = createZodValidator(finalSchema);
} else {
var _getAjvInstance, _getAjvInstance$compi;
schemaValidatorRef.current = (_getAjvInstance = getAjvInstance()) === null || _getAjvInstance === void 0 || (_getAjvInstance$compi = _getAjvInstance.compile) === null || _getAjvInstance$compi === void 0 ? void 0 : _getAjvInstance$compi.call(_getAjvInstance, finalSchema);
}
}
const asyncBehaviorIsEnabled = useMemo(() => {
return isAsync(onChange) || isAsync(onChangeContext);
}, [onChangeContext, onChange]);
const validatedValueRef = useRef();
const changeEventResultRef = useRef(null);
const asyncProcessRef = useRef(null);
const defineAsyncProcess = useCallback(name => {
asyncProcessRef.current = name;
}, []);
const asyncBufferRef = useRef({});
for (const key in asyncBufferRef.current) {
const {
resolve,
validateProcesses
} = asyncBufferRef.current[key] || {};
if ((validateProcesses === null || validateProcesses === void 0 ? void 0 : validateProcesses()) === false) {
delete asyncBufferRef.current[key];
if (typeof resolve === 'function') {
window.requestAnimationFrame(resolve);
}
}
}
const eventPool = useRef({
onChangeValidator: null,
onBlurValidator: null,
onChangeContext: null,
onChangeLocal: null
});
const addToPool = useCallback((name, fn, runAsync) => {
if (!eventPool.current[name]) {
eventPool.current[name] = {
fn,
runAsync
};
}
}, []);
const runPool = useCallback(async (cb = null) => {
for (const key in eventPool.current) {
if (!eventPool.current[key]) {
continue;
}
const {
fn,
runAsync
} = eventPool.current[key] || {};
if (fn) {
eventPool.current[key] = null;
if (runAsync) {
await fn();
} else {
fn();
}
}
}
cb === null || cb === void 0 || cb();
}, []);
const fieldStateRef = useRef();
const setFieldState = useCallback(state => {
fieldStateRef.current = state;
setFieldStateDataContext === null || setFieldStateDataContext === void 0 || setFieldStateDataContext(identifier, resolveValidatingState(state));
setFieldStateFieldBlock === null || setFieldStateFieldBlock === void 0 || setFieldStateFieldBlock(identifier, resolveValidatingState(state));
if (!validateInitially) {
forceUpdate();
}
}, [setFieldStateDataContext, identifier, setFieldStateFieldBlock, validateInitially]);
const setErrorState = useCallback(hasError => {
setFieldErrorWizard === null || setFieldErrorWizard === void 0 || setFieldErrorWizard(wizardIndex, identifier, handleFieldAsVisible !== false ? hasError : undefined);
showFieldErrorFieldBlock === null || showFieldErrorFieldBlock === void 0 || showFieldErrorFieldBlock(identifier, hasError);
revealErrorBoundary === null || revealErrorBoundary === void 0 || revealErrorBoundary(identifier, hasError);
revealErrorDataContext === null || revealErrorDataContext === void 0 || revealErrorDataContext(identifier, hasError);
}, [identifier, handleFieldAsVisible, revealErrorBoundary, revealErrorDataContext, setFieldErrorWizard, showFieldErrorFieldBlock, wizardIndex]);
const revealError = useCallback(() => {
if (validateInitially === false && revealErrorRef.current === false) {
revealErrorRef.current = undefined;
return;
}
const hasError = Boolean(localErrorRef.current);
revealErrorRef.current = true;
setErrorState(hasError);
}, [validateInitially, setErrorState]);
const hideError = useCallback(() => {
if (revealErrorRef.current) {
revealErrorRef.current = undefined;
setErrorState(false);
}
}, [setErrorState]);
const errorMessagesCacheRef = useRef({
locale: null,
errorMessages: null,
extendedErrorMessages: null
});
const combinedErrorMessages = useMemo(() => {
const cache = errorMessagesCacheRef.current;
if (cache.locale === locale && errorMessages && cache.extendedErrorMessages && Object.values(cache.errorMessages || {}).join('') === Object.values(errorMessages || {}).join('')) {
return cache.extendedErrorMessages;
}
const messages = {
...contextErrorMessages,
...(contextErrorMessages === null || contextErrorMessages === void 0 ? void 0 : contextErrorMessages[identifier]),
...errorMessages
};
const extendedErrorMessages = extendErrorMessagesWithTranslationMessages(overwriteErrorMessagesWithGivenAjvKeys(messages), translationRef.current);
errorMessagesCacheRef.current = {
locale,
errorMessages,
extendedErrorMessages
};
return extendedErrorMessages;
}, [contextErrorMessages, errorMessages, identifier, locale]);
const prepareError = useCallback(error => {
const prepare = error => {
if (error instanceof FormError) {
let message = error.message;
const {
ajvKeyword
} = error;
if (typeof ajvKeyword === 'string') {
const ajvMessage = combinedErrorMessages === null || combinedErrorMessages === void 0 ? void 0 : combinedErrorMessages[ajvKeyword];
if (ajvMessage) {
message = ajvMessage;
}
}
const {
validationRule
} = error;
if (typeof validationRule === 'string') {
const ajvMessage = combinedErrorMessages === null || combinedErrorMessages === void 0 ? void 0 : combinedErrorMessages[validationRule];
if (ajvMessage) {
message = ajvMessage;
}
}
if (combinedErrorMessages !== null && combinedErrorMessages !== void 0 && combinedErrorMessages[message]) {
message = combinedErrorMessages === null || combinedErrorMessages === void 0 ? void 0 : combinedErrorMessages[message];
if (error.messageValues) {
message = Object.entries(error.messageValues || {}).reduce((msg, [key, value]) => {
return msg.replace(`{${key}}`, value);
}, message);
}
} else if (message.includes('.')) {
message = formatMessage(message, error.messageValues);
}
if (React.isValidElement(message)) {
error.formattedMessage = message;
} else {
error.message = message;
}
}
return ensureErrorMessageObject(error);
};
if (Array.isArray(error)) {
return new FormError('Error', {
errors: error.map(prepare)
});
}
if (error instanceof FormError) {
if (Array.isArray(error.errors)) {
error.errors = error.errors.map(prepare);
return error;
}
return prepare(error);
}
return error;
}, [combinedErrorMessages, ensureErrorMessageObject, formatMessage]);
contextErrorRef.current = useMemo(() => {
const dataContextError = dataContextErrors === null || dataContextErrors === void 0 ? void 0 : dataContextErrors[identifier];
if (!dataContextError) {
return undefined;
}
const error = prepareError(dataContextError);
if (errorChanged(error, contextErrorRef.current)) {
return error;
}
return contextErrorRef.current;
}, [dataContextErrors, identifier, prepareError]);
if (((_localErrorRef$curren = localErrorRef.current) === null || _localErrorRef$curren === void 0 ? void 0 : _localErrorRef$curren['ajvKeyword']) === 'type' || ((_contextErrorRef$curr = contextErrorRef.current) === null || _contextErrorRef$curr === void 0 ? void 0 : _contextErrorRef$curr['ajvKeyword']) === 'type') {
revealErrorRef.current = true;
}
const getBufferedError = useCallback(() => {
if (initialErrorProp !== 'initial' && typeof errorProp !== 'function') {
return prepareError(errorProp);
} else if (revealErrorRef.current) {
var _contextErrorRef$curr2, _ref, _prepareError;
if (((_contextErrorRef$curr2 = contextErrorRef.current) === null || _contextErrorRef$curr2 === void 0 ? void 0 : _contextErrorRef$curr2['ajvKeyword']) === 'type') {
return contextErrorRef.current;
}
return (_ref = (_prepareError = prepareError(error)) !== null && _prepareError !== void 0 ? _prepareError : localErrorRef.current) !== null && _ref !== void 0 ? _ref : contextErrorRef.current;
} else if (error === null) {
return null;
}
}, [error, errorProp, initialErrorProp, prepareError]);
const bufferedError = getBufferedError();
const bufferedErrorRef = useRef(bufferedError);
bufferedErrorRef.current = bufferedError;
const errorIsVisible = Boolean(bufferedError) || inFieldBlock && fieldBlockContext.hasErrorProp;
const hasError = useCallback(() => {
var _ref2;
return Boolean((_ref2 = error !== null && error !== void 0 ? error : localErrorRef.current) !== null && _ref2 !== void 0 ? _ref2 : contextErrorRef.current);
}, [error]);
const connectWithPathListenerRef = useRef(() => {
runOnChangeValidator();
runOnBlurValidator();
});
const handleConnectWithPath = useCallback(path => {
setFieldEventListener === null || setFieldEventListener === void 0 || setFieldEventListener(path, 'onPathChange', connectWithPathListenerRef.current);
return {
getValue: () => getValueByPath(path)
};
}, [getValueByPath, setFieldEventListener]);
const additionalArgsRef = useRef({
validators: exportValidators,
props,
dataContext,
getValueByPath,
getSourceValue,
setFieldEventListener
});
additionalArgsRef.current.validators = exportValidators;
additionalArgsRef.current.props = props;
const additionalArgs = useMemo(() => {
const args = {
...combinedErrorMessages,
errorMessages: combinedErrorMessages,
...additionalArgsRef.current,
connectWithPath: path => {
return handleConnectWithPath(path);
},
connectWithItemPath: itemPath => {
return handleConnectWithPath(makeIteratePath(itemPath));
}
};
return args;
}, [combinedErrorMessages, handleConnectWithPath, makeIteratePath]);
const callStackRef = useRef([]);
const hasBeenCalledRef = useCallback(validator => {
var _context;
const result = callStackRef.current.includes(validator);
_pushInstanceProperty(_context = callStackRef.current).call(_context, validator);
return result;
}, []);
const callValidatorFnAsync = useCallback(async (validator, value = valueRef.current) => {
if (typeof validator !== 'function') {
return;
}
const result = await validator(value, additionalArgs);
if (Array.isArray(result)) {
const errors = [];
for (const validatorOrError of result) {
if (validatorOrError instanceof Error) {
_pushInstanceProperty(errors).call(errors, validatorOrError);
} else if (!hasBeenCalledRef(validatorOrError)) {
const result = await callValidatorFnAsync(validatorOrError, value);
if (result instanceof Error) {
callStackRef.current = [];
return result;
}
}
}
if (errors.length > 0) {
return new FormError('Error', {
errors
});
}
callStackRef.current = [];
} else {
return ensureErrorMessageObject(result);
}
}, [additionalArgs, hasBeenCalledRef, ensureErrorMessageObject]);
const callValidatorFnSync = useCallback((validator, value = valueRef.current) => {
if (typeof validator !== 'function') {
return;
}
const result = validator(value, additionalArgs);
if (Array.isArray(result)) {
const hasAsyncValidator = result.some(validator => isAsync(validator));
if (hasAsyncValidator) {
return new Promise(resolve => {
callValidatorFnAsync(validator, value).then(result => {
resolve(result);
});
});
}
const errors = [];
for (const validatorOrError of result) {
if (validatorOrError instanceof Error) {
_pushInstanceProperty(errors).call(errors, validatorOrError);
} else if (!hasBeenCalledRef(validatorOrError)) {
const result = callValidatorFnSync(validatorOrError, value);
if (result instanceof Error) {
callStackRef.current = [];
return result;
}
}
}
if (errors.length > 0) {
return new FormError('Error', {
errors
});
}
callStackRef.current = [];
} else {
return ensureErrorMessageObject(result);
}
}, [additionalArgs, callValidatorFnAsync, hasBeenCalledRef, ensureErrorMessageObject]);
const stateId = useId();
const persistErrorState = useCallback((method, initiator, errorArg = undefined) => {
var _errorMethodRef$curre, _errorMethodRef$curre2;
const error = prepareError(errorArg);
if (!errorChanged(error, localErrorRef.current)) {
return;
}
if (initiator !== 'dataContextError') {
localErrorInitiatorRef.current = initiator;
}
if (method === 'wipe') {
errorMethodRef.current = {};
} else {
errorMethodRef.current[method] = error;
}
if (!error && method === 'gracefully' && ((_errorMethodRef$curre = errorMethodRef.current) !== null && _errorMethodRef$curre !== void 0 && _errorMethodRef$curre.weak || (_errorMethodRef$curre2 = errorMethodRef.current) !== null && _errorMethodRef$curre2 !== void 0 && _errorMethodRef$curre2.gracefully)) {
return;
}
const currentError = handleFieldAsVisible !== false ? error : undefined;
localErrorRef.current = currentError;
setFieldErrorDataContext === null || setFieldErrorDataContext === void 0 || setFieldErrorDataContext(identifier, currentError);
setFieldErrorBoundary === null || setFieldErrorBoundary === void 0 || setFieldErrorBoundary(identifier, currentError);
setBlockRecord === null || setBlockRecord === void 0 || setBlockRecord({
stateId,
identifier,
type: 'error',
content: currentError,
showInitially: Boolean(inFieldBlock && validateInitially)
});
setFieldStateDataContext === null || setFieldStateDataContext === void 0 || setFieldStateDataContext(identifier, error ? 'error' : undefined);
if (updateContextDataInSync && !prerenderFieldProps) {
setFieldErrorWizard === null || setFieldErrorWizard === void 0 || setFieldErrorWizard(wizardIndex, identifier, Boolean(currentError));
}
forceUpdate();
}, [handleFieldAsVisible, identifier, inFieldBlock, prepareError, prerenderFieldProps, setBlockRecord, setFieldErrorBoundary, setFieldErrorDataContext, setFieldErrorWizard, setFieldStateDataContext, stateId, updateContextDataInSync, validateInitially, wizardIndex]);
const clearErrorState = useCallback(() => {
persistErrorState('wipe', undefined);
localErrorInitiatorRef.current = undefined;
const schemaValidator = schemaValidatorRef.current;
if (schemaValidator && !hasZodSchema && Array.isArray(schemaValidator === null || schemaValidator === void 0 ? void 0 : schemaValidator.errors)) {
schemaValidator.errors = [];
}
}, [persistErrorState, hasZodSchema]);
const setChanged = useCallback(state => {
changedRef.current = state;
}, []);
const validatorCacheRef = useRef({
onChangeValidator: null,
onBlurValidator: null
});
const revealOnChangeValidatorResult = useCallback(({
result,
unchangedValue
}) => {
const runAsync = isAsync(onChangeValidatorRef.current);
if (unchangedValue) {
persistErrorState(runAsync ? 'gracefully' : 'weak', 'onChangeValidator', result);
if (validateInitially && !changedRef.current || validateUnchanged || validateContinuously || runAsync) {
window.requestAnimationFrame(() => {
if (localErrorInitiatorRef.current === 'onChangeValidator') {
revealError();
forceUpdate();
}
});
}
}
if (runAsync) {
defineAsyncProcess(undefined);
if (unchangedValue) {
setFieldState(result instanceof Error ? 'error' : 'complete');
} else {
setFieldState('pending');
}
}
}, [validateContinuously, defineAsyncProcess, persistErrorState, revealError, setFieldState, validateInitially, validateUnchanged]);
const callOnChangeValidator = useCallback(async () => {
if (typeof onChangeValidatorRef.current !== 'function') {
return {};
}
const tmpValue = valueRef.current;
let result = isAsync(onChangeValidatorRef.current) ? await callValidatorFnAsync(onChangeValidatorRef.current) : callValidatorFnSync(onChangeValidatorRef.current);
if (result instanceof Promise) {
result = await result;
}
const unchangedValue = tmpValue === valueRef.current;
return {
result,
unchangedValue
};
}, [callValidatorFnAsync, callValidatorFnSync]);
const startOnChangeValidatorValidation = useCallback(async () => {
if (typeof onChangeValidatorRef.current !== 'function') {
return;
}
if (isAsync(onChangeValidatorRef.current)) {
defineAsyncProcess('onChangeValidator');
setFieldState('validating');
hideError();
}
const tmpValue = valueRef.current;
let result = isAsync(onChangeValidatorRef.current) ? await callValidatorFnAsync(onChangeValidatorRef.current) : callValidatorFnSync(onChangeValidatorRef.current);
if (result instanceof Promise) {
result = await result;
}
const unchangedValue = tmpValue === valueRef.current;
revealOnChangeValidatorResult({
result,
unchangedValue
});
return {
result
};
}, [callValidatorFnAsync, callValidatorFnSync, defineAsyncProcess, hideError, revealOnChangeValidatorResult, setFieldState]);
const runOnChangeValidator = useCallback(async () => {
if (!onChangeValidatorRef.current) {
return;
}
const {
result,
unchangedValue
} = await callOnChangeValidator();
if (String(result) !== String(validatorCacheRef.current.onChangeValidator)) {
if (result) {
revealOnChangeValidatorResult({
result,
unchangedValue
});
} else {
hideError();
clearErrorState();
}
}
validatorCacheRef.current.onChangeValidator = result || null;
}, [callOnChangeValidator, clearErrorState, hideError, revealOnChangeValidatorResult]);
const callOnBlurValidator = useCallback(async ({
overrideValue = null
} = {}) => {
if (typeof onBlurValidatorRef.current !== 'function') {
return {};
}
const value = transformers.current.toEvent(overrideValue !== null && overrideValue !== void 0 ? overrideValue : valueRef.current, 'onBlurValidator');
let result = isAsync(onBlurValidatorRef.current) ? await callValidatorFnAsync(onBlurValidatorRef.current, value) : callValidatorFnSync(onBlurValidatorRef.current, value);
if (result instanceof Promise) {
result = await result;
}
return {
result
};
}, [callValidatorFnAsync, callValidatorFnSync]);
const revealOnBlurValidatorResult = useCallback(({
result
}) => {
persistErrorState('gracefully', 'onBlurValidator', result);
if (isAsync(onBlurValidatorRef.current)) {
defineAsyncProcess(undefined);
setFieldState(result instanceof Error ? 'error' : 'complete');
}
revealError();
}, [defineAsyncProcess, persistErrorState, revealError, setFieldState]);
const startOnBlurValidatorProcess = useCallback(async ({
overrideValue = null
} = {}) => {
if (typeof onBlurValidatorRef.current !== 'function') {
return;
}
if ((localErrorInitiatorRef.current === 'required' || localErrorInitiatorRef.current === 'schema') && !asyncBehaviorIsEnabled && !isAsync(onChangeValidatorRef.current)) {
return;
}
if (isAsync(onBlurValidatorRef.current)) {
defineAsyncProcess('onBlurValidator');
setFieldState('validating');
}
const value = transformers.current.toEvent(overrideValue !== null && overrideValue !== void 0 ? overrideValue : valueRef.current, 'onBlurValidator');
let result = isAsync(onBlurValidatorRef.current) ? await callValidatorFnAsync(onBlurValidatorRef.current, value) : callValidatorFnSync(onBlurValidatorRef.current, value);
if (result instanceof Promise) {
result = await result;
}
revealOnBlurValidatorResult({
result
});
return {
result
};
}, [asyncBehaviorIsEnabled, callValidatorFnAsync, callValidatorFnSync, defineAsyncProcess, revealOnBlurValidatorResult, setFieldState]);
const runOnBlurValidator = useCallback(async () => {
if (!onBlurValidatorRef.current) {
return;
}
const {
result
} = await callOnBlurValidator();
if (String(result) !== String(validatorCacheRef.current.onBlurValidator) && revealErrorRef.current) {
if (result) {
revealOnBlurValidatorResult({
result
});
} else {
hideError();
clearErrorState();
}
}
validatorCacheRef.current.onBlurValidator = result || null;
}, [callOnBlurValidator, clearErrorState, hideError, revealOnBlurValidatorResult]);
const prioritizeContextSchema = useMemo(() => {
if (errorPrioritization) {
const contextSchema = dataContext === null || dataContext === void 0 ? void 0 : dataContext.schema;
if (isZodSchema(contextSchema)) {
return (errorPrioritization === null || errorPrioritization === void 0 ? void 0 : errorPrioritization.indexOf('contextSchema')) === 0;
}
const schemaPath = identifier.split('/').join('/properties/');
const hasContextSchema = pointer.has(contextSchema || {}, schemaPath);
return hasContextSchema && (errorPrioritization === null || errorPrioritization === void 0 ? void 0 : errorPrioritization.indexOf('contextSchema')) === 0;
}
}, [dataContext === null || dataContext === void 0 ? void 0 : dataContext.schema, errorPrioritization, identifier]);
const prioritizeSectionSchema = useMemo(() => {
return (errorPrioritization === null || errorPrioritization === void 0 ? void 0 : errorPrioritization.indexOf('sectionSchema')) === 0 && hasSectionSchema;
}, [errorPrioritization, hasSectionSchema]);
const validateValue = useCallback(async () => {
const isProcessActive = startProcess();
if (disabled) {
if (isProcessActive()) {
clearErrorState();
}
hideError();
setFieldState(undefined);
return;
}
const value = valueRef.current;
changeEventResultRef.current = null;
validatedValueRef.current = null;
let initiator = null;
try {
const requiredError = transformers.current.validateRequired(value, {
emptyValue,
required,
isChanged: changedRef.current,
error: new FormError('Field.errorRequired')
});
if (requiredError instanceof Error) {
initiator = 'required';
throw requiredError;
}
if (error instanceof Error) {
initiator = 'errorProp';
throw error;
}
const skipLocalSchema = prioritizeContextSchema || prioritizeSectionSchema;
if (value !== undefined && !skipLocalSchema && typeof schemaValidatorRef.current === 'function') {
const validationResult = schemaValidatorRef.current(value);
if (validationResult !== true) {
let error;
if (hasZodSchema) {
const zodError = validationResult;
error = zodErrorsToOneFormError(zodError.issues);
} else {
error = ajvErrorsToOneFormError(schemaValidatorRef.current.errors, value);
}
initiator = 'schema';
throw error;
}
}
if (onChangeValidatorRef.current && (changedRef.current || validateInitially || validateUnchanged)) {
const {
result
} = await startOnChangeValidatorValidation();
if (result instanceof Error) {
initiator = 'onChangeValidator';
throw result;
}
}
if (onBlurValidatorRef.current && validateInitially && !changedRef.current) {
const {
result
} = await startOnBlurValidatorProcess();
if (result instanceof Error) {
initiator = 'onBlurValidator';
throw result;
}
}
if (isProcessActive()) {
clearErrorState();
}
validatedValueRef.current = value;
} catch (error) {
if (isProcessActive()) {
persistErrorState('weak', initiator, error);
if (validateContinuously && changedRef.current) {
revealError();
}
}
}
}, [clearErrorState, disabled, emptyValue, error, hasZodSchema, hideError, persistErrorState, prioritizeContextSchema, prioritizeSectionSchema, required, revealError, setFieldState, startOnBlurValidatorProcess, startOnChangeValidatorValidation, startProcess, validateInitially, validateContinuously, validateUnchanged]);
const removeError = useCallback(() => {
setChanged(false);
hideError();
clearErrorState();
validateValue();
}, [clearErrorState, hideError, setChanged, validateValue]);
const handleError = useCallback(() => {
if (validateContinuously || validateContinuously !== false && !hasFocusRef.current) {
revealError();
} else {
hideError();
}
}, [validateContinuously, hideError, revealError]);
const getEventArgs = useCallback(({
eventName,
additionalArgs,
overrideValue = undefined
}) => {
const value = transformers.current.toEvent(overrideValue !== null && overrideValue !== void 0 ? overrideValue : valueRef.current, eventName);
const args = transformers.current.provideAdditionalArgs(value, additionalArgs);
const transformedValue = transformers.current.transformOut(value, args);
if (typeof args !== 'undefined') {
return [transformedValue, args];
}
return [transformedValue];
}, []);
const setHasFocus = useCallback(async (hasFocus, overrideValue, localAdditionalArgs) => {
const args = getEventArgs({
eventName: hasFocus ? 'onFocus' : 'onBlur',
overrideValue,
additionalArgs: localAdditionalArgs ? {
...additionalArgs,
...localAdditionalArgs
} : additionalArgs
});
if (hasFocus) {
hasFocusRef.current = true;
onFocus === null || onFocus === void 0 || onFocus.apply(this, args);
setMountedFieldStateDataContext(identifier, {
isFocused: true
});
} else {
hasFocusRef.current = false;
onBlur === null || onBlur === void 0 || onBlur.apply(this, args);
setMountedFieldStateDataContext(identifier, {
isFocused: false
});
if (!changedRef.current && !validateUnchanged) {
return;
}
addToPool('onBlurValidator', async () => await startOnBlurValidatorProcess({
overrideValue
}), isAsync(onBlurValidatorRef.current));
await runPool(() => {
revealError();
forceUpdate();
});
}
}, [getEventArgs, additionalArgs, onFocus, setMountedFieldStateDataContext, identifier, onBlur, validateUnchanged, addToPool, runPool, startOnBlurValidatorProcess, revealError]);
const yieldAsyncProcess = useCallback(async ({
name,
waitFor
}) => {
return new Promise(resolve => {
const validateProcesses = () => {
const result = waitFor.some(({
processName,
withStates,
hasValue
}) => {
const hasMatchingValue = hasValue === validatedValueRef.current;
const result = (typeof hasValue === 'undefined' ? false : !hasMatchingValue) || (processName ? processName === asyncProcessRef.current : true) && (withStates === null || withStates === void 0 ? void 0 : withStates.some(state => {
return state === fieldStateRef.current;
}));
return result;
});
return result;
};
if (validateProcesses() === true) {
asyncBufferRef.current[name] = {
resolve,
validateProcesses
};
} else {
resolve();
setFieldState('pending');
}
});
}, [setFieldState]);
const handleChangeEventResult = useCallback(async () => {
const result = changeEventResultRef.current || {};
if ('error' in result) {
if (!result.error) {
removeError();
} else {
persistErrorState('gracefully', 'onChangeValidator', result.error);
revealError();
}
}
if ('warning' in result) {
warningRef.current = result.warning;
}
if ('info' in result) {
infoRef.current = result.info;
}
if (asyncBehaviorIsEnabled) {
await yieldAsyncProcess({
name: 'onSubmitContext',
waitFor: [{
withStates: ['validating']
}]
});
}
defineAsyncProcess(undefined);
if ((result === null || result === void 0 ? void 0 : result.success) === 'saved') {
setFieldState('success');
} else if (result !== null && result !== void 0 && result.error) {
setFieldState('error');
} else if (asyncBehaviorIsEnabled) {
setFieldState('complete');
}
forceUpdate();
}, [asyncBehaviorIsEnabled, defineAsyncProcess, removeError, persistErrorState, revealError, yieldAsyncProcess, setFieldState]);
const setEventResult = useCallback(async result => {
if (result instanceof Error) {
result = {
error: result
};
}
changeEventResultRef.current = {
...changeEventResultRef.current,
...result
};
await handleChangeEventResult();
}, [handleChangeEventResult]);
const callOnChangeContext = useCallback(async () => {
if (asyncBehaviorIsEnabled && !executeOnChangeRegardlessOfError) {
await yieldAsyncProcess({
name: 'onChangeContext',
waitFor: [{
processName: 'onChangeValidator',
withStates: ['validating', 'error'],
hasValue: valueRef.current
}, {
processName: 'onBlurValidator',
withStates: ['validating', 'error'],
hasValue: valueRef.current
}]
});
}
if (hasPath) {
if (isAsync(onChangeContext)) {
defineAsyncProcess('onChangeContext');
if (!hasError() || executeOnChangeRegardlessOfError) {
await setEventResult(await (handlePathChangeDataContext === null || handlePathChangeDataContext === void 0 ? void 0 : handlePathChangeDataContext(identifier)));
} else {
await setEventResult(null);
}
} else if (onChangeContext || !asyncBehaviorIsEnabled) {
setEventResult(handlePathChangeDataContext === null || handlePathChangeDataContext === void 0 ? void 0 : handlePathChangeDataContext(identifier));
}
}
forceUpdate();
}, [asyncBehaviorIsEnabled, executeOnChangeRegardlessOfError, hasPath, yieldAsyncProcess, onChangeContext, defineAsyncProcess, hasError, setEventResult, handlePathChangeDataContext, identifier]);
const updateValue = useCallback(async newValue => {
var _transformers$current;
const currentValue = valueRef.current;
const valueIsUnchanged = newValue === currentValue;
if (!executeOnChangeRegardlessOfUnchangedValue && valueIsUnchanged) {
return;
}
const transformedValue = (_transformers$current = transformers.current.transformValue(newValue, currentValue)) !== null && _transformers$current !== void 0 ? _transformers$current : emptyValue;
const contextValue = transformers.current.transformOut(transformedValue, transformers.current.provideAdditionalArgs(transformedValue, additionalArgs));
valueRef.current = transformedValue;
if (hasPath || itemPath) {
handlePathChangeUnvalidatedDataContext(nestedIteratePath || identifier, contextValue);
}
if (itemPath) {
handleChangeIterateContext === null || handleChangeIterateContext === void 0 || handleChangeIterateContext(makeIteratePath(itemPath, '', {
omitSectionPath: true
}), contextValue);
}
addToPool('onChangeValidator', validateValue, isAsync(onChangeValidatorRef.current));
addToPool('onChangeContext', callOnChangeContext, isAsync(onChangeContext));
await runPool(() => {
handleError();
});
}, [emptyValue, additionalArgs, hasPath, itemPath, addToPool, validateValue, callOnChangeContext, onChangeContext, runPool, handlePathChangeUnvalidatedDataContext, nestedIteratePath, identifier, handleChangeIterateContext, makeIteratePath, handleError, executeOnChangeRegardlessOfUnchangedValue]);
const valueEqualsEmptyValue = useCallback(value => {
if (value === emptyValue) {
return true;
}
if (value instanceof Date && emptyValue instanceof Date) {
return value.getTime() === emptyValue.getTime();
}
return false;
}, [emptyValue]);
const setDisplayValue = useCallback((value, options) => {
const {
path: fieldPath = itemPath ? identifier : path,
type = 'field'
} = options || {};
if (!fieldPath || !(fieldDisplayValueRef !== null && fieldDisplayValueRef !== void 0 && fieldDisplayValueRef.current)) {
return;
}
fieldDisplayValueRef.current[fieldPath] = valueEqualsEmptyValue(valueRef.current) ? {
type
} : {
value,
type
};
}, [identifier, fieldDisplayValueRef, itemPath, path, valueEqualsEmptyValue]);
const handleChange = useCallback(async (argFromInput, localAdditionalArgs = undefined) => {
const currentValue = valueRef.current;
const fromInput = transformers.current.fromInput(argFromInput);
const valueIsUnchanged = fromInput === currentValue;
if (!executeOnChangeRegardlessOfUnchangedValue && valueIsUnchanged) {
re