UNPKG

@carbon/react

Version:

React components for the Carbon Design System

94 lines (88 loc) 2.66 kB
/** * Copyright IBM Corp. 2016, 2023 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var _rollupPluginBabelHelpers = require('../../_virtual/_rollupPluginBabelHelpers.js'); var PropTypes = require('prop-types'); var React = require('react'); var TextDirectionContext = require('./TextDirectionContext.js'); // eslint-disable-next-line react/display-name -- https://github.com/carbon-design-system/carbon/issues/20452 const Text = /*#__PURE__*/React.forwardRef(({ as, children, dir = 'auto', ...rest }, ref) => { const context = React.useContext(TextDirectionContext.TextDirectionContext); const textProps = {}; const BaseComponent = as ?? 'span'; const value = { ...context }; if (!context) { textProps.dir = dir; value.direction = dir; } else { const { direction: parentDirection, getTextDirection } = context; if (getTextDirection && getTextDirection.current) { const text = getTextFromChildren(children); const override = getTextDirection.current(text); if (parentDirection !== override) { textProps.dir = override; value.direction = override; } else if (parentDirection === 'auto') { textProps.dir = override; } } else if (parentDirection !== dir) { textProps.dir = dir; value.direction = dir; } else if (parentDirection === 'auto') { textProps.dir = dir; } } return /*#__PURE__*/React.createElement(TextDirectionContext.TextDirectionContext.Provider, { value: value }, /*#__PURE__*/React.createElement(BaseComponent, _rollupPluginBabelHelpers.extends({ ref: ref }, rest, textProps), children)); }); // @ts-expect-error - `propTypes` isn't typed. Text.propTypes = { /** * Provide a custom element type used to render the outermost node */ as: PropTypes.oneOfType([PropTypes.func, PropTypes.string, PropTypes.elementType]), /** * Provide child elements or text to be rendered inside of this component */ children: PropTypes.node, /** * Specify the text direction to be used for this component and any of its * children */ dir: PropTypes.oneOf(['ltr', 'rtl', 'auto']) }; const getTextFromChildren = children => { if (typeof children === 'string') { return children; } const text = React.Children.map(children, child => { if (typeof child === 'string') { return child; } return null; })?.filter(text => { return text !== null; }); if (text?.length === 1) { return text[0]; } return text; }; exports.Text = Text;