UNPKG

@carbon/ibm-products

Version:

Carbon for IBM Products

87 lines (83 loc) 2.74 kB
/** * Copyright IBM Corp. 2020, 2025 * * 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 React = require('react'); var cx = require('classnames'); var react = require('@carbon/react'); var settings = require('../../settings.js'); var devtools = require('../../global/js/utils/devtools.js'); var useTruncatedText = require('./useTruncatedText.js'); const blockClass = `${settings.pkg.prefix}--truncated-text`; const componentName = 'TruncatedText'; exports.TruncatedText = /*#__PURE__*/React.forwardRef((props, ref) => { const { align = 'top', autoAlign = false, className, collapseLabel, expandLabel, id = `${blockClass}-default-id`, lines = 2, value, type = 'tooltip', ...rest } = props; const [expanded, setExpanded] = React.useState(false); const { ref: contentRef, truncated } = useTruncatedText.default({ lines, value, expanded }); const textContentStyles = { WebkitLineClamp: type === 'expand' && !expanded || type === 'tooltip' ? lines : 'none' }; const textContentClasses = cx(`${blockClass}__text-content`, { [`${blockClass}__text-content--expanded`]: expanded }); const handleExpand = () => { setExpanded(!expanded); }; const handleExpandKey = evt => { const { key } = evt; if (key === 'Enter' || key === ' ') { handleExpand(); } }; const valueBody = /*#__PURE__*/React.createElement("span", { ref: contentRef, className: textContentClasses, id: id, style: textContentStyles }, value); const tooltipVariant = /*#__PURE__*/React.createElement(react.Tooltip, { align: align, autoAlign: autoAlign, label: value }, valueBody); const expandVariant = /*#__PURE__*/React.createElement(React.Fragment, null, valueBody, /*#__PURE__*/React.createElement("span", { "aria-controls": id, "aria-expanded": expanded, className: `${blockClass}__expand-toggle`, onClick: handleExpand, onKeyDown: handleExpandKey, role: "button", tabIndex: 0 }, expanded ? collapseLabel : expandLabel)); const truncatedBody = type === 'expand' ? expandVariant : tooltipVariant; return /*#__PURE__*/React.createElement("div", _rollupPluginBabelHelpers.extends({}, rest, { className: cx(blockClass, className), ref: ref }, devtools.getDevtoolsProps(componentName)), truncated ? truncatedBody : valueBody); }); exports.TruncatedText = settings.pkg.checkComponentEnabled(exports.TruncatedText, componentName); exports.TruncatedText.displayName = componentName;