UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

72 lines (71 loc) 2.6 kB
"use strict"; "use client"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = FieldBoundaryProvider; var _react = require("react"); var _FieldBoundaryContext = _interopRequireDefault(require("./FieldBoundaryContext.js")); var _Context = _interopRequireDefault(require("../Context.js")); var _jsxRuntime = require("react/jsx-runtime"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } function FieldBoundaryProvider(props) { const { showErrors = undefined, onPathError = null, children } = props; const [, forceUpdate] = (0, _react.useReducer)(() => ({}), {}); const { showAllErrors } = (0, _react.useContext)(_Context.default); const onPathErrorRef = (0, _react.useRef)(onPathError); onPathErrorRef.current = onPathError; const errorsRef = (0, _react.useRef)({}); const showBoundaryErrorsRef = (0, _react.useRef)(showErrors); const hasError = Object.keys(errorsRef.current).length > 0; const verifyFieldError = (0, _react.useCallback)(() => { return Object.keys(errorsRef.current).length > 0; }, []); const hasSubmitError = showAllErrors && hasError; const setFieldError = (0, _react.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 || delete _errorsRef$current[path]; } forceUpdate(); (_onPathErrorRef$curre = onPathErrorRef.current) === null || _onPathErrorRef$curre === void 0 || _onPathErrorRef$curre.call(onPathErrorRef, path, error); }, []); const hasVisibleErrorRef = (0, _react.useRef)(new Map()); const revealError = (0, _react.useCallback)((path, hasError) => { if (hasError) { hasVisibleErrorRef.current.set(path, hasError); } else { hasVisibleErrorRef.current.delete(path); } forceUpdate(); }, []); const setShowBoundaryErrors = (0, _react.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 (0, _jsxRuntime.jsx)(_FieldBoundaryContext.default, { value: context, children: children }); } //# sourceMappingURL=FieldBoundaryProvider.js.map