@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
60 lines (59 loc) • 2.09 kB
JavaScript
"use client";
import React, { useCallback, useContext, useReducer, useRef } from 'react';
import FieldBoundaryContext from './FieldBoundaryContext';
import DataContext from '../Context';
export default function FieldBoundaryProvider(props) {
const {
showErrors = undefined,
onPathError = null,
children
} = props;
const [, forceUpdate] = useReducer(() => ({}), {});
const {
showAllErrors
} = useContext(DataContext);
const onPathErrorRef = useRef(onPathError);
onPathErrorRef.current = onPathError;
const errorsRef = useRef({});
const showBoundaryErrorsRef = useRef(showErrors);
const hasError = Object.keys(errorsRef.current).length > 0;
const hasSubmitError = showAllErrors && hasError;
const setFieldError = useCallback((path, error) => {
var _onPathErrorRef$curre;
if (error) {
errorsRef.current[path] = !!error;
} else {
var _errorsRef$current;
(_errorsRef$current = errorsRef.current) === null || _errorsRef$current === void 0 ? true : delete _errorsRef$current[path];
}
forceUpdate();
(_onPathErrorRef$curre = onPathErrorRef.current) === null || _onPathErrorRef$curre === void 0 ? void 0 : _onPathErrorRef$curre.call(onPathErrorRef, path, error);
}, []);
const hasVisibleErrorRef = useRef(new Map());
const revealError = useCallback((path, hasError) => {
if (hasError) {
hasVisibleErrorRef.current.set(path, hasError);
} else {
hasVisibleErrorRef.current.delete(path);
}
forceUpdate();
}, []);
const setShowBoundaryErrors = useCallback(showBoundaryErrors => {
showBoundaryErrorsRef.current = showBoundaryErrors ? Date.now() : false;
forceUpdate();
}, []);
const context = {
hasError,
hasSubmitError,
hasVisibleError: hasVisibleErrorRef.current.size > 0,
errorsRef,
showBoundaryErrors: showBoundaryErrorsRef.current,
setShowBoundaryErrors,
setFieldError,
revealError
};
return React.createElement(FieldBoundaryContext.Provider, {
value: context
}, children);
}
//# sourceMappingURL=FieldBoundaryProvider.js.map