UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

101 lines 2.9 kB
import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import classnames from 'classnames'; import Space from "../space/Space.js"; import { warn } from "../../shared/component-helper.js"; import StatRootContext from "./StatRootContext.js"; function Root(props) { const { children, id = null, className = null, style = null, visualOrder = 'label-content', skeleton = null, ...rest } = props; if (!hasOnlySupportedChildren(children)) { warn('Stat.Root should only contain Stat.Label and Stat.Content.'); } const hasLabel = hasRequiredLabel(children); if (!hasLabel) { warn('Stat.Root should contain a Stat.Label.'); } if (hasLabel && !hasValidLabelContentOrder(children)) { warn('Stat.Root: every Stat.Content should be preceded by a Stat.Label for valid dt/dd pairing.'); } return React.createElement(StatRootContext.Provider, { value: { inRoot: true, skeleton } }, React.createElement(Space, _extends({ element: "dl", id: id, style: style, className: classnames(`dnb-stat dnb-stat__root dnb-stat__root--${visualOrder}`, className) }, rest), children)); } Root._supportsSpacingProps = true; export default Root; function hasOnlySupportedChildren(children) { return React.Children.toArray(children).every(child => isSupportedChild(child)); } function isSupportedChild(child) { if (!React.isValidElement(child)) { if (typeof child === 'string') { return child.trim().length === 0; } return true; } if (child.type === React.Fragment) { return hasOnlySupportedChildren(child.props.children); } const role = child.type?._statRole; return role === 'label' || role === 'content'; } function hasRequiredLabel(children) { return React.Children.toArray(children).some(child => hasLabelChild(child)); } function hasLabelChild(child) { if (!React.isValidElement(child)) { return false; } if (child.type === React.Fragment) { return hasRequiredLabel(child.props.children); } const role = child.type?._statRole; return role === 'label'; } function flattenRoles(children) { const roles = []; for (const child of React.Children.toArray(children)) { if (!React.isValidElement(child)) { continue; } if (child.type === React.Fragment) { roles.push(...flattenRoles(child.props.children)); continue; } const role = child.type?._statRole; if (role === 'label' || role === 'content') { roles.push(role); } } return roles; } function hasValidLabelContentOrder(children) { const roles = flattenRoles(children); let hasSeenLabel = false; for (const role of roles) { if (role === 'label') { hasSeenLabel = true; } else if (role === 'content') { if (!hasSeenLabel) { return false; } } } return true; } //# sourceMappingURL=Root.js.map