UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

1,143 lines (1,142 loc) 44 kB
"use strict"; "use client"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "checkForError", { enumerable: true, get: function () { return _useFieldError.checkForError; } }); exports.clearedArray = void 0; exports.default = useFieldProps; var _push = _interopRequireDefault(require("core-js-pure/stable/instance/push.js")); var _react = require("react"); var _index = _interopRequireDefault(require("../utils/json-pointer/index.js")); var _index2 = require("../utils/index.js"); var _index3 = require("../DataContext/index.js"); var _Provider = require("../DataContext/Provider/Provider.js"); var _FieldProviderContext = _interopRequireDefault(require("../Field/Provider/FieldProviderContext.js")); var _componentHelper = require("../../../shared/component-helper.js"); var _useId = _interopRequireDefault(require("../../../shared/helpers/useId.js")); var _useUpdateEffect = _interopRequireDefault(require("../../../shared/helpers/useUpdateEffect.js")); var _FieldBlockContext = _interopRequireDefault(require("../FieldBlock/FieldBlockContext.js")); var _IterateItemContext = _interopRequireDefault(require("../Iterate/IterateItemContext.js")); var _SectionContext = _interopRequireDefault(require("../Form/Section/SectionContext.js")); var _FieldBoundaryContext = _interopRequireDefault(require("../DataContext/FieldBoundary/FieldBoundaryContext.js")); var _VisibilityContext = _interopRequireDefault(require("../Form/Visibility/VisibilityContext.js")); var _index4 = _interopRequireDefault(require("../Wizard/Context/index.js")); var _StepContext = _interopRequireDefault(require("../Wizard/Step/StepContext.js")); var _SnapshotContext = _interopRequireDefault(require("../Form/Snapshot/SnapshotContext.js")); var _usePath = _interopRequireDefault(require("./usePath.js")); var _Context = _interopRequireDefault(require("../../../shared/Context.js")); var _useSharedState = require("../../../shared/helpers/useSharedState.js"); var _isAsync = require("../../../shared/helpers/isAsync.js"); var _useTranslation = _interopRequireDefault(require("./useTranslation.js")); var _useExternalValue = _interopRequireDefault(require("./useExternalValue.js")); var _useDataValue = _interopRequireDefault(require("./useDataValue.js")); var _useFieldTransform = _interopRequireDefault(require("./useFieldTransform.js")); var _useFieldError = _interopRequireWildcard(require("./useFieldError.js")); var _useFieldAsync = _interopRequireDefault(require("./useFieldAsync.js")); var _useFieldValidation = _interopRequireDefault(require("./useFieldValidation.js")); var _useIsomorphicLayoutEffect = require("../../../shared/helpers/useIsomorphicLayoutEffect.js"); function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } function useFieldProps(localProps, { executeOnChangeRegardlessOfError = false, executeOnChangeRegardlessOfUnchangedValue = false, updateContextDataInSync = false, omitMultiplePathWarning = false, forceUpdateWhenContextDataIsSet = false, omitSectionPath = false, getExternalValueSnapshot = undefined } = {}) { var _dataContext$props$lo, _props$autoComplete; const { extend } = (0, _react.useContext)(_FieldProviderContext.default); const props = extend(localProps); const { path: pathProp, value: valueProp, defaultValue, itemPath, emptyValue, required: requiredProp, disabled: disabledProp, readOnly, info: infoProp, warning: warningProp, error: initialErrorProp = 'initial', errorMessages, onStatusChange, onFocus, onBlur, onChange, onBlurValidator, onChangeValidator: onChangeValidatorProp, exportValidators, schema, validateInitially, validateUnchanged, validateContinuously, 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; } return undefined; } } = props; const [salt, forceUpdate] = (0, _react.useReducer)(() => ({}), {}); const isInternalRerenderRef = (0, _react.useRef)(null); (0, _react.useMemo)(() => { isInternalRerenderRef.current = salt; }, [salt]); const id = (0, _useId.default)(props.id); const dataContext = (0, _react.useContext)(_index3.Context); const { locale: sharedLocale } = (0, _react.useContext)(_Context.default) || {}; const fieldBlockContext = (0, _react.useContext)(_FieldBlockContext.default); const iterateItemContext = (0, _react.useContext)(_IterateItemContext.default); const sectionContext = (0, _react.useContext)(_SectionContext.default); const fieldBoundaryContext = (0, _react.useContext)(_FieldBoundaryContext.default); const wizardContext = (0, _react.useContext)(_index4.default); const wizardStepContext = (0, _react.useContext)(_StepContext.default); const { setMountedField: setMountedFieldSnapshot } = (0, _react.useContext)(_SnapshotContext.default) || {}; const { isVisible, keepInDOM } = (0, _react.useContext)(_VisibilityContext.default) || {}; const handleFieldAsVisible = isVisible || keepInDOM; const { getValueByPath, getSourceValue } = (0, _useDataValue.default)(); const translation = (0, _useTranslation.default)(); const { formatMessage } = translation; const translationRef = (0, _react.useRef)(translation); translationRef.current = translation; 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 setMountedFieldStateRef = (0, _react.useRef)(setMountedFieldStateDataContext); setMountedFieldStateRef.current = setMountedFieldStateDataContext; const setMountedFieldState = (0, _react.useCallback)((...args) => { return setMountedFieldStateRef.current?.(...args); }, []); const disabled = disabledProp !== null && disabledProp !== void 0 ? disabledProp : readOnly; const inFieldBlock = Boolean(fieldBlockContext && fieldBlockContext.disableStatusSummary !== true); const resolvedSchema = (0, _react.useMemo)(() => { const s = schema; if (typeof s === 'function') { try { return s(props); } catch (_) { return undefined; } } return s; }, [schema]); const finalSchema = (0, _react.useMemo)(() => { const s = resolvedSchema; if (typeof s === 'function') { try { return s(props); } catch (_) { return undefined; } } return s; }, [resolvedSchema]); const hasZodSchema = (0, _index2.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, restoreValueCount } = 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 } = (0, _usePath.default)({ 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 = (0, _react.useRef)(defaultValue); (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(() => { defaultValueRef.current = defaultValue; }, []); const valueRef = (0, _react.useRef)(undefined); const changedRef = (0, _react.useRef)(undefined); const hasFocusRef = (0, _react.useRef)(undefined); const validatedValidatorValuesRef = (0, _react.useRef)({}); const { transformers, getEventArgs } = (0, _useFieldTransform.default)({ transformIn: transformIn, transformOut, toInput: toInput, fromInput, toEvent, transformValue, provideAdditionalArgs, fromExternal, validateRequired, valueRef }); const tmpValue = (0, _useExternalValue.default)({ path: identifier, itemPath, value: valueProp, getValueSnapshot: getExternalValueSnapshot, transformers, emptyValue: defaultValue ? undefined : emptyValue }); const externalValueDeps = tmpValue; const iterateArrayValueDeps = hasItemPath ? iterateArrayValue : undefined; const iterateRestoreValueDeps = hasItemPath ? restoreValueCount : undefined; const externalValue = transformers.current.transformIn(tmpValue !== null && tmpValue !== void 0 ? tmpValue : defaultValueRef.current); const valueInitializedRef = (0, _react.useRef)(false); if (!valueInitializedRef.current) { valueInitializedRef.current = true; valueRef.current = externalValue; } (0, _react.useEffect)(() => { if (finalSchema && !hasZodSchema && !omitMultiplePathWarning && hasDataContext && !dataContext?.props?.ajvInstance) { (0, _componentHelper.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 required = (0, _react.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 = _index.default.has(schema, pathWithoutLast) ? _index.default.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]); }); (0, _push.default)(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; } } } return undefined; }, [cleanPath, dataContext.schema, identifier, joinPath, requiredProp, schema, sectionPath]); const getFieldByPath = (0, _react.useCallback)(path => { return fieldInternalsRef.current?.[path] || { props: undefined, id: undefined }; }, [fieldInternalsRef]); const schemaValidatorRef = (0, _react.useRef)(undefined); const { error, warning, info, combinedErrorMessages, bufferedError, bufferedErrorRef, errorIsVisible: errorIsVisibleBase, ensureErrorMessageObject, prepareError, persistErrorState, clearErrorState, revealError, hideError, setFieldState, hasError, handleError, revealErrorRef, localErrorRef, localErrorInitiatorRef, contextErrorRef, fieldStateRef, warningRef, infoRef } = (0, _useFieldError.default)({ initialErrorProp, warningProp, infoProp, errorMessages, validateInitially, validateContinuously, disabled, identifier, locale, handleFieldAsVisible, inFieldBlock, prerenderFieldProps, updateContextDataInSync, hasZodSchema, setFieldStateDataContext, setFieldStateFieldBlock, setFieldErrorDataContext, setFieldErrorBoundary, setFieldErrorWizard, setBlockRecord, showFieldErrorFieldBlock, revealErrorDataContext, revealErrorBoundary, wizardIndex, dataContextErrors, contextErrorMessages: contextErrorMessages, valueRef, hasFocusRef, isInternalRerenderRef, schemaValidatorRef, translationRef, formatMessage, getFieldByPath, getValueByPath, forceUpdate }); const errorIsVisible = errorIsVisibleBase || inFieldBlock && fieldBlockContext.hasErrorProp; const removeErrorRef = (0, _react.useRef)(() => {}); const { asyncBehaviorIsEnabled, defineAsyncProcess, addToPool, runPool, yieldAsyncProcess, setEventResult, callOnChangeContext, asyncProcessRef, validatedValueRef, changeEventResultRef } = (0, _useFieldAsync.default)({ onChange, onChangeContext, valueRef, forceUpdate, persistErrorState, revealError, setFieldState, hasError, warningRef, infoRef, fieldStateRef, removeErrorRef, hasPath, identifier, executeOnChangeRegardlessOfError, handlePathChangeDataContext: handlePathChangeDataContext }); const { validateValue, startOnChangeValidatorValidation, startOnBlurValidatorProcess, onChangeValidatorRef, onBlurValidatorRef, additionalArgs } = (0, _useFieldValidation.default)({ finalSchema, hasZodSchema, onChangeValidatorProp, onBlurValidator, validateInitially, validateUnchanged, validateContinuously, identifier, disabled, emptyValue, required, hasDataContext, getAjvInstanceDataContext, setFieldEventListener, getValueByPath, getSourceValue, exportValidators, props, dataContext, combinedErrorMessages, makeIteratePath, errorPrioritization, sectionPath, hasSectionSchema, dataContextSchema: dataContext?.schema, valueRef, changedRef, transformers, schemaValidatorRef, asyncProcessRef, validatedValueRef, changeEventResultRef, localErrorInitiatorRef, error, persistErrorState, clearErrorState, revealError, hideError, setFieldState, ensureErrorMessageObject, asyncBehaviorIsEnabled, defineAsyncProcess, forceUpdate, revealErrorRef }); const valueEqualsEmptyValue = (0, _react.useCallback)(value => { if (value === emptyValue) { return true; } if (value instanceof Date && emptyValue instanceof Date) { return value.getTime() === emptyValue.getTime(); } return false; }, [emptyValue]); const setChanged = (0, _react.useCallback)(state => { changedRef.current = state; }, []); const removeError = (0, _react.useCallback)(() => { setChanged(false); hideError(); clearErrorState(); validateValue(); }, [clearErrorState, hideError, setChanged, validateValue]); removeErrorRef.current = removeError; const setValidatedValidatorValue = (0, _react.useCallback)((validatorName, value = valueRef.current) => { validatedValidatorValuesRef.current[validatorName] = { value }; }, []); const isValidatorValueChanged = (0, _react.useCallback)(validatorName => { const cachedValue = validatedValidatorValuesRef.current[validatorName]; if (!cachedValue) { return true; } return !Object.is(cachedValue.value, valueRef.current); }, []); const externalValueDidChangeRef = (0, _react.useRef)(false); (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(() => { if (valueRef.current !== externalValue) { valueRef.current = externalValue; externalValueDidChangeRef.current = true; } }, [externalValueDeps, hasItemPath, iterateArrayValueDeps, iterateRestoreValueDeps]); const syncExternalValueUpdate = (0, _react.useCallback)(() => { if (externalValueDidChangeRef.current) { externalValueDidChangeRef.current = false; if (!validateContinuously && valueEqualsEmptyValue(valueRef.current)) { hideError(); } validateValue(); forceUpdate(); } }, [forceUpdate, hideError, validateContinuously, validateValue, valueEqualsEmptyValue]); (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(() => { if (hasItemPath) { syncExternalValueUpdate(); } }, [externalValueDeps, hasItemPath, iterateArrayValueDeps, iterateRestoreValueDeps, syncExternalValueUpdate]); (0, _useUpdateEffect.default)(() => { if (!hasItemPath) { syncExternalValueUpdate(); } }, [externalValueDeps, hasItemPath, iterateArrayValueDeps, iterateRestoreValueDeps, syncExternalValueUpdate]); const setHasFocus = (0, _react.useCallback)(async (hasFocus, overrideValue, localAdditionalArgs) => { const args = getEventArgs({ eventName: hasFocus ? 'onFocus' : 'onBlur', overrideValue, additionalArgs: localAdditionalArgs ? { ...additionalArgs, ...localAdditionalArgs } : additionalArgs }); if (hasFocus) { hasFocusRef.current = true; onFocus?.(...args); setMountedFieldState(identifier, { isFocused: true }); } else { hasFocusRef.current = false; onBlur?.(...args); setMountedFieldState(identifier, { isFocused: false }); if (!changedRef.current && !validateUnchanged) { return undefined; } addToPool('onBlurValidator', () => { setValidatedValidatorValue('onBlurValidator', overrideValue !== null && overrideValue !== void 0 ? overrideValue : valueRef.current); return startOnBlurValidatorProcess({ overrideValue }); }, (0, _isAsync.isAsync)(onBlurValidatorRef.current)); await runPool(() => { revealError(); forceUpdate(); }); } }, [getEventArgs, additionalArgs, onFocus, setMountedFieldState, identifier, onBlur, validateUnchanged, addToPool, onBlurValidatorRef, runPool, startOnBlurValidatorProcess, setValidatedValidatorValue, revealError]); const updateValue = (0, _react.useCallback)(async (newValue, options) => { var _transformers$current; const currentValue = valueRef.current; const valueIsUnchanged = newValue === currentValue; if (!executeOnChangeRegardlessOfUnchangedValue && valueIsUnchanged) { return undefined; } 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, { preventUpdate: options?.preventUpdate }); } if (itemPath) { handleChangeIterateContext?.(makeIteratePath(itemPath, '', { omitSectionPath: true }), contextValue); } addToPool('onChangeValidator', () => { setValidatedValidatorValue('onChangeValidator'); return validateValue(); }, (0, _isAsync.isAsync)(onChangeValidatorRef.current)); addToPool('onChangeContext', callOnChangeContext, (0, _isAsync.isAsync)(onChangeContext)); await runPool(() => { handleError(); }); }, [executeOnChangeRegardlessOfUnchangedValue, transformers, emptyValue, additionalArgs, hasPath, itemPath, addToPool, validateValue, setValidatedValidatorValue, onChangeValidatorRef, callOnChangeContext, onChangeContext, runPool, handlePathChangeUnvalidatedDataContext, nestedIteratePath, identifier, handleChangeIterateContext, makeIteratePath, handleError]); const setDisplayValue = (0, _react.useCallback)((value, options) => { const { path: fieldPath = itemPath ? identifier : path, type = 'field' } = options || {}; if (!fieldPath || !fieldDisplayValueRef?.current) { return undefined; } fieldDisplayValueRef.current[fieldPath] = valueEqualsEmptyValue(valueRef.current) ? { type } : { value, type }; }, [identifier, fieldDisplayValueRef, itemPath, path, valueEqualsEmptyValue]); const handleChange = (0, _react.useCallback)(async (argFromInput, localAdditionalArgs = undefined, options) => { const currentValue = valueRef.current; const fromInput = transformers.current.fromInput(argFromInput); const valueIsUnchanged = fromInput === currentValue; if (!executeOnChangeRegardlessOfUnchangedValue && valueIsUnchanged) { return undefined; } setChanged(true); if (asyncBehaviorIsEnabled) { hideError(); await updateValue(fromInput, options); } else { updateValue(fromInput, options); } if ((0, _isAsync.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()) { var _await$onChange; await setEventResult((_await$onChange = await onChange?.(...args)) !== null && _await$onChange !== void 0 ? _await$onChange : null); } else { await setEventResult(null); } }, true); } else { var _onChange; const args = getEventArgs({ eventName: 'onChange', additionalArgs: localAdditionalArgs ? { ...additionalArgs, ...localAdditionalArgs } : additionalArgs }); setEventResult((_onChange = onChange?.(...args)) !== null && _onChange !== void 0 ? _onChange : null); } await runPool(); }, [addToPool, additionalArgs, asyncBehaviorIsEnabled, defineAsyncProcess, executeOnChangeRegardlessOfUnchangedValue, getEventArgs, hasError, hideError, onChange, runPool, setChanged, setEventResult, transformers, updateValue, yieldAsyncProcess]); const handleFocus = (0, _react.useCallback)(() => setHasFocus(true), [setHasFocus]); const handleBlur = (0, _react.useCallback)(() => setHasFocus(false), [setHasFocus]); setFieldInternalsDataContext?.(identifier, { id, props }); const activeIndexTmpRef = (0, _react.useRef)(activeIndex); (0, _react.useEffect)(() => { activeIndexTmpRef.current = activeIndex; }, [activeIndex]); (0, _react.useMemo)(() => { setMountedFieldState(identifier, { isPreMounted: true }); if (typeof isVisible === 'boolean') { setMountedFieldState(identifier, { isVisible }); } }, [setMountedFieldState, identifier, isVisible]); (0, _react.useEffect)(() => { if (prerenderFieldProps) { return undefined; } if (typeof activeIndexRef?.current === 'number') { setMountedFieldState(identifier, { wasStepChange: false }); return () => { const wasStepChange = typeof activeIndex === 'number' && activeIndexRef.current !== activeIndexTmpRef.current; setMountedFieldState(identifier, { wasStepChange }); }; } return undefined; }, [activeIndex, activeIndexRef, identifier, prerenderFieldProps, setMountedFieldState]); (0, _react.useEffect)(() => { if (prerenderFieldProps) { return undefined; } setMountedFieldState(identifier, { isMounted: true, isPreMounted: true }); setMountedFieldSnapshot?.(identifier, { isMounted: true }); return () => { setMountedFieldState(identifier, { isMounted: false, isPreMounted: false }); setMountedFieldSnapshot?.(identifier, { isMounted: false }); }; }, [identifier, prerenderFieldProps, setMountedFieldSnapshot, setMountedFieldState]); (0, _react.useEffect)(() => { if (!omitMultiplePathWarning && !isParentRelativePath && process.env.NODE_ENV !== 'production' && (hasPath || hasItemPath) && (hasPath ? !iterateItemContext : true) && existingFieldsRef?.current) { const existingFields = existingFieldsRef.current; if (existingFields.has(identifier)) { (0, _componentHelper.warn)('Path declared multiple times:', identifier); } else { existingFields.set(identifier, true); return () => { existingFields.delete(identifier); }; } } return undefined; }, [existingFieldsRef, hasItemPath, hasPath, identifier, iterateItemContext, isParentRelativePath, omitMultiplePathWarning]); (0, _react.useEffect)(() => { if (prerenderFieldProps) { return undefined; } const mountedFields = mountedFieldsRef?.current; return () => { Promise.resolve().then(() => { const isMounted = mountedFields?.get?.(identifier)?.isMounted === true; const sharedAttachments = dataContext?.id ? (0, _useSharedState.createSharedState)((0, _useSharedState.createReferenceKey)(dataContext.id, 'attachments')).get?.() : undefined; const hasFieldConnection = Boolean(sharedAttachments?.fieldConnectionsRef?.current?.[identifier]); if (!isMounted && !hasFieldConnection) { setFieldErrorDataContext?.(identifier, undefined); setFieldErrorBoundary?.(identifier, undefined); } }); localErrorRef.current = undefined; }; }, [identifier, dataContext.id, mountedFieldsRef, prerenderFieldProps, setFieldErrorBoundary, setFieldErrorDataContext, localErrorRef]); (0, _react.useEffect)(() => { if (prerenderFieldProps) { return undefined; } return () => { setFieldErrorWizard?.(wizardIndex, identifier, undefined); }; }, [identifier, prerenderFieldProps, setFieldErrorWizard, wizardIndex]); (0, _react.useEffect)(() => { validateValue(); }, [validateValue]); const previousLocaleRef = (0, _react.useRef)(locale); (0, _useUpdateEffect.default)(() => { if (previousLocaleRef.current !== locale) { previousLocaleRef.current = locale; const hasValidationError = hasError() || fieldStateRef.current === 'error'; const hasVisibleError = revealErrorRef.current === true; const shouldRevalidateOnLocaleChange = changedRef.current || hasValidationError || hasVisibleError || validateInitially || validateUnchanged; if (prerenderFieldProps || valueEqualsEmptyValue(valueRef.current) && !shouldRevalidateOnLocaleChange) { return undefined; } if (onBlurValidatorRef.current && shouldRevalidateOnLocaleChange) { addToPool('onBlurValidator', () => { setValidatedValidatorValue('onBlurValidator'); return startOnBlurValidatorProcess(); }, (0, _isAsync.isAsync)(onBlurValidatorRef.current)); runPool(() => { revealError(); forceUpdate(); }); return undefined; } } }, [addToPool, forceUpdate, hasError, locale, prerenderFieldProps, revealError, runPool, startOnBlurValidatorProcess, setValidatedValidatorValue, validateInitially, validateUnchanged, valueEqualsEmptyValue]); (0, _react.useEffect)(() => { if (prerenderFieldProps || !dataContext?.id) { return undefined; } const sharedAttachments = (0, _useSharedState.createSharedState)((0, _useSharedState.createReferenceKey)(dataContext.id, 'attachments')).get?.(); const status = sharedAttachments?.fieldStatusRef?.current?.[identifier]; if (status) { void setEventResult(status); } }, [dataContext?.id, identifier, locale, prerenderFieldProps, setEventResult]); (0, _react.useEffect)(() => { if (!localErrorInitiatorRef.current) { const error = contextErrorRef.current; if (error) { persistErrorState('weak', 'dataContextError', error); if (validateInitially) { handleError(); } } else { clearErrorState(); } } }, [dataContextErrors, clearErrorState, handleError, persistErrorState, prepareError, validateInitially, localErrorInitiatorRef, contextErrorRef]); const internalData = dataContext.internalDataRef?.current; const tmpTransValueRef = (0, _react.useRef)({ itemPath: id }); const setContextData = (0, _react.useCallback)(({ preventUpdate = undefined } = {}) => { if (!hasPath && !hasItemPath) { return undefined; } let valueToStore = valueProp; const storePath = nestedIteratePath ? makeIteratePath(itemPath, nestedIteratePath) : identifier; const hasValue = _index.default.has(internalData, storePath) || storePath === '/'; const existingValue = storePath === '/' ? internalData : hasValue ? _index.default.get(internalData, storePath) : undefined; if (dataContext.id && !hasValue && typeof existingValue === 'undefined' && typeof valueToStore === 'undefined') { const sharedState = (0, _useSharedState.createSharedState)(dataContext.id); const hasValue = _index.default.has(sharedState.data, storePath); if (hasValue) { const sharedValue = _index.default.get(sharedState.data, storePath); if (sharedValue) { valueToStore = sharedValue; } } } const hasDefaultValue = typeof defaultValueRef.current !== 'undefined' && typeof valueToStore === 'undefined'; if (hasDefaultValue) { valueToStore = defaultValueRef.current; defaultValueRef.current = undefined; } else if (!hasValue && typeof valueToStore === 'undefined') { valueToStore = emptyValue; } let skipEqualCheck = false; if (hasItemPath) { if (existingValue === valueToStore) { if (hasValue) { return; } else { if (tmpTransValueRef.current['itemPath'] === valueToStore) { return; } } } tmpTransValueRef.current['itemPath'] = valueToStore; if (iterateArrayValue === clearedArray) { return; } if (typeof valueToStore === 'undefined' && typeof existingValue !== 'undefined') { valueToStore = existingValue; } if (itemPath === '/') { if (existingValue === _Provider.clearedData) { valueRef.current = undefined; } if (hasDefaultValue && Array.isArray(existingValue)) { skipEqualCheck = true; } } } if (updateContextDataInSync) { if (hasDefaultValue && hasValue) { return; } if (Array.isArray(existingValue) && Array.isArray(valueToStore)) { if (valueToStore.length !== existingValue.length) { skipEqualCheck = true; } valueRef.current = existingValue; } } if (typeof valueToStore === 'undefined' && typeof existingValue !== 'undefined') { valueToStore = existingValue; } if (!skipEqualCheck && hasValue && (valueToStore === existingValue || valueRef.current === existingValue)) { return; } if (storePath in tmpTransValueRef.current && tmpTransValueRef.current[storePath] === valueToStore) { return; } const valueIn = transformers.current.transformIn(valueToStore); const transformedValue = transformers.current.transformOut(valueIn, transformers.current.provideAdditionalArgs(valueIn)); if (transformedValue !== valueToStore) { tmpTransValueRef.current[storePath] = valueToStore; valueToStore = transformedValue; } if (hasItemPath && !nestedIteratePath && iterateIndex < iterateArrayValue?.length - 1) { preventUpdate = true; } updateDataValueDataContext?.(storePath, valueToStore, { preventUpdate }); if (!preventUpdate) { validateDataDataContext?.(); } }, [dataContext.id, emptyValue, hasItemPath, hasPath, identifier, internalData, itemPath, iterateArrayValue, iterateIndex, makeIteratePath, nestedIteratePath, transformers, updateContextDataInSync, updateDataValueDataContext, validateDataDataContext, valueProp]); const isEmptyData = (0, _react.useCallback)(() => { var _dataContext$props$em; return dataContext.isEmptyDataRef?.current || dataContext.internalDataRef?.current === ((_dataContext$props$em = dataContext.props?.emptyData) !== null && _dataContext$props$em !== void 0 ? _dataContext$props$em : _Provider.clearedData); }, [dataContext.internalDataRef, dataContext.props?.emptyData, externalValueDeps]); (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(() => { if (isEmptyData()) { defaultValueRef.current = defaultValue; setChanged(false); hideError(); clearErrorState(); } }, [clearErrorState, defaultValue, hideError, isEmptyData, setChanged]); (0, _react.useMemo)(() => { if (updateContextDataInSync && !isEmptyData()) { setContextData({ preventUpdate: true }); } }, [isEmptyData, updateContextDataInSync, setContextData]); (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(() => { if (!updateContextDataInSync && !isEmptyData()) { setContextData(); } if (forceUpdateWhenContextDataIsSet) { forceUpdate(); } }, [forceUpdateWhenContextDataIsSet, isEmptyData, setContextData, updateContextDataInSync]); (0, _react.useEffect)(() => { if (isEmptyData()) { setContextData(); validateValue(); } }, [isEmptyData, setContextData, validateValue]); (0, _react.useEffect)(() => { if (showAllErrors || showBoundaryErrors) { if (fieldStateRef.current !== 'validating') { revealError(); } } else if (showBoundaryErrors === false) { hideError(); } }, [fieldStateRef, hideError, revealError, showAllErrors, showBoundaryErrors]); (0, _react.useEffect)(() => { if (dataContext.formState === 'pending' && (onChangeValidatorRef.current || onBlurValidatorRef.current)) { hideError(); forceUpdate(); } }, [dataContext.formState, hideError, onBlurValidatorRef, onChangeValidatorRef]); const shouldRunValidatorOnSubmit = (0, _react.useCallback)((validatorName, validator) => { var _getValidatorOptions$; const runOnSubmit = (_getValidatorOptions$ = (0, _index2.getValidatorOptions)(validator)?.runOnSubmit) !== null && _getValidatorOptions$ !== void 0 ? _getValidatorOptions$ : 'always'; if (runOnSubmit === 'never') { return false; } if (runOnSubmit === 'when-changed') { return isValidatorValueChanged(validatorName); } return true; }, [isValidatorValueChanged]); const onSubmitHandler = (0, _react.useCallback)(async () => { if (hasError()) { return undefined; } if (shouldRunValidatorOnSubmit('onChangeValidator', onChangeValidatorRef.current)) { addToPool('onChangeValidator', () => { setValidatedValidatorValue('onChangeValidator'); return startOnChangeValidatorValidation(); }, (0, _isAsync.isAsync)(onChangeValidatorRef.current)); } if (shouldRunValidatorOnSubmit('onBlurValidator', onBlurValidatorRef.current)) { addToPool('onBlurValidator', () => { setValidatedValidatorValue('onBlurValidator'); return startOnBlurValidatorProcess(); }, (0, _isAsync.isAsync)(onBlurValidatorRef.current)); } await runPool(); }, [hasError, addToPool, shouldRunValidatorOnSubmit, startOnChangeValidatorValidation, onChangeValidatorRef, startOnBlurValidatorProcess, onBlurValidatorRef, setValidatedValidatorValue, runPool]); (0, _react.useEffect)(() => { setFieldEventListener?.(identifier, 'onSubmitCall', onSubmitHandler); }, [identifier, onSubmitHandler, setFieldEventListener]); (0, _react.useEffect)(() => { if (inFieldBlock) { setBlockRecord?.({ identifier, type: 'error', content: error, showInitially: true, show: true }); setBlockRecord?.({ identifier, type: 'warning', content: warning, showInitially: true, show: true }); setBlockRecord?.({ identifier, type: 'information', content: info, showInitially: true, show: true }); return () => { if (mountedFieldsRefFieldBlock) { mountedFieldsRefFieldBlock.current.set(identifier, true); } }; } return undefined; }, [error, identifier, inFieldBlock, info, mountedFieldsRefFieldBlock, setBlockRecord, warning]); const statusRef = (0, _react.useRef)(null); (0, _react.useEffect)(() => { if (!onStatusChange) { return undefined; } const status = { info: infoRef.current, warning: warningRef.current, error: bufferedErrorRef.current }; const statusVisible = Boolean(status.info) || Boolean(status.warning) || errorIsVisible && Boolean(status.error); const previous = statusRef.current; const hasChanged = !previous || previous.error !== status.error || previous.warning !== status.warning || previous.info !== status.info || previous.validateInitially !== validateInitially; if (hasChanged && (statusVisible || previous)) { statusRef.current = { warning: status.warning, info: status.info, error: status.error, validateInitially }; onStatusChange(status); } }, [onStatusChange, bufferedError, warning, info, validateInitially, errorIsVisible, infoRef, warningRef, bufferedErrorRef]); const connections = (0, _react.useMemo)(() => { return { setEventResult, emptyValue }; }, [emptyValue, setEventResult]); setFieldConnectionDataContext?.(identifier, connections); const htmlAttributes = (0, _react.useMemo)(() => { return Object.keys(props).reduce((acc, cur) => { if (cur.startsWith('aria-') || cur.startsWith('data-')) { acc[cur] = props[cur]; } return acc; }, { ...props.htmlAttributes }); }, [props]); if (bufferedError) { htmlAttributes['aria-invalid'] = bufferedError ? 'true' : 'false'; } if (required) { htmlAttributes['aria-required'] = 'true'; } if (inFieldBlock) { if (mountedFieldsRefFieldBlock) { mountedFieldsRefFieldBlock.current.set(identifier, true); } const stateIds = fieldBlockContext.fieldStateIdsRef?.current; if (stateIds) { htmlAttributes['aria-describedby'] = (0, _componentHelper.combineDescribedBy)(htmlAttributes, [bufferedError && stateIds.error, warning && stateIds.warning, info && stateIds.information].filter(Boolean)); } } else { const ids = [(bufferedError || error) && `${id}-form-status--error`, warning && `${id}-form-status--warning`, info && `${id}-form-status--information`].filter(Boolean); if (ids.length) { htmlAttributes['aria-describedby'] = (0, _componentHelper.combineDescribedBy)(htmlAttributes, ids); } } const help = props.help; if (help?.title || help?.content) { htmlAttributes['aria-describedby'] = (0, _componentHelper.combineDescribedBy)(htmlAttributes, `${id}-help`); } const fieldBlockProps = { info: !inFieldBlock ? infoRef.current : undefined, warning: !inFieldBlock ? warningRef.current : undefined, error: !inFieldBlock ? bufferedError : undefined, required, label: props.label, labelDescription: props.labelDescription, labelDescriptionInline: props.labelDescriptionInline, labelSuffix: props.labelSuffix, labelSize: props.labelSize, labelSrOnly: props.labelSrOnly, statusPosition: props.statusPosition, layout: props.layout, layoutOptions: props.layoutOptions, help: props.help, disabled: onBlurValidator && asyncProcessRef.current === 'onBlurValidator' && fieldStateRef.current === 'validating' ? true : disabled, fieldState: (0, _useFieldError.resolveValidatingState)(fieldStateRef.current), labelHeight: typeof props['size'] === 'string' ? props['size'] : undefined }; const sharedData = (0, _useSharedState.createSharedState)('field-block-props-' + id); sharedData.set(fieldBlockProps, { silent: true }); (0, _react.useEffect)(() => { isInternalRerenderRef.current = undefined; }); return { ...props, ...fieldBlockProps, name: props.name || props.path?.replace('/', '') || id, autoComplete: (_props$autoComplete = props.autoComplete) !== null && _props$autoComplete !== void 0 ? _props$autoComplete : typeof dataContext.autoComplete === 'boolean' ? dataContext.autoComplete ? 'on' : 'off' : undefined, id, value: transformers.current.toInput(valueRef.current), hasError: errorIsVisible, isChanged: Boolean(changedRef.current), props, htmlAttributes, setHasFocus, handleFocus, handleBlur, handleChange, updateValue, setChanged, setDisplayValue, validateValue, revealError, handleError, forceUpdate, additionalArgs, dataContext }; } const clearedArray = exports.clearedArray = []; //# sourceMappingURL=useFieldProps.js.map