@mskcc/carbon-react
Version:
Carbon react components for the MSKCC DSM
95 lines (87 loc) • 2.9 kB
JavaScript
/**
* MSKCC 2021, 2024
*/
;
Object.defineProperty(exports, '__esModule', { value: true });
var _rollupPluginBabelHelpers = require('../../_virtual/_rollupPluginBabelHelpers.js');
var PropTypes = require('prop-types');
var React = require('react');
var TextDirectionContext = require('./TextDirectionContext.js');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var PropTypes__default = /*#__PURE__*/_interopDefaultLegacy(PropTypes);
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
function Text(_ref) {
let {
as,
children,
dir = 'auto',
...rest
} = _ref;
// TODO: Update with context typing once its been converted to TS
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__default["default"].createElement(TextDirectionContext.TextDirectionContext.Provider, {
value: value
}, /*#__PURE__*/React__default["default"].createElement(BaseComponent, _rollupPluginBabelHelpers["extends"]({}, rest, textProps), children));
}
Text.propTypes = {
/**
* Provide a custom element type used to render the outermost node
*/
as: PropTypes__default["default"].oneOfType([PropTypes__default["default"].func, PropTypes__default["default"].string, PropTypes__default["default"].elementType]),
/**
* Provide child elements or text to be rendered inside of this component
*/
children: PropTypes__default["default"].node.isRequired,
/**
* Specify the text direction to be used for this component and any of its
* children
*/
dir: PropTypes__default["default"].oneOf(['ltr', 'rtl', 'auto'])
};
function getTextFromChildren(children) {
if (typeof children === 'string') {
return children;
}
const text = React__default["default"].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;