UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

74 lines (73 loc) 2.85 kB
"use client"; import _pushInstanceProperty from "core-js-pure/stable/instance/push.js"; import { useCallback, useContext, useMemo, useRef } from 'react'; import WizardContext from "../Context/WizardContext.js"; import { createReferenceKey, useSharedState } from "../../../../shared/helpers/useSharedState.js"; import { useIsomorphicLayoutEffect as useLayoutEffect } from "../../../../shared/helpers/useIsomorphicLayoutEffect.js"; export default function useStep(id = null, { onStepChange } = {}) { const setFormError = useCallback(() => null, []); const wizardContext = useContext(WizardContext) || { setFormError }; if (onStepChange && !id && wizardContext.id) { id = wizardContext.id; } const sharedDataRef = useRef(null); sharedDataRef.current = useSharedState(id ? createReferenceKey(id, 'wizard') : undefined); const data = sharedDataRef.current.data; if (data && !data.setFormError) { data.setFormError = setFormError; } const context = data || wizardContext; const { totalStepsRef } = context; const totalSteps = (totalStepsRef === null || totalStepsRef === void 0 ? void 0 : totalStepsRef.current) || 0; if (context.totalSteps !== totalSteps) { context.totalSteps = totalSteps; } const actualSetActiveIndex = context.setActiveIndex; const pendingSetActiveIndexCallsRef = useRef([]); const setActiveIndexRef = useRef(); const setActiveIndexFromHook = useCallback((index, options) => { var _context; const handler = setActiveIndexRef.current; if (handler) { handler(index, options); return; } _pushInstanceProperty(_context = pendingSetActiveIndexCallsRef.current).call(_context, [index, options]); }, []); useLayoutEffect(() => { setActiveIndexRef.current = actualSetActiveIndex; if (actualSetActiveIndex && pendingSetActiveIndexCallsRef.current.length > 0) { pendingSetActiveIndexCallsRef.current.forEach(([index, options]) => { actualSetActiveIndex(index, options); }); pendingSetActiveIndexCallsRef.current = []; } }, [actualSetActiveIndex]); useLayoutEffect(() => { const { onStepChangeEventsRef } = context; if (onStepChange && onStepChangeEventsRef !== null && onStepChangeEventsRef !== void 0 && onStepChangeEventsRef.current && !onStepChangeEventsRef.current.has(onStepChange)) { onStepChangeEventsRef === null || onStepChangeEventsRef === void 0 || onStepChangeEventsRef.current.add(onStepChange); } }, [context, onStepChange]); useLayoutEffect(() => { if (id) { sharedDataRef.current.extend({}); } }, [id]); const contextWithBridge = useMemo(() => { return { ...context, setActiveIndex: setActiveIndexFromHook }; }, [context, setActiveIndexFromHook]); return contextWithBridge; } //# sourceMappingURL=useStep.js.map