@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
1,081 lines (1,080 loc) • 46 kB
JavaScript
"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
} = {}) {
var _dataContext$props, _dataContext$props$lo, _dataContext$props2, _dataContext$props4, _dataContext$internal, _dataContext$props6, _props$path, _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)(undefined);
(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 === null || dataContext === void 0 || (_dataContext$props = dataContext.props) === null || _dataContext$props === void 0 ? void 0 : _dataContext$props.onChange;
const locale = (_dataContext$props$lo = dataContext === null || dataContext === void 0 || (_dataContext$props2 = dataContext.props) === null || _dataContext$props2 === void 0 ? void 0 : _dataContext$props2.locale) !== null && _dataContext$props$lo !== void 0 ? _dataContext$props$lo : sharedLocale;
const disabled = disabledProp !== null && disabledProp !== void 0 ? disabledProp : 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
} = 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 === null || sectionSchemaPathsRef === void 0 ? void 0 : sectionSchemaPathsRef.current;
const hasSectionSchema = Boolean((sectionSchemaPaths === null || sectionSchemaPaths === void 0 ? void 0 : sectionSchemaPaths.size) && identifier && Array.from(sectionSchemaPaths).some(sectionSchemaPath => {
if (sectionSchemaPath === '/') {
return true;
}
return identifier === sectionSchemaPath || identifier.startsWith(`${sectionSchemaPath}/`);
}));
const defaultValueRef = (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 {
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,
transformers,
emptyValue: defaultValue ? undefined : emptyValue
});
const externalValueDeps = tmpValue;
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)(() => {
var _dataContext$props3;
if (finalSchema && !hasZodSchema && !omitMultiplePathWarning && hasDataContext && !(dataContext !== null && dataContext !== void 0 && (_dataContext$props3 = dataContext.props) !== null && _dataContext$props3 !== void 0 && _dataContext$props3.ajvInstance)) {
(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 === null || dataContext === void 0 || (_dataContext$props4 = dataContext.props) === null || _dataContext$props4 === void 0 ? void 0 : _dataContext$props4.ajvInstance, omitMultiplePathWarning]);
const required = (0, _react.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 = _index.default.has(schema, pathWithoutLast) ? _index.default.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]);
});
(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 => {
var _fieldInternalsRef$cu;
return ((_fieldInternalsRef$cu = fieldInternalsRef.current) === null || _fieldInternalsRef$cu === void 0 ? void 0 : _fieldInternalsRef$cu[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 === null || dataContext === void 0 ? void 0 : 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 externalValueDidChangeRef = (0, _react.useRef)(false);
(0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(() => {
if (valueRef.current !== externalValue) {
valueRef.current = externalValue;
externalValueDidChangeRef.current = true;
}
}, [externalValueDeps, hasItemPath]);
(0, _useUpdateEffect.default)(() => {
if (externalValueDidChangeRef.current) {
externalValueDidChangeRef.current = false;
if (!validateContinuously && valueEqualsEmptyValue(valueRef.current)) {
hideError();
}
validateValue();
forceUpdate();
}
}, [externalValueDeps, validateContinuously, valueEqualsEmptyValue]);
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 === null || onFocus === void 0 || onFocus(...args);
setMountedFieldStateDataContext(identifier, {
isFocused: true
});
} else {
hasFocusRef.current = false;
onBlur === null || onBlur === void 0 || onBlur(...args);
setMountedFieldStateDataContext(identifier, {
isFocused: false
});
if (!changedRef.current && !validateUnchanged) {
return undefined;
}
addToPool('onBlurValidator', async () => await startOnBlurValidatorProcess({
overrideValue
}), (0, _isAsync.isAsync)(onBlurValidatorRef.current));
await runPool(() => {
revealError();
forceUpdate();
});
}
}, [getEventArgs, additionalArgs, onFocus, setMountedFieldStateDataContext, identifier, onBlur, validateUnchanged, addToPool, onBlurValidatorRef, runPool, startOnBlurValidatorProcess, revealError]);
const updateValue = (0, _react.useCallback)(async newValue => {
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);
}
if (itemPath) {
handleChangeIterateContext === null || handleChangeIterateContext === void 0 || handleChangeIterateContext(makeIteratePath(itemPath, '', {
omitSectionPath: true
}), contextValue);
}
addToPool('onChangeValidator', validateValue, (0, _isAsync.isAsync)(onChangeValidatorRef.current));
addToPool('onChangeContext', callOnChangeContext, (0, _isAsync.isAsync)(onChangeContext));
await runPool(() => {
handleError();
});
}, [executeOnChangeRegardlessOfUnchangedValue, transformers, emptyValue, additionalArgs, hasPath, itemPath, addToPool, validateValue, 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 !== null && fieldDisplayValueRef !== void 0 && 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) => {
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);
} else {
updateValue(fromInput);
}
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 === null || onChange === void 0 ? void 0 : 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 === null || onChange === void 0 ? void 0 : 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 === null || setFieldInternalsDataContext === void 0 || setFieldInternalsDataContext(identifier, {
id,
props
});
const activeIndexTmpRef = (0, _react.useRef)(activeIndex);
(0, _react.useEffect)(() => {
activeIndexTmpRef.current = activeIndex;
}, [activeIndex]);
(0, _react.useMemo)(() => {
setMountedFieldStateDataContext(identifier, {
isPreMounted: true
});
if (typeof isVisible === 'boolean') {
setMountedFieldStateDataContext(identifier, {
isVisible
});
}
}, [setMountedFieldStateDataContext, identifier, isVisible]);
(0, _react.useEffect)(() => {
if (prerenderFieldProps) {
return undefined;
}
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
});
};
}
return undefined;
}, [activeIndex, activeIndexRef, identifier, prerenderFieldProps, setMountedFieldStateDataContext]);
(0, _react.useEffect)(() => {
if (prerenderFieldProps) {
return undefined;
}
setMountedFieldStateDataContext(identifier, {
isMounted: true,
isPreMounted: true
});
setMountedFieldSnapshot === null || setMountedFieldSnapshot === void 0 || setMountedFieldSnapshot(identifier, {
isMounted: true
});
return () => {
setMountedFieldStateDataContext(identifier, {
isMounted: false,
isPreMounted: false
});
setMountedFieldSnapshot === null || setMountedFieldSnapshot === void 0 || setMountedFieldSnapshot(identifier, {
isMounted: false
});
};
}, [identifier, prerenderFieldProps, setMountedFieldSnapshot, setMountedFieldStateDataContext]);
(0, _react.useEffect)(() => {
if (!omitMultiplePathWarning && !isParentRelativePath && 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)) {
(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 === null || mountedFieldsRef === void 0 ? void 0 : mountedFieldsRef.current;
return () => {
Promise.resolve().then(() => {
var _mountedFields$get, _createSharedState$ge, _createSharedState, _sharedAttachments$fi;
const isMounted = (mountedFields === null || mountedFields === void 0 || (_mountedFields$get = mountedFields.get) === null || _mountedFields$get === void 0 || (_mountedFields$get = _mountedFields$get.call(mountedFields, identifier)) === null || _mountedFields$get === void 0 ? void 0 : _mountedFields$get.isMounted) === true;
const sharedAttachments = dataContext !== null && dataContext !== void 0 && dataContext.id ? (_createSharedState$ge = (_createSharedState = (0, _useSharedState.createSharedState)((0, _useSharedState.createReferenceKey)(dataContext.id, 'attachments'))).get) === null || _createSharedState$ge === void 0 ? void 0 : _createSharedState$ge.call(_createSharedState) : undefined;
const hasFieldConnection = Boolean(sharedAttachments === null || sharedAttachments === void 0 || (_sharedAttachments$fi = sharedAttachments.fieldConnectionsRef) === null || _sharedAttachments$fi === void 0 || (_sharedAttachments$fi = _sharedAttachments$fi.current) === null || _sharedAttachments$fi === void 0 ? void 0 : _sharedAttachments$fi[identifier]);
if (!isMounted && !hasFieldConnection) {
setFieldErrorDataContext === null || setFieldErrorDataContext === void 0 || setFieldErrorDataContext(identifier, undefined);
setFieldErrorBoundary === null || setFieldErrorBoundary === void 0 || setFieldErrorBoundary(identifier, undefined);
}
});
localErrorRef.current = undefined;
};
}, [identifier, dataContext.id, mountedFieldsRef, prerenderFieldProps, setFieldErrorBoundary, setFieldErrorDataContext, localErrorRef]);
(0, _react.useEffect)(() => {
if (prerenderFieldProps) {
return undefined;
}
return () => {
setFieldErrorWizard === null || setFieldErrorWizard === void 0 || 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', async () => await startOnBlurValidatorProcess(), (0, _isAsync.isAsync)(onBlurValidatorRef.current));
runPool(() => {
revealError();
forceUpdate();
});
return undefined;
}
}
}, [addToPool, forceUpdate, hasError, locale, prerenderFieldProps, revealError, runPool, startOnBlurValidatorProcess, validateInitially, validateUnchanged, valueEqualsEmptyValue]);
(0, _react.useEffect)(() => {
var _createSharedState$ge2, _createSharedState2, _sharedAttachments$fi2;
if (prerenderFieldProps || !(dataContext !== null && dataContext !== void 0 && dataContext.id)) {
return undefined;
}
const sharedAttachments = (_createSharedState$ge2 = (_createSharedState2 = (0, _useSharedState.createSharedState)((0, _useSharedState.createReferenceKey)(dataContext.id, 'attachments'))).get) === null || _createSharedState$ge2 === void 0 ? void 0 : _createSharedState$ge2.call(_createSharedState2);
const status = sharedAttachments === null || sharedAttachments === void 0 || (_sharedAttachments$fi2 = sharedAttachments.fieldStatusRef) === null || _sharedAttachments$fi2 === void 0 || (_sharedAttachments$fi2 = _sharedAttachments$fi2.current) === null || _sharedAttachments$fi2 === void 0 ? void 0 : _sharedAttachments$fi2[identifier];
if (status) {
void setEventResult(status);
}
}, [dataContext === null || dataContext === void 0 ? void 0 : 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$internal = dataContext.internalDataRef) === null || _dataContext$internal === void 0 ? void 0 : _dataContext$internal.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 === null || iterateArrayValue === void 0 ? void 0 : iterateArrayValue.length) - 1) {
preventUpdate = true;
}
updateDataValueDataContext === null || updateDataValueDataContext === void 0 || updateDataValueDataContext(storePath, valueToStore, {
preventUpdate
});
if (!preventUpdate) {
validateDataDataContext === null || validateDataDataContext === void 0 || 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$isEmptyD, _dataContext$internal2, _dataContext$props$em, _dataContext$props5;
return ((_dataContext$isEmptyD = dataContext.isEmptyDataRef) === null || _dataContext$isEmptyD === void 0 ? void 0 : _dataContext$isEmptyD.current) || ((_dataContext$internal2 = dataContext.internalDataRef) === null || _dataContext$internal2 === void 0 ? void 0 : _dataContext$internal2.current) === ((_dataContext$props$em = (_dataContext$props5 = dataContext.props) === null || _dataContext$props5 === void 0 ? void 0 : _dataContext$props5.emptyData) !== null && _dataContext$props$em !== void 0 ? _dataContext$props$em : _Provider.clearedData);
}, [dataContext.internalDataRef, (_dataContext$props6 = dataContext.props) === null || _dataContext$props6 === void 0 ? void 0 : _dataContext$props6.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 onSubmitHandler = (0, _react.useCallback)(async () => {
if (hasError()) {
return undefined;
}
addToPool('onChangeValidator', startOnChangeValidatorValidation, (0, _isAsync.isAsync)(onChangeValidatorRef.current));
addToPool('onBlurValidator', startOnBlurValidatorProcess, (0, _isAsync.isAsync)(onBlurValidatorRef.current));
await runPool();
}, [hasError, addToPool, startOnChangeValidatorValidation, onChangeValidatorRef, startOnBlurValidatorProcess, onBlurValidatorRef, runPool]);
(0, _react.useEffect)(() => {
setFieldEventListener === null || setFieldEventListener === void 0 || setFieldEventListener(identifier, 'onSubmitCall', onSubmitHandler);
}, [identifier, onSubmitHandler, setFieldEventListener]);
(0, _react.useEffect)(() => {
if (inFieldBlock) {
setBlockRecord === null || setBlockRecord === void 0 || setBlockRecord({
identifier,
type: 'error',
content: error,
showInitially: true,
show: true
});
setBlockRecord === null || setBlockRecord === void 0 || setBlockRecord({
identifier,
type: 'warning',
content: warning,
showInitially: true,
show: true
});
setBlockRecord === null || setBlockRecord === void 0 || 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 === null || setFieldConnectionDataContext === void 0 || 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) {
var _fieldBlockContext$fi;
if (mountedFieldsRefFieldBlock) {
mountedFieldsRefFieldBlock.current.set(identifier, true);
}
const stateIds = (_fieldBlockContext$fi = fieldBlockContext.fieldStateIdsRef) === null || _fieldBlockContext$fi === void 0 ? void 0 : _fieldBlockContext$fi.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 !== null && help !== void 0 && help.title || help !== null && help !== void 0 && 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.useSharedState)('field-block-props-' + id);
sharedData.set(fieldBlockProps);
(0, _react.useEffect)(() => {
isInternalRerenderRef.current = undefined;
});
return {
...props,
...fieldBlockProps,
name: props.name || ((_props$path = props.path) === null || _props$path === void 0 ? void 0 : _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