@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
114 lines (113 loc) • 3.27 kB
JavaScript
"use client";
import { Children, createElement, isValidElement, useContext } from 'react';
import { useIsomorphicLayoutEffect as useLayoutEffect } from "../../../../shared/helpers/useIsomorphicLayoutEffect.js";
import WizardContext from "../Context/WizardContext.js";
import WizardStepContext from "../Step/StepContext.js";
import Step from "../Step/Step.js";
import { useCollectStepsData } from "./useCollectStepsData.js";
import { jsx as _jsx } from "react/jsx-runtime";
export function getWizardStepElement(child) {
if (isValidElement(child)) {
if (child.type === Step) {
return child;
}
if (typeof child.type === 'function') {
const result = child.type(child.props);
if (result?.type === Step) {
return result;
}
}
}
return undefined;
}
export function IterateOverSteps({
children
}) {
const {
check,
stepsRef,
activeIndexRef,
totalStepsRef,
stepIndexRef,
updateTitlesRef,
prerenderFieldProps,
prerenderFieldPropsRef,
hasErrorInOtherStepRef,
mapOverChildrenRef
} = useContext(WizardContext);
const {
collectStepsData
} = useCollectStepsData();
stepsRef.current = new Map();
hasErrorInOtherStepRef.current = false;
stepIndexRef.current = -1;
totalStepsRef.current = 0;
const childrenArray = Children.map(children, child => {
if (isValidElement(child)) {
const stepElement = getWizardStepElement(child);
if (stepElement) {
child = stepElement;
const {
title,
inactive,
keepInDOM,
include,
id,
includeWhen
} = stepElement.props || {};
if (include === false) {
return null;
}
if (includeWhen && !check({
visibleWhen: includeWhen
})) {
return null;
}
const index = totalStepsRef.current;
totalStepsRef.current = totalStepsRef.current + 1;
collectStepsData({
id,
index,
title,
inactive,
keepInDOM
});
if (prerenderFieldProps && typeof document !== 'undefined' && index !== activeIndexRef.current && typeof prerenderFieldPropsRef.current['step-' + index] === 'undefined') {
const key = `${index}-${activeIndexRef.current}`;
prerenderFieldPropsRef.current['step-' + index] = {
index,
fn: () => createElement(child.type, {
...child.props,
key,
index,
prerenderFieldProps: true
})
};
}
return child;
}
}
return child;
});
if (totalStepsRef.current === 0) {
activeIndexRef.current = 0;
} else if (totalStepsRef.current < activeIndexRef.current + 1) {
activeIndexRef.current = totalStepsRef.current - 1;
}
const totalSteps = totalStepsRef.current;
useLayoutEffect(() => {
updateTitlesRef.current?.();
}, [totalSteps, updateTitlesRef]);
if (mapOverChildrenRef.current) {
return childrenArray.map((child, index) => {
return _jsx(WizardStepContext, {
value: {
index
},
children: child
}, index);
});
}
return children;
}
//# sourceMappingURL=IterateOverSteps.js.map