@carbon/ibm-products
Version:
Carbon for IBM Products
87 lines (83 loc) • 2.73 kB
JavaScript
/**
* 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.
*/
import { extends as _extends } from '../../_virtual/_rollupPluginBabelHelpers.js';
import React__default, { forwardRef, useState } from 'react';
import cx from 'classnames';
import { Tooltip } from '@carbon/react';
import { pkg } from '../../settings.js';
import { getDevtoolsProps } from '../../global/js/utils/devtools.js';
import useTruncatedText from './useTruncatedText.js';
const blockClass = `${pkg.prefix}--truncated-text`;
const componentName = 'TruncatedText';
let TruncatedText = /*#__PURE__*/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] = useState(false);
const {
ref: contentRef,
truncated
} = useTruncatedText({
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__default.createElement("span", {
ref: contentRef,
className: textContentClasses,
id: id,
style: textContentStyles
}, value);
const tooltipVariant = /*#__PURE__*/React__default.createElement(Tooltip, {
align: align,
autoAlign: autoAlign,
label: value
}, valueBody);
const expandVariant = /*#__PURE__*/React__default.createElement(React__default.Fragment, null, valueBody, /*#__PURE__*/React__default.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__default.createElement("div", _extends({}, rest, {
className: cx(blockClass, className),
ref: ref
}, getDevtoolsProps(componentName)), truncated ? truncatedBody : valueBody);
});
TruncatedText = pkg.checkComponentEnabled(TruncatedText, componentName);
TruncatedText.displayName = componentName;
export { TruncatedText };