UNPKG

@alicloud/console-components-truncate

Version:

React component for Alibaba Cloud.

77 lines (74 loc) 2.72 kB
import _typeof from '@babel/runtime/helpers/typeof'; import React, { useRef, useState, useCallback, useLayoutEffect } from 'react'; import classnames from 'classnames'; import { BASE_CLASS_NAME, MAIN_CLASS_NAME, OMISSION_CLASS_NAME } from '../constants.js'; import { TruncateWidthContainer } from '../styles/Truncate.js'; import Tooltip from './Tooltip.js'; function isWidthOverflow(comparedElement) { return comparedElement.scrollWidth > comparedElement.clientWidth; } function TruncateByWidth(props) { var children = props.children, threshold = props.threshold, omission = props.omission, showTooltip = props.showTooltip, align = props.align, className = props.className, tooltipMaxWidth = props.tooltipMaxWidth, updaterRef = props.updaterRef, isOverflowChange = props.isOverflowChange, _a = props.popupStyle, popupStyle = _a === void 0 ? {} : _a, popupClassName = props.popupClassName, patchPopupProps = props.patchPopupProps; var ref = useRef(null); var _b = useState(false), isOverflow = _b[0], setIsOverflow = _b[1]; // 通过css`text-overflow: ellipsis;`来渲染省略符,还是用react来渲染 // css渲染方式能够以字符为单位进行截断,观感更好 var omissionByCss = omission === '...'; var checkOverflow = useCallback(function () { var el = ref.current; if (!el) { // 尚未渲染完成 return; } var newIsOverflow = isWidthOverflow(el); if (newIsOverflow !== isOverflow) { setIsOverflow(newIsOverflow); if (typeof isOverflowChange === 'function') { setTimeout(function () { isOverflowChange(newIsOverflow); }, 0); } } }, [isOverflow, isOverflowChange]); useLayoutEffect(function () { checkOverflow(); if (_typeof(updaterRef) === 'object') // eslint-disable-next-line updaterRef.current = checkOverflow; }); var truncateContainer = /*#__PURE__*/React.createElement(TruncateWidthContainer, { threshold: Number(threshold) || threshold, omissionByCss: omissionByCss, className: classnames(className, BASE_CLASS_NAME) }, /*#__PURE__*/React.createElement("span", { ref: ref, className: MAIN_CLASS_NAME }, children), isOverflow && !OMISSION_CLASS_NAME && /*#__PURE__*/React.createElement("span", { className: OMISSION_CLASS_NAME }, omission)); return Tooltip({ showTooltip: isOverflow && showTooltip, tooltipMaxWidth: tooltipMaxWidth, align: align, originalContent: children, truncatedContent: truncateContainer, popupStyle: popupStyle, popupClassName: popupClassName, patchPopupProps: patchPopupProps }); } export { TruncateByWidth as default };