UNPKG

braid-design-system

Version:
31 lines (30 loc) 795 B
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 };