@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
62 lines (61 loc) • 1.96 kB
JavaScript
"use client";
import React, { useCallback, useContext, useReducer, useRef } from 'react';
import FieldBoundaryContext from "./FieldBoundaryContext.js";
import DataContext from "../Context.js";
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 verifyFieldError = useCallback(() => {
return Object.keys(errorsRef.current).length > 0;
}, []);
const hasSubmitError = showAllErrors && hasError;
const setFieldError = useCallback((path, error) => {
if (error) {
errorsRef.current[path] = !!error;
} else {
delete errorsRef.current?.[path];
}
forceUpdate();
onPathErrorRef.current?.(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,
verifyFieldError,
setShowBoundaryErrors,
setFieldError,
revealError
};
return React.createElement(FieldBoundaryContext.Provider, {
value: context
}, children);
}
//# sourceMappingURL=FieldBoundaryProvider.js.map