@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
1,232 lines (1,231 loc) • 62.7 kB
JavaScript
"use client";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import React, { useRef, useEffect, useContext, useCallback, useMemo, useReducer } from 'react';
import pointer from '../utils/json-pointer';
import { ajvErrorsToOneFormError, errorChanged, overwriteErrorMessagesWithGivenAjvKeys, extendErrorMessagesWithTranslationMessages, FormError } from '../utils';
import { Context as DataContext } from '../DataContext';
import { clearedData } from '../DataContext/Provider/Provider';
import FieldProviderContext from '../Field/Provider/FieldProviderContext';
import { combineDescribedBy, convertJsxToString, warn } from '../../../shared/component-helper';
import useId from '../../../shared/helpers/useId';
import useUpdateEffect from '../../../shared/helpers/useUpdateEffect';
import FieldBlockContext from '../FieldBlock/FieldBlockContext';
import IterateElementContext from '../Iterate/IterateItemContext';
import SectionContext from '../Form/Section/SectionContext';
import FieldBoundaryContext from '../DataContext/FieldBoundary/FieldBoundaryContext';
import VisibilityContext from '../Form/Visibility/VisibilityContext';
import WizardContext from '../Wizard/Context';
import WizardStepContext from '../Wizard/Step/StepContext';
import SnapshotContext from '../Form/Snapshot/SnapshotContext';
import useProcessManager from './useProcessManager';
import usePath from './usePath';
import { createSharedState, useSharedState } from '../../../shared/helpers/useSharedState';
import { isAsync } from '../../../shared/helpers/isAsync';
import useTranslation from './useTranslation';
import useExternalValue from './useExternalValue';
import useDataValue from './useDataValue';
const useLayoutEffect = typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;
export default function useFieldProps(localProps, {
executeOnChangeRegardlessOfError = false,
updateContextDataInSync = false,
omitMultiplePathWarning = false,
forceUpdateWhenContextDataIsSet = false
} = {}) {
var _dataContext$props, _localErrorRef$curren, _dataContext$props3, _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,
onFocus,
onBlur,
onChange,
onBlurValidator,
validator,
onChangeValidator = 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 fieldBlockContext = useContext(FieldBlockContext);
const iterateItemContext = useContext(IterateElementContext);
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,
setFieldEventListener,
errors: dataContextErrors,
showAllErrors,
contextErrorMessages,
fieldDisplayValueRef,
existingFieldsRef,
fieldInternalsRef
} = dataContext || {};
const onChangeContext = dataContext === null || dataContext === void 0 ? void 0 : (_dataContext$props = dataContext.props) === null || _dataContext$props === void 0 ? void 0 : _dataContext$props.onChange;
const disabled = disabledProp !== null && disabledProp !== void 0 ? disabledProp : props.readOnly;
const inFieldBlock = Boolean(fieldBlockContext && fieldBlockContext.disableStatusSummary !== true);
const {
setBlockRecord,
setFieldState: setFieldStateFieldBlock,
showFieldError: showFieldErrorFieldBlock,
mountedFieldsRef: mountedFieldsRefFieldBlock
} = inFieldBlock ? fieldBlockContext : {};
const {
activeIndex,
activeIndexRef,
prerenderFieldProps,
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 hasItemPath = Boolean(itemPath);
const {
path,
identifier,
makeIteratePath,
joinPath,
cleanPath
} = usePath({
id,
path: pathProp,
itemPath
});
const defaultValueRef = useRef(defaultValue);
useLayoutEffect(() => {
defaultValueRef.current = defaultValue;
}, []);
const tmpValue = useExternalValue({
path,
itemPath,
value: valueProp,
transformers,
emptyValue: defaultValue ? undefined : emptyValue
});
const externalValueDeps = tmpValue;
const externalValue = transformers.current.transformIn(tmpValue !== null && tmpValue !== void 0 ? tmpValue : defaultValueRef.current);
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]);
});
requiredInSchema.push(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 => {
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 ensureErrorMessageObject(message);
}, [getFieldByPath, getValueByPath, ensureErrorMessageObject]);
const errorProp = initialErrorProp === 'initial' ? undefined : initialErrorProp;
const error = executeMessage(errorProp);
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 onChangeValidatorRef = useRef(onChangeValidator);
useUpdateEffect(() => {
onChangeValidatorRef.current = onChangeValidator;
}, [onChangeValidator]);
const onBlurValidatorRef = useRef(onBlurValidator);
useUpdateEffect(() => {
onBlurValidatorRef.current = onBlurValidator;
}, [onBlurValidator]);
const schemaValidatorRef = useRef();
if (!schemaValidatorRef.current && schema) {
var _dataContext$ajvInsta;
schemaValidatorRef.current = (_dataContext$ajvInsta = dataContext.ajvInstance) === null || _dataContext$ajvInsta === void 0 ? void 0 : _dataContext$ajvInsta.compile(schema);
}
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 ? void 0 : cb();
}, []);
const fieldStateRef = useRef();
const setFieldState = useCallback(state => {
fieldStateRef.current = state;
setFieldStateDataContext === null || setFieldStateDataContext === void 0 ? void 0 : setFieldStateDataContext(identifier, resolveValidatingState(state));
setFieldStateFieldBlock === null || setFieldStateFieldBlock === void 0 ? void 0 : setFieldStateFieldBlock(identifier, resolveValidatingState(state));
if (!validateInitially) {
forceUpdate();
}
}, [setFieldStateDataContext, identifier, setFieldStateFieldBlock, validateInitially]);
const setErrorState = useCallback(hasError => {
setFieldErrorWizard === null || setFieldErrorWizard === void 0 ? void 0 : setFieldErrorWizard(wizardIndex, identifier, handleFieldAsVisible !== false ? hasError : undefined);
showFieldErrorFieldBlock === null || showFieldErrorFieldBlock === void 0 ? void 0 : showFieldErrorFieldBlock(identifier, hasError);
revealErrorBoundary === null || revealErrorBoundary === void 0 ? void 0 : revealErrorBoundary(identifier, hasError);
revealErrorDataContext === null || revealErrorDataContext === void 0 ? 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 = hasError;
setErrorState(hasError);
}, [validateInitially, setErrorState]);
const hideError = useCallback(() => {
if (revealErrorRef.current) {
revealErrorRef.current = undefined;
setErrorState(false);
}
}, [setErrorState]);
const errorMessagesCacheRef = useRef({
errorMessages: null,
extendedErrorMessages: null
});
const combinedErrorMessages = useMemo(() => {
const cache = errorMessagesCacheRef.current;
if (errorMessages && cache.extendedErrorMessages && Object.values(cache.errorMessages || {}).join('') === Object.values(errorMessages || {}).join('')) {
return cache.extendedErrorMessages;
}
const messages = _objectSpread(_objectSpread(_objectSpread({}, contextErrorMessages), contextErrorMessages === null || contextErrorMessages === void 0 ? void 0 : contextErrorMessages[identifier]), errorMessages);
const extendedErrorMessages = extendErrorMessagesWithTranslationMessages(overwriteErrorMessagesWithGivenAjvKeys(messages), translationRef.current);
errorMessagesCacheRef.current = {
errorMessages,
extendedErrorMessages
};
return extendedErrorMessages;
}, [contextErrorMessages, errorMessages, identifier]);
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[path];
if (!dataContextError) {
return undefined;
}
const error = prepareError(dataContextError);
if (errorChanged(error, contextErrorRef.current)) {
return error;
}
return contextErrorRef.current;
}, [dataContextErrors, path, prepareError]);
if (((_localErrorRef$curren = localErrorRef.current) === null || _localErrorRef$curren === void 0 ? void 0 : _localErrorRef$curren['ajvKeyword']) === 'type') {
revealErrorRef.current = true;
}
const getBufferedError = useCallback(() => {
if (initialErrorProp !== 'initial' && typeof errorProp !== 'function') {
return prepareError(errorProp);
} else if (revealErrorRef.current) {
var _ref, _prepareError;
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 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 ? 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 = _objectSpread(_objectSpread(_objectSpread({}, 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 => {
const result = callStackRef.current.includes(validator);
callStackRef.current.push(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) {
errors.push(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) {
errors.push(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;
}
localErrorRef.current = error;
setFieldErrorDataContext === null || setFieldErrorDataContext === void 0 ? void 0 : setFieldErrorDataContext(identifier, error);
setFieldErrorBoundary === null || setFieldErrorBoundary === void 0 ? void 0 : setFieldErrorBoundary(identifier, error);
setBlockRecord === null || setBlockRecord === void 0 ? void 0 : setBlockRecord({
stateId,
identifier,
type: 'error',
content: error,
showInitially: Boolean(inFieldBlock && validateInitially)
});
setFieldStateDataContext === null || setFieldStateDataContext === void 0 ? void 0 : setFieldStateDataContext(identifier, error ? 'error' : undefined);
forceUpdate();
}, [identifier, inFieldBlock, prepareError, setBlockRecord, setFieldErrorBoundary, setFieldErrorDataContext, setFieldStateDataContext, stateId, validateInitially]);
const clearErrorState = useCallback(() => {
var _schemaValidatorRef$c;
persistErrorState('wipe', undefined);
localErrorInitiatorRef.current = undefined;
if (Array.isArray((_schemaValidatorRef$c = schemaValidatorRef.current) === null || _schemaValidatorRef$c === void 0 ? void 0 : _schemaValidatorRef$c.errors)) {
schemaValidatorRef.current.errors = [];
}
}, [persistErrorState]);
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 schemaPath = identifier.split('/').join('/properties/');
const hasContextSchema = pointer.has((dataContext === null || dataContext === void 0 ? void 0 : dataContext.schema) || {}, 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 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;
}
if (value !== undefined && !prioritizeContextSchema && typeof schemaValidatorRef.current === 'function') {
if (!schemaValidatorRef.current(value)) {
const 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);
}
}
}, [clearErrorState, disabled, emptyValue, error, hideError, persistErrorState, prioritizeContextSchema, required, setFieldState, startOnBlurValidatorProcess, startOnChangeValidatorValidation, startProcess, validateInitially, 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 ? _objectSpread(_objectSpread({}, additionalArgs), localAdditionalArgs) : additionalArgs
});
if (hasFocus) {
hasFocusRef.current = true;
onFocus === null || onFocus === void 0 ? void 0 : onFocus.apply(this, args);
setMountedFieldStateDataContext(identifier, {
isFocused: true
});
} else {
hasFocusRef.current = false;
onBlur === null || onBlur === void 0 ? 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 = _objectSpread(_objectSpread({}, 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;
if (newValue === currentValue) {
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 ? void 0 : handleChangeIterateContext(makeIteratePath(itemPath, ''), 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]);
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] = valueRef.current === emptyValue ? {
type
} : {
value,
type
};
}, [identifier, emptyValue, fieldDisplayValueRef, itemPath, path]);
const handleChange = useCallback(async (argFromInput, localAdditionalArgs = undefined) => {
const currentValue = valueRef.current;
const fromInput = transformers.current.fromInput(argFromInput);
if (fromInput === currentValue) {
return;
}
setChanged(true);
if (asyncBehaviorIsEnabled) {
hideError();
await updateValue(fromInput);
} else {
updateValue(fromInput);
}
if (isAsync(onChange)) {
addToPool('onChangeLocal', async () => {
const args = getEventArgs({
eventName: 'onChange',
additionalArgs: localAdditionalArgs ? _objectSpread(_objectSpread({}, additionalArgs), localAdditionalArgs) : additionalArgs
});
await yieldAsyncProcess({
name: 'onChangeLocal',
waitFor: [{
processName: 'onChangeValidator',
withStates: ['validating', 'error'],
hasValue: args[0]
}, {
processName: 'onBlurValidator',
withStates: ['validating', 'error'],
hasValue: args[0]
}, {
processName: 'onChangeContext',
withStates: ['pending', 'error'],
hasValue: args[0]
}]
});
defineAsyncProcess('onChangeLocal');
if (!hasError()) {
await setEventResult(await (onChange === null || onChange === void 0 ? void 0 : onChange.apply(this, args)));
} else {
await setEventResult(null);
}
}, true);
} else {
const args = getEventArgs({
eventName: 'onChange',
additionalArgs: localAdditionalArgs ? _objectSpread(_objectSpread({}, additionalArgs), localAdditionalArgs) : additionalArgs
});
setEventResult(onChange === null || onChange === void 0 ? void 0 : onChange.apply(this, args));
}
await runPool();
}, [addToPool, additionalArgs, asyncBehaviorIsEnabled, defineAsyncProcess, getEventArgs, hasError, hideError, onChange, runPool, setChanged, setEventResult, updateValue, yieldAsyncProcess]);
const handleFocus = useCallback(() => setHasFocus(true), [setHasFocus]);
const handleBlur = useCallback(() => setHasFocus(false), [setHasFocus]);
setFieldInternalsDataContext === null || setFieldInternalsDataContext === void 0 ? void 0 : setFieldInternalsDataContext(identifier, props, id);
const activeIndexTmpRef = useRef(activeIndex);
useEffect(() => {
activeIndexTmpRef.current = activeIndex;
}, [activeIndex]);
useMemo(() => {
setMountedFieldStateDataContext(identifier, {
isPreMounted: true
});
if (typeof isVisible === 'boolean') {
setMountedFieldStateDataContext(identifier, {
isVisible
});
}
}, [setMountedFieldStateDataContext, identifier, isVisible]);
useEffect(() => {
if (typeof (activeIndexRef === null || activeIndexRef === void 0 ? void 0 : activeIndexRef.current) === 'number') {
setMountedFieldStateDataContext(identifier, {
wasStepChange: false
});
return () => {
const wasStepChange = typeof activeIndex === 'number' && activeIndexRef.current !== activeIndexTmpRef.current;
setMountedFieldStateDataContext(identifier, {
wasStepChange
});
};
}
}, [activeIndex, activeIndexRef, identifier, setMountedFieldStateDataContext]);
useEffect(() => {
setMountedFieldStateDataContext(identifier, {
isMounted: true,
isPreMounted: true
});
setMountedFieldSnapshot === null || setMountedFieldSnapshot === void 0 ? void 0 : setMountedFieldSnapshot(identifier, {
isMounted: true
});
return () => {
setMountedFieldStateDataContext(identifier, {
isMounted: false,
isPreMounted: false
});
setMountedFieldSnapshot === null || setMountedFieldSnapshot === void 0 ? void 0 : setMountedFieldSnapshot(identifier, {
isMounted: false
});
};
}, [identifier, setMountedFieldSnapshot, setMountedFieldStateDataContext]);
useEffect(() => {
if (!omitMultiplePathWarning && process.env.NODE_ENV !== 'production' && (hasPath || hasItemPath) && (hasPath ? !iterateItemContext : true) && existingFieldsRef !== null && existingFieldsRef !== void 0 && existingFieldsRef.current) {
const existingFields = existingFieldsRef.current;
if (existingFields.has(identifier)) {
warn('Path declared multiple times:', identifier);
} else {
existingFields.set(identifier, true);
return () => {
existingFields.delete(identifier);
};
}
}
}, [existingFieldsRef, hasItemPath, hasPath, identifier, iterateItemContext, omitMultiplePathWarning]);
useEffect(() => {
return () => {
setFieldErrorDataContext === null || setFieldErrorDataContext === void 0 ? void 0 : setFieldErrorDataContext(identifier, undefined);
setFieldErrorBoundary === null || setFieldErrorBoundary === void 0 ? void 0 : setFieldErrorBoundary(identifier, undefined);
localErrorRef.current = undefined;
};
}, [identifier, setFieldErrorBoundary, setFieldErrorDataContext]);
useEffect(() => {
return () => {
setFieldErrorWizard === null || setFieldErrorWizard === void 0 ? void 0 : setFieldErrorWizard(wizardIndex, identifier, undefined);
};
}, [identifier, setFieldErrorWizard, wizardIndex]);
useEffect(() => {
validateValue();
}, [validateValue]);
useUpdateEffect(() => {
var _dataContext$ajvInsta2;
schemaValidatorRef.current = schema ? (_dataContext$ajvInsta2 = dataContext.ajvInstance) === null || _dataContext$ajvInsta2 === void 0 ? void 0 : _dataContext$ajvInsta2.compile(schema) : undefined;
validateValue();
}, [schema]);
const externalValueDidChangeRef = useRef(false);
useLayoutEffect(() => {
if (valueRef.current !== externalValue) {
valueRef.curre