UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

1,346 lines (1,345 loc) 65.1 kB
"use client"; 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$lo, _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?.props?.onChange; const locale = (_dataContext$props$lo = dataContext?.props?.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?.current; const hasSectionSchema = Boolean(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(() => { if (finalSchema && !hasZodSchema && !omitMultiplePathWarning && hasDataContext && !dataContext?.props?.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?.props?.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?.schema) { const paths = identifier.split('/'); if (paths.length > 0) { const requiredInSchema = [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?.['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 => { return fieldInternalsRef.current?.[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?.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?.() : makeAjvInstance(); }, [hasDataContext, getAjvInstanceDataContext]); const schemaValidatorRef = useRef(); if (!schemaValidatorRef.current && finalSchema) { if (hasZodSchema) { schemaValidatorRef.current = createZodValidator(finalSchema); } else { schemaValidatorRef.current = getAjvInstance()?.compile?.(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?.() === 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?.(); }, []); const fieldStateRef = useRef(); const setFieldState = useCallback(state => { fieldStateRef.current = state; setFieldStateDataContext?.(identifier, resolveValidatingState(state)); setFieldStateFieldBlock?.(identifier, resolveValidatingState(state)); if (!validateInitially) { forceUpdate(); } }, [setFieldStateDataContext, identifier, setFieldStateFieldBlock, validateInitially]); const setErrorState = useCallback(hasError => { setFieldErrorWizard?.(wizardIndex, identifier, handleFieldAsVisible !== false ? hasError : undefined); showFieldErrorFieldBlock?.(identifier, hasError); revealErrorBoundary?.(identifier, hasError); 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?.[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?.[ajvKeyword]; if (ajvMessage) { message = ajvMessage; } } const { validationRule } = error; if (typeof validationRule === 'string') { const ajvMessage = combinedErrorMessages?.[validationRule]; if (ajvMessage) { message = ajvMessage; } } if (combinedErrorMessages?.[message]) { message = 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?.[identifier]; if (!dataContextError) { return undefined; } const error = prepareError(dataContextError); if (errorChanged(error, contextErrorRef.current)) { return error; } return contextErrorRef.current; }, [dataContextErrors, identifier, prepareError]); if (localErrorRef.current?.['ajvKeyword'] === 'type' || contextErrorRef.current?.['ajvKeyword'] === 'type') { revealErrorRef.current = true; } const getBufferedError = useCallback(() => { if (initialErrorProp !== 'initial' && typeof errorProp !== 'function') { return prepareError(errorProp); } else if (revealErrorRef.current) { var _ref, _prepareError; if (contextErrorRef.current?.['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?.(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 => { 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) => { 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.current?.weak || errorMethodRef.current?.gracefully)) { return; } const currentError = handleFieldAsVisible !== false ? error : undefined; localErrorRef.current = currentError; setFieldErrorDataContext?.(identifier, currentError); setFieldErrorBoundary?.(identifier, currentError); setBlockRecord?.({ stateId, identifier, type: 'error', content: currentError, showInitially: Boolean(inFieldBlock && validateInitially) }); setFieldStateDataContext?.(identifier, error ? 'error' : undefined); if (updateContextDataInSync && !prerenderFieldProps) { 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?.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?.schema; if (isZodSchema(contextSchema)) { return errorPrioritization?.indexOf('contextSchema') === 0; } const schemaPath = identifier.split('/').join('/properties/'); const hasContextSchema = pointer.has(contextSchema || {}, schemaPath); return hasContextSchema && errorPrioritization?.indexOf('contextSchema') === 0; } }, [dataContext?.schema, errorPrioritization, identifier]); const prioritizeSectionSchema = useMemo(() => { return 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?.apply(this, args); setMountedFieldStateDataContext(identifier, { isFocused: true }); } else { hasFocusRef.current = false; 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?.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?.success === 'saved') { setFieldState('success'); } else if (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?.(identifier)); } else { await setEventResult(null); } } else if (onChangeContext || !asyncBehaviorIsEnabled) { setEventResult(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?.(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?.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) { 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 ? { ...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?.apply(this, args)); } else { await setEventResult(null); } }, true); } else { const args = getEventArgs({ eventName: 'onChange', additionalArgs: localAdditionalArgs ? { ...additionalArgs, ...localAdditionalArgs } : additionalArgs }); setEventResult(onChange?.apply(this, args)); } await runPool(); }, [addToPool, additionalArgs, asyncBehaviorIsEnabled, defineAsyncProcess, executeOnChangeRegardlessOfUnchangedValue, getEventArgs, hasError, hideError, onChange, runPool, setChanged, setEventResult, updateValue, yieldAsyncProcess]); const handleFocus = useCallback(() => setHasFocus(true), [setHasFocus]); const handleBlur = useCallback(() => setHasFocus(false), [setHasFocus]); setFieldInternalsDataContext?.(identifier, { id, props }); 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 (prerenderFieldProps) { return; } if (typeof activeIndexRef?.current === 'number') { setMountedFieldStateDataContext(identifier, { wasStepChange: false }); return () => { const wasStepChange = typeof activeIndex === 'number' && activeIndexRef.current !== activeIndexTmpRef.current; setMountedFieldStateDataContext(identifier, { wasStepChange }); }; } }, [activeIndex, activeIndexRef, identifier, prerenderFieldProps, setMountedFieldStateDataContext]); useEffect(() => { if (prerenderFieldProps) { return; } setMountedFieldStateDataContext(identifier, { isMounted: true, isPreMounted: true }); setMountedFieldSnapshot?.(identifier, { isMounted: true }); return () => { setMountedFieldStateDataContext(identifier, { isMounted: false, isPreMounted: false }); setMountedFieldSnapshot?.(identifier, { isMounted: false }); }; }, [identifier, prerenderFieldProps, setMountedFieldSnapshot, setMountedFieldStateDataContext]); useEffect(() => { if (!omitMultiplePathWarning && !isParentRelativePath && process.env.NODE_ENV !== 'production' && (hasPath || hasItemPath) && (hasPath ? !iterateItemContext : true) && 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, isParentRelativePath, omitMultiplePathWarning]); useEffect(() => { if (prerenderFieldProps) { return; } const mountedFields = mountedFieldsRef?.current; return () => { Promise.resolve().then(() => { const isMounted = mountedFields?.get?.(identifier)?.isMounted === true; const sharedAttachments = dataContext?.id ? createSharedState(createReferenceKey(dataContext.id, 'attachments')).get?.() : undefined; const hasFieldConnection = Boolean(sharedAttachments?.fieldConnectionsRef?.current?.[identifier]); if (!is