@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
72 lines (71 loc) • 2.51 kB
JavaScript
"use client";
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?.current || 0;
if (context.totalSteps !== totalSteps) {
context.totalSteps = totalSteps;
}
const actualSetActiveIndex = context.setActiveIndex;
const pendingSetActiveIndexCallsRef = useRef([]);
const setActiveIndexRef = useRef();
const setActiveIndexFromHook = useCallback((index, options) => {
const handler = setActiveIndexRef.current;
if (handler) {
handler(index, options);
return;
}
pendingSetActiveIndexCallsRef.current.push([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?.current && !onStepChangeEventsRef.current.has(onStepChange)) {
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