braid-design-system
Version:
Themeable design system for the SEEK Group
31 lines (30 loc) • 795 B
JavaScript
import { Children, isValidElement, cloneElement } from "react";
import { isFragment } from "./isFragment.mjs";
function flattenChildren(children, depth = 0, keys = []) {
return Children.toArray(children).reduce(
(acc, node, nodeIndex) => {
if (isFragment(node)) {
acc.push(
...flattenChildren(
node.props.children,
depth + 1,
keys.concat(node.key || nodeIndex)
)
);
} else if (isValidElement(node)) {
acc.push(
cloneElement(node, {
key: keys.concat(String(node.key)).join(".")
})
);
} else if (typeof node === "string" || typeof node === "number") {
acc.push(node);
}
return acc;
},
[]
);
}
export {
flattenChildren
};