UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

508 lines (507 loc) 18.7 kB
"use strict"; "use client"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _includes = _interopRequireDefault(require("core-js-pure/stable/instance/includes.js")); var _react = require("react"); var _clsx = require("clsx"); var _index = require("../../../../components/index.js"); var _componentHelper = require("../../../../shared/component-helper.js"); var _isAsync = require("../../../../shared/helpers/isAsync.js"); var _useId = _interopRequireDefault(require("../../../../shared/helpers/useId.js")); var _WizardContext = _interopRequireDefault(require("../Context/WizardContext.js")); var _Context = _interopRequireDefault(require("../../DataContext/Context.js")); var _useEventListener = _interopRequireDefault(require("../../DataContext/Provider/useEventListener.js")); var _Handler = _interopRequireDefault(require("../../Form/Handler/Handler.js")); var _useSharedState = require("../../../../shared/helpers/useSharedState.js"); var _useHandleLayoutEffect = _interopRequireDefault(require("./useHandleLayoutEffect.js")); var _useStepAnimation = _interopRequireDefault(require("./useStepAnimation.js")); var _useVisibility = _interopRequireDefault(require("../../Form/Visibility/useVisibility.js")); var _useDataValue = _interopRequireDefault(require("../../hooks/useDataValue.js")); var _usePath = _interopRequireDefault(require("../../hooks/usePath.js")); var _DisplaySteps = require("./DisplaySteps.js"); var _IterateOverSteps = require("./IterateOverSteps.js"); var _PrerenderFieldPropsOfOtherSteps = require("./PrerenderFieldPropsOfOtherSteps.js"); var _Step = _interopRequireDefault(require("../Step/Step.js")); var _useIsomorphicLayoutEffect = require("../../../../shared/helpers/useIsomorphicLayoutEffect.js"); var _withComponentMarkers = _interopRequireDefault(require("../../../../shared/helpers/withComponentMarkers.js")); var _jsxRuntime = require("react/jsx-runtime"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } function collectIncludeWhenDependencies(children) { const dataPaths = new Set(); const dataItemPaths = new Set(); const fieldStatePaths = new Set(); const fieldStateItemPaths = new Set(); let hasWrappedStepChildren = false; const addIncludeWhen = includeWhen => { if (!includeWhen) { return; } const usesItemPath = 'itemPath' in includeWhen; const path = usesItemPath ? includeWhen.itemPath : includeWhen.path; if ('hasValue' in includeWhen) { if (usesItemPath) { dataItemPaths.add(path); } else { dataPaths.add(path); } } if ('isValid' in includeWhen) { if (usesItemPath) { fieldStateItemPaths.add(path); } else { fieldStatePaths.add(path); } } }; _react.Children.forEach(children, child => { if ((0, _react.isValidElement)(child)) { if (child.type === _Step.default) { addIncludeWhen(child.props.includeWhen); } else if (typeof child.type === 'function') { hasWrappedStepChildren = true; } } }); return { dataPaths: Array.from(dataPaths), dataItemPaths: Array.from(dataItemPaths), fieldStatePaths: Array.from(fieldStatePaths), fieldStateItemPaths: Array.from(fieldStateItemPaths), hasWrappedStepChildren }; } function WizardContainer(props) { const { className, id: idProp, mode = 'strict', initialActiveIndex = 0, omitScrollManagement, omitFocusManagement, onStepChange, children, noAnimation = false, expandedInitially = false, prerenderFieldProps = true, keepInDOM, validationMode, outset = false, ...rest } = props; const dataContext = (0, _react.useContext)(_Context.default); const { hasContext, setFormState, handleSubmitCall, setShowAllErrors, setSubmitState, hasFieldState, hasErrors, setFieldEventListener } = dataContext; const id = (0, _useId.default)(idProp); const [, forceUpdate] = (0, _react.useReducer)(() => ({}), {}); const activeIndexRef = (0, _react.useRef)(initialActiveIndex); const totalStepsRef = (0, _react.useRef)(NaN); const visitedStepsRef = (0, _react.useRef)(new Map()); const fieldErrorRef = (0, _react.useRef)(new Map()); const storeStepStateRef = (0, _react.useRef)(new Map()); const onStepChangeEventsRef = (0, _react.useRef)(new Set()); const hasErrorInOtherStepRef = (0, _react.useRef)(false); const elementRef = (0, _react.useRef)(undefined); const stepElementRef = (0, _react.useRef)(undefined); const preventNextStepRef = (0, _react.useRef)(false); const stepsRef = (0, _react.useRef)(new Map()); const tmpStepsRef = (0, _react.useRef)(undefined); const stepIndexRef = (0, _react.useRef)(-1); const updateTitlesRef = (0, _react.useRef)(undefined); const prerenderFieldPropsRef = (0, _react.useRef)({}); const bypassOnNavigation = validationMode === 'bypassOnNavigation'; const sharedStateRef = (0, _react.useRef)(undefined); sharedStateRef.current = (0, _useSharedState.useSharedState)(hasContext && id ? (0, _useSharedState.createReferenceKey)(id, 'wizard') : undefined); const hasFieldErrorInStep = (0, _react.useCallback)(index => { return Array.from(fieldErrorRef.current.values()).some(({ index: i, hasError }) => { return i === index && hasError; }); }, []); const setStepAsVisited = (0, _react.useCallback)(index => { visitedStepsRef.current.set(index, true); }, []); (0, _react.useEffect)(() => { if (!initialActiveIndex) { setStepAsVisited(activeIndexRef.current); } }, [initialActiveIndex, setStepAsVisited]); const syncStepsState = (0, _react.useCallback)((index = undefined, forStates = ['unknown', 'error']) => { const checkUnknown = (0, _includes.default)(forStates).call(forStates, 'unknown'); const checkError = (0, _includes.default)(forStates).call(forStates, 'error'); for (let i = 0; i < totalStepsRef.current; i++) { if (index !== undefined && index !== i) { continue; } let result = undefined; if (checkUnknown) { const state = i < activeIndexRef.current && visitedStepsRef.current.get(i) === undefined; if (state) { result = 'unknown'; } } if (checkError) { const state = hasFieldErrorInStep(i); const existingState = storeStepStateRef.current.get(i); if (state) { result = 'error'; } else if (existingState === 'error') { if (i === activeIndexRef.current) { result = undefined; } else { result = existingState; } } } storeStepStateRef.current.set(i, result); } }, [hasFieldErrorInStep]); const hasInvalidStepsState = (0, _react.useCallback)((index = undefined, forStates = ['unknown', 'error']) => { syncStepsState(); const checkUnknown = (0, _includes.default)(forStates).call(forStates, 'unknown'); const checkError = (0, _includes.default)(forStates).call(forStates, 'error'); for (let i = 0; i < totalStepsRef.current; i++) { if (index !== undefined && index !== i) { continue; } const state = storeStepStateRef.current.get(i); if (checkUnknown) { if (state === 'unknown') { return true; } } if (checkError) { if (state === 'error') { return true; } } } return false; }, [syncStepsState]); const setFieldError = (0, _react.useCallback)((index, path, hasError) => { fieldErrorRef.current.set(path, { index, hasError }); }, []); const preventNavigation = (0, _react.useCallback)((shouldPrevent = true) => { preventNextStepRef.current = shouldPrevent; }, []); const getStepChangeOptions = (0, _react.useCallback)(index => { const previousIndex = activeIndexRef.current; const totalSteps = Number.isNaN(totalStepsRef.current) ? stepsRef.current.size : totalStepsRef.current; const options = { preventNavigation, totalSteps, previousStep: { index: previousIndex } }; const id = stepsRef.current.get(index)?.id; if (id) { Object.assign(options, { id }); } const previousId = stepsRef.current.get(previousIndex)?.id; if (previousId) { Object.assign(options.previousStep, { id: previousId }); } return options; }, [preventNavigation]); const callOnStepChange = (0, _react.useCallback)(async (index, mode) => { if ((0, _isAsync.isAsync)(onStepChange)) { return await onStepChange(index, mode, getStepChangeOptions(index)); } return onStepChange?.(index, mode, getStepChangeOptions(index)); }, [getStepChangeOptions, onStepChange]); const { setFocus, scrollToTop, isInteractionRef } = (0, _useHandleLayoutEffect.default)({ elementRef, stepElementRef }); const executeLayoutAnimationRef = (0, _react.useRef)(undefined); (0, _useStepAnimation.default)({ activeIndexRef, stepElementRef, executeLayoutAnimationRef }); const handleLayoutEffect = (0, _react.useCallback)(() => { if (!omitFocusManagement) { setFocus(); } if (!omitScrollManagement) { scrollToTop(); } }, [omitScrollManagement, omitFocusManagement, setFocus, scrollToTop]); const handleStepChange = (0, _react.useCallback)(async ({ index, skipErrorCheck, skipStepChangeCall, skipStepChangeCallBeforeMounted, skipStepChangeCallFromHook, mode }) => { let didSubmit = false; const onSubmit = async () => { if (!skipStepChangeCallFromHook) { onStepChangeEventsRef?.current?.forEach(onStepChange => { if (typeof onStepChange === 'function') { onStepChange(index, mode, getStepChangeOptions(index)); } }); } let result = undefined; if (!skipStepChangeCall && !(skipStepChangeCallBeforeMounted && !isInteractionRef.current)) { result = await callOnStepChange(index, mode); } setFormState('abort'); setShowAllErrors(bypassOnNavigation ? false : hasInvalidStepsState(index, ['error'])); if (!preventNextStepRef.current && !(result instanceof Error)) { handleLayoutEffect(); activeIndexRef.current = index; setStepAsVisited(activeIndexRef.current); forceUpdate(); } preventNextStepRef.current = false; didSubmit = true; return result; }; await handleSubmitCall({ skipErrorCheck, skipFieldValidation: skipErrorCheck, enableAsyncBehavior: (0, _isAsync.isAsync)(onStepChange), onSubmit: bypassOnNavigation ? () => null : onSubmit }); if (!didSubmit) { if (bypassOnNavigation) { await onSubmit(); } else { if (mode === 'next') { if (!hasInvalidStepsState(activeIndexRef.current) && !hasErrors?.() && !hasFieldState?.('pending')) { await onSubmit(); } } } } }, [bypassOnNavigation, callOnStepChange, getStepChangeOptions, handleLayoutEffect, handleSubmitCall, hasErrors, hasFieldState, hasInvalidStepsState, isInteractionRef, onStepChange, setFormState, setShowAllErrors, setStepAsVisited]); const setActiveIndex = (0, _react.useCallback)((index, options) => { if (index === activeIndexRef.current) { return; } const mode = index > activeIndexRef.current ? 'next' : 'previous'; handleStepChange({ index, skipErrorCheck: mode === 'previous', mode, ...options }); }, [handleStepChange]); const handlePrevious = (0, _react.useCallback)(() => { setActiveIndex(activeIndexRef.current - 1); }, [setActiveIndex]); const handleNext = (0, _react.useCallback)(() => { setActiveIndex(activeIndexRef.current + 1); }, [setActiveIndex]); const handleChange = (0, _react.useCallback)(({ currentStep }) => { setActiveIndex(currentStep, mode === 'loose' ? { skipErrorCheck: true } : undefined); }, [mode, setActiveIndex]); const setFormError = (0, _react.useCallback)(error => { setSubmitState?.({ error }); }, [setSubmitState]); const handleSubmit = (0, _react.useCallback)(({ preventSubmit }) => { if (hasInvalidStepsState(undefined, ['error'])) { return preventSubmit(); } if (activeIndexRef.current + 1 < totalStepsRef.current) { handleNext(); preventSubmit(); } }, [hasInvalidStepsState, handleNext]); (0, _useEventListener.default)('onSubmit', handleSubmit); const { check } = (0, _useVisibility.default)({}); const includeWhenDependencies = (0, _react.useMemo)(() => collectIncludeWhenDependencies(children), [children]); const includeWhenDataPaths = (0, _react.useMemo)(() => { if (includeWhenDependencies.hasWrappedStepChildren) { return [...includeWhenDependencies.dataPaths, '//']; } return includeWhenDependencies.dataPaths; }, [includeWhenDependencies]); (0, _useDataValue.default)(includeWhenDataPaths, undefined, { pathType: 'absolute' }); (0, _useDataValue.default)(includeWhenDependencies.dataItemPaths, undefined, { pathType: 'iterate' }); const { makePath, makeIteratePath } = (0, _usePath.default)(); const includeWhenFieldStateDependencyPaths = (0, _react.useMemo)(() => { const paths = new Set(); includeWhenDependencies.fieldStatePaths.forEach(path => { paths.add(makePath(path)); }); includeWhenDependencies.fieldStateItemPaths.forEach(path => { paths.add(makeIteratePath(path)); }); if (includeWhenDependencies.hasWrappedStepChildren) { paths.add(undefined); } return Array.from(paths); }, [includeWhenDependencies, makeIteratePath, makePath]); const includeWhenSnapshotVersionRef = (0, _react.useRef)(0); const subscribeIncludeWhenFieldState = (0, _react.useCallback)(callback => { if (includeWhenFieldStateDependencyPaths.length === 0 || !setFieldEventListener) { return () => undefined; } let isSubscribed = true; const handleFieldStateUpdate = params => { if (params && 'state' in params && params.state.isFocused === true) { return undefined; } includeWhenSnapshotVersionRef.current += 1; queueMicrotask(() => { if (isSubscribed) { callback(); } }); }; includeWhenFieldStateDependencyPaths.forEach(path => { setFieldEventListener(path, 'onSetMountedFieldState', handleFieldStateUpdate); setFieldEventListener(path, 'onSetFieldError', handleFieldStateUpdate); }); return () => { isSubscribed = false; includeWhenFieldStateDependencyPaths.forEach(path => { setFieldEventListener(path, 'onSetMountedFieldState', handleFieldStateUpdate, { remove: true }); setFieldEventListener(path, 'onSetFieldError', handleFieldStateUpdate, { remove: true }); }); }; }, [includeWhenFieldStateDependencyPaths, setFieldEventListener]); const getIncludeWhenSnapshot = (0, _react.useCallback)(() => includeWhenSnapshotVersionRef.current, []); (0, _react.useSyncExternalStore)(subscribeIncludeWhenFieldState, getIncludeWhenSnapshot, getIncludeWhenSnapshot); const mapOverChildrenRef = (0, _react.useRef)(false); const enableMapOverChildren = (0, _react.useCallback)(() => { mapOverChildrenRef.current = true; }, []); const activeIndex = activeIndexRef.current; const providerValue = (0, _react.useMemo)(() => { return { id, activeIndex, initialActiveIndex, stepElementRef, stepsRef, updateTitlesRef, activeIndexRef, stepIndexRef, totalStepsRef, prerenderFieldProps, prerenderFieldPropsRef, hasErrorInOtherStepRef, onStepChangeEventsRef, keepInDOM, enableMapOverChildren, mapOverChildrenRef, check, setActiveIndex, handlePrevious, hasInvalidStepsState, setFieldError, handleNext, setFormError }; }, [id, activeIndex, initialActiveIndex, prerenderFieldProps, keepInDOM, enableMapOverChildren, check, setActiveIndex, handlePrevious, hasInvalidStepsState, setFieldError, handleNext, setFormError]); (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(() => { if (id && hasContext) { sharedStateRef.current.extend(providerValue); } }, [hasContext, id, providerValue]); (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(() => { updateTitlesRef.current?.(); }, [stepsRef.current]); const stepsLengthDidChange = (0, _react.useCallback)(() => { const tmpCount = tmpStepsRef.current; if (tmpCount === undefined) { return false; } const count = totalStepsRef.current; return count !== 0 && tmpCount !== 0 && count !== tmpCount; }, []); (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(() => { if (stepsLengthDidChange()) { callOnStepChange(activeIndexRef.current, 'stepListModified'); executeLayoutAnimationRef.current?.(); } tmpStepsRef.current = totalStepsRef.current; }, [totalStepsRef.current, callOnStepChange, stepsLengthDidChange]); if (!hasContext) { (0, _componentHelper.warn)('You may wrap Wizard.Container in Form.Handler'); return (0, _jsxRuntime.jsx)(_Handler.default, { children: (0, _jsxRuntime.jsx)(WizardContainer, { ...props, id: id }) }); } return (0, _jsxRuntime.jsxs)(_WizardContext.default, { value: providerValue, children: [(0, _jsxRuntime.jsxs)(_index.Space, { className: (0, _clsx.clsx)('dnb-forms-wizard-layout', className), ref: elementRef, ...rest, children: [(0, _jsxRuntime.jsx)(_DisplaySteps.DisplaySteps, { mode: mode, noAnimation: noAnimation, expandedInitially: expandedInitially, handleChange: handleChange, outset: outset }), (0, _jsxRuntime.jsx)("div", { className: "dnb-forms-wizard-layout__contents", children: (0, _jsxRuntime.jsx)(_IterateOverSteps.IterateOverSteps, { children: children }) })] }), prerenderFieldProps && !keepInDOM && (0, _jsxRuntime.jsx)(_PrerenderFieldPropsOfOtherSteps.PrerenderFieldPropsOfOtherSteps, { prerenderFieldPropsRef: prerenderFieldPropsRef, stepsRef: stepsRef })] }); } (0, _withComponentMarkers.default)(WizardContainer, { _supportsSpacingProps: true }); var _default = exports.default = WizardContainer; //# sourceMappingURL=WizardContainer.js.map