base.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. import React, { Component } from 'react';
  2. import ReactDOM from 'react-dom';
  3. import cls from 'classnames';
  4. import PropTypes from 'prop-types';
  5. import { cssClasses, strings } from '@douyinfe/semi-foundation/typography/constants';
  6. import Typography from './typography';
  7. import Copyable from './copyable';
  8. import { IconSize as Size } from '../icons/index';
  9. import { isUndefined, omit, merge, isString, isNull } from 'lodash';
  10. import Tooltip from '../tooltip/index';
  11. import Popover from '../popover/index';
  12. import getRenderText from './util';
  13. import warning from '@douyinfe/semi-foundation/utils/warning';
  14. import isEnterPress from '@douyinfe/semi-foundation/utils/isEnterPress';
  15. import LocaleConsumer from '../locale/localeConsumer';
  16. import { Locale } from '../locale/interface';
  17. import { Ellipsis, EllipsisPos, ShowTooltip, TypographyBaseSize, TypographyBaseType } from './interface';
  18. import { CopyableConfig, LinkType } from './title';
  19. import { BaseProps } from '../_base/baseComponent';
  20. import { isSemiIcon } from '../_utils';
  21. import ResizeObserver from '../resizeObserver';
  22. export interface BaseTypographyProps extends BaseProps {
  23. copyable?: CopyableConfig | boolean;
  24. delete?: boolean;
  25. disabled?: boolean;
  26. icon?: React.ReactNode;
  27. ellipsis?: Ellipsis | boolean;
  28. mark?: boolean;
  29. underline?: boolean;
  30. link?: LinkType;
  31. strong?: boolean;
  32. type?: TypographyBaseType;
  33. size?: TypographyBaseSize;
  34. style?: React.CSSProperties;
  35. className?: string;
  36. code?: boolean;
  37. children?: React.ReactNode;
  38. component?: React.ElementType;
  39. spacing?: string;
  40. heading?: string
  41. }
  42. interface BaseTypographyState {
  43. editable: boolean;
  44. copied: boolean;
  45. isOverflowed: boolean;
  46. ellipsisContent: React.ReactNode;
  47. expanded: boolean;
  48. isTruncated: boolean;
  49. prevChildren: React.ReactNode
  50. }
  51. const prefixCls = cssClasses.PREFIX;
  52. const ELLIPSIS_STR = '...';
  53. const wrapperDecorations = (props: BaseTypographyProps, content: React.ReactNode) => {
  54. const { mark, code, underline, strong, link, disabled } = props;
  55. let wrapped = content;
  56. const wrap = (isNeeded: boolean | LinkType, tag: string) => {
  57. let wrapProps = {};
  58. if (!isNeeded) {
  59. return;
  60. }
  61. if (typeof isNeeded === 'object') {
  62. wrapProps = { ...isNeeded };
  63. }
  64. wrapped = React.createElement(tag, wrapProps, wrapped);
  65. };
  66. wrap(mark, 'mark');
  67. wrap(code, 'code');
  68. wrap(underline && !link, 'u');
  69. wrap(strong, 'strong');
  70. wrap(props.delete, 'del');
  71. wrap(link, disabled ? 'span' : 'a');
  72. return wrapped;
  73. };
  74. export default class Base extends Component<BaseTypographyProps, BaseTypographyState> {
  75. static propTypes = {
  76. children: PropTypes.node,
  77. copyable: PropTypes.oneOfType([
  78. PropTypes.shape({
  79. text: PropTypes.string,
  80. onCopy: PropTypes.func,
  81. successTip: PropTypes.node,
  82. copyTip: PropTypes.node,
  83. }),
  84. PropTypes.bool,
  85. ]),
  86. delete: PropTypes.bool,
  87. disabled: PropTypes.bool,
  88. // editable: PropTypes.bool,
  89. ellipsis: PropTypes.oneOfType([
  90. PropTypes.shape({
  91. rows: PropTypes.number,
  92. expandable: PropTypes.bool,
  93. expandText: PropTypes.string,
  94. onExpand: PropTypes.func,
  95. suffix: PropTypes.string,
  96. showTooltip: PropTypes.oneOfType([
  97. PropTypes.shape({
  98. type: PropTypes.string,
  99. opts: PropTypes.object,
  100. }),
  101. PropTypes.bool,
  102. ]),
  103. collapsible: PropTypes.bool,
  104. collapseText: PropTypes.string,
  105. pos: PropTypes.oneOf(['end', 'middle']),
  106. }),
  107. PropTypes.bool,
  108. ]),
  109. mark: PropTypes.bool,
  110. underline: PropTypes.bool,
  111. link: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
  112. spacing: PropTypes.oneOf(strings.SPACING),
  113. strong: PropTypes.bool,
  114. size: PropTypes.oneOf(strings.SIZE),
  115. type: PropTypes.oneOf(strings.TYPE),
  116. style: PropTypes.object,
  117. className: PropTypes.string,
  118. icon: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
  119. heading: PropTypes.string,
  120. component: PropTypes.string,
  121. };
  122. static defaultProps = {
  123. children: null as React.ReactNode,
  124. copyable: false,
  125. delete: false,
  126. disabled: false,
  127. // editable: false,
  128. ellipsis: false,
  129. icon: '',
  130. mark: false,
  131. underline: false,
  132. strong: false,
  133. link: false,
  134. type: 'primary',
  135. spacing: 'normal',
  136. size: 'normal',
  137. style: {},
  138. className: '',
  139. };
  140. wrapperRef: React.RefObject<any>;
  141. expandRef: React.RefObject<any>;
  142. copyRef: React.RefObject<any>;
  143. rafId: ReturnType<typeof requestAnimationFrame>;
  144. expandStr: string;
  145. collapseStr: string;
  146. constructor(props: BaseTypographyProps) {
  147. super(props);
  148. this.state = {
  149. editable: false,
  150. copied: false,
  151. // ellipsis
  152. // if text is overflow in container
  153. isOverflowed: true,
  154. ellipsisContent: props.children,
  155. expanded: false,
  156. // if text is truncated with js
  157. isTruncated: true,
  158. prevChildren: null,
  159. };
  160. this.wrapperRef = React.createRef();
  161. this.expandRef = React.createRef();
  162. this.copyRef = React.createRef();
  163. }
  164. componentDidMount() {
  165. if (this.props.ellipsis) {
  166. this.onResize();
  167. }
  168. }
  169. static getDerivedStateFromProps(props: BaseTypographyProps, prevState: BaseTypographyState) {
  170. const { prevChildren } = prevState;
  171. const newState: Partial<BaseTypographyState> = {};
  172. newState.prevChildren = props.children;
  173. if (props.ellipsis && prevChildren !== props.children) {
  174. // reset ellipsis state if children update
  175. newState.isOverflowed = true;
  176. newState.ellipsisContent = props.children;
  177. newState.expanded = false;
  178. newState.isTruncated = true;
  179. }
  180. return newState;
  181. }
  182. componentDidUpdate(prevProps: BaseTypographyProps) {
  183. // Render was based on outdated refs and needs to be rerun
  184. if (this.props.children !== prevProps.children) {
  185. this.forceUpdate();
  186. if (this.props.ellipsis) {
  187. this.onResize();
  188. }
  189. }
  190. }
  191. componentWillUnmount() {
  192. if (this.rafId) {
  193. window.cancelAnimationFrame(this.rafId);
  194. }
  195. }
  196. onResize = () => {
  197. if (this.rafId) {
  198. window.cancelAnimationFrame(this.rafId);
  199. }
  200. this.rafId = window.requestAnimationFrame(this.getEllipsisState.bind(this));
  201. };
  202. // if need to use js overflowed:
  203. // 1. text is expandable 2. expandText need to be shown 3. has extra operation 4. text need to ellipse from mid
  204. canUseCSSEllipsis = () => {
  205. const { copyable } = this.props;
  206. const { expandable, expandText, pos, suffix } = this.getEllipsisOpt();
  207. return !expandable && isUndefined(expandText) && !copyable && pos === 'end' && !suffix.length;
  208. };
  209. /**
  210. * whether truncated
  211. * rows < = 1 if there is overflow content, return true
  212. * rows > 1 if there is overflow height, return true
  213. * @param {Number} rows
  214. * @returns {Boolean}
  215. */
  216. shouldTruncated = (rows: number) => {
  217. if (!rows || rows < 1) {
  218. return false;
  219. }
  220. const updateOverflow =
  221. rows <= 1 ?
  222. this.wrapperRef.current.scrollWidth > this.wrapperRef.current.offsetWidth :
  223. this.wrapperRef.current.scrollHeight > this.wrapperRef.current.offsetHeight;
  224. return updateOverflow;
  225. };
  226. showTooltip = () => {
  227. const { isOverflowed, isTruncated, expanded } = this.state;
  228. const { showTooltip, expandable, expandText } = this.getEllipsisOpt();
  229. const overflowed = !expanded && (isOverflowed || isTruncated);
  230. const noExpandText = !expandable && isUndefined(expandText);
  231. const show = noExpandText && overflowed && showTooltip;
  232. if (!show) {
  233. return show;
  234. }
  235. const defaultOpts = {
  236. type: 'tooltip',
  237. opts: {},
  238. };
  239. if (typeof showTooltip === 'object') {
  240. if (showTooltip.type && showTooltip.type.toLowerCase() === 'popover') {
  241. return merge(
  242. {
  243. opts: {
  244. style: { width: '240px' },
  245. showArrow: true,
  246. },
  247. },
  248. showTooltip
  249. );
  250. }
  251. return { ...defaultOpts, ...showTooltip };
  252. }
  253. return defaultOpts;
  254. };
  255. getEllipsisState() {
  256. const { rows, suffix, pos } = this.getEllipsisOpt();
  257. const { children } = this.props;
  258. // wait until element mounted
  259. if (!this.wrapperRef || !this.wrapperRef.current) {
  260. this.onResize();
  261. return false;
  262. }
  263. const { expanded } = this.state;
  264. const canUseCSSEllipsis = this.canUseCSSEllipsis();
  265. // If children is null, css/js truncated flag isTruncate is false
  266. if (isNull(children)) {
  267. this.setState({
  268. isTruncated: false,
  269. isOverflowed: false
  270. });
  271. return undefined;
  272. }
  273. // Currently only text truncation is supported, if there is non-text,
  274. // both css truncation and js truncation should throw a warning
  275. warning(
  276. 'children' in this.props && typeof children !== 'string',
  277. "[Semi Typography] Only children with pure text could be used with ellipsis at this moment."
  278. );
  279. if (!rows || rows < 0 || expanded) {
  280. return undefined;
  281. }
  282. if (canUseCSSEllipsis) {
  283. const updateOverflow = this.shouldTruncated(rows);
  284. // isOverflowed needs to be updated to show tooltip when using css ellipsis
  285. this.setState({
  286. isOverflowed: updateOverflow,
  287. isTruncated: false
  288. });
  289. return undefined;
  290. }
  291. const extraNode = { expand: this.expandRef.current, copy: this.copyRef && this.copyRef.current };
  292. const content = getRenderText(
  293. this.wrapperRef.current,
  294. rows,
  295. // Perform type conversion on children to prevent component crash due to non-string type of children
  296. String(children),
  297. extraNode,
  298. ELLIPSIS_STR,
  299. suffix,
  300. pos
  301. );
  302. this.setState({
  303. ellipsisContent: content,
  304. isTruncated: children !== content,
  305. });
  306. return undefined;
  307. }
  308. /**
  309. * Triggered when the fold button is clicked to save the latest expanded state
  310. * @param {Event} e
  311. */
  312. toggleOverflow = (e: React.MouseEvent<HTMLAnchorElement>) => {
  313. const { onExpand, expandable, collapsible } = this.getEllipsisOpt();
  314. const { expanded } = this.state;
  315. onExpand && onExpand(!expanded, e);
  316. if ((expandable && !expanded) || (collapsible && expanded)) {
  317. this.setState({ expanded: !expanded });
  318. }
  319. };
  320. getEllipsisOpt = (): Ellipsis => {
  321. const { ellipsis } = this.props;
  322. if (!ellipsis) {
  323. return {};
  324. }
  325. const opt = {
  326. rows: 1,
  327. expandable: false,
  328. pos: 'end' as EllipsisPos,
  329. suffix: '',
  330. showTooltip: false,
  331. collapsible: false,
  332. expandText: (ellipsis as Ellipsis).expandable ? this.expandStr : undefined,
  333. collapseText: (ellipsis as Ellipsis).collapsible ? this.collapseStr : undefined,
  334. ...(typeof ellipsis === 'object' ? ellipsis : null),
  335. };
  336. return opt;
  337. };
  338. renderExpandable = () => {
  339. const { expanded, isTruncated } = this.state;
  340. if (!isTruncated) return null;
  341. const { expandText, expandable, collapseText, collapsible } = this.getEllipsisOpt();
  342. const noExpandText = !expandable && isUndefined(expandText);
  343. const noCollapseText = !collapsible && isUndefined(collapseText);
  344. let text;
  345. if (!expanded && !noExpandText) {
  346. text = expandText;
  347. } else if (expanded && !noCollapseText) {
  348. text = collapseText;
  349. }
  350. if (!noExpandText || !noCollapseText) {
  351. return (
  352. // TODO: replace `a` tag with `span` in next major version
  353. // NOTE: may have effect on style
  354. // eslint-disable-next-line jsx-a11y/anchor-is-valid
  355. <a
  356. role="button"
  357. tabIndex={0}
  358. className={`${prefixCls}-ellipsis-expand`}
  359. key="expand"
  360. ref={this.expandRef}
  361. aria-label={text}
  362. onClick={this.toggleOverflow}
  363. onKeyPress={e => isEnterPress(e) && this.toggleOverflow(e as any)}
  364. >
  365. {text}
  366. </a>
  367. );
  368. }
  369. return null;
  370. };
  371. /**
  372. * 获取文本的缩略class和style
  373. *
  374. * 截断类型:
  375. * - CSS 截断,仅在 rows=1 且没有 expandable、pos、suffix 时生效
  376. * - JS 截断,应对 CSS 无法阶段的场景
  377. * 相关变量
  378. * props:
  379. * - ellipsis:
  380. * - rows
  381. * - expandable
  382. * - pos
  383. * - suffix
  384. * state:
  385. * - isOverflowed,文本是否处于overflow状态
  386. * - expanded,文本是否处于折叠状态
  387. * - isTruncated,文本是否被js截断
  388. *
  389. * Get the abbreviated class and style of the text
  390. *
  391. * Truncation type:
  392. * -CSS truncation, which only takes effect when rows = 1 and there is no expandable, pos, suffix
  393. * -JS truncation, dealing with scenarios where CSS cannot stage
  394. * related variables
  395. * props:
  396. * -ellipsis:
  397. * -rows
  398. * -expandable
  399. * -pos
  400. * -suffix
  401. * state:
  402. * -isOverflowed, whether the text is in an overflow state
  403. * -expanded, whether the text is in a collapsed state
  404. * -isTruncated, whether the text is truncated by js
  405. * @returns {Object}
  406. */
  407. getEllipsisStyle = () => {
  408. const { ellipsis, component } = this.props;
  409. if (!ellipsis) {
  410. return {
  411. ellipsisCls: '',
  412. ellipsisStyle: {},
  413. // ellipsisAttr: {}
  414. };
  415. }
  416. const { rows } = this.getEllipsisOpt();
  417. const { expanded } = this.state;
  418. const useCSS = !expanded && this.canUseCSSEllipsis();
  419. const ellipsisCls = cls({
  420. [`${prefixCls}-ellipsis`]: true,
  421. [`${prefixCls}-ellipsis-single-line`]: rows === 1,
  422. [`${prefixCls}-ellipsis-multiple-line`]: rows > 1,
  423. // component === 'span', Text component, It should be externally displayed inline
  424. [`${prefixCls}-ellipsis-multiple-line-text`]: rows > 1 && component === 'span',
  425. [`${prefixCls}-ellipsis-overflow-ellipsis`]: rows === 1 && useCSS,
  426. // component === 'span', Text component, It should be externally displayed inline
  427. [`${prefixCls}-ellipsis-overflow-ellipsis-text`]: rows === 1 && useCSS && component === 'span',
  428. });
  429. const ellipsisStyle = useCSS && rows > 1 ? { WebkitLineClamp: rows } : {};
  430. return {
  431. ellipsisCls,
  432. ellipsisStyle,
  433. };
  434. };
  435. renderEllipsisText = (opt: Ellipsis) => {
  436. const { suffix } = opt;
  437. const { children } = this.props;
  438. const { isTruncated, expanded, ellipsisContent } = this.state;
  439. if (expanded || !isTruncated) {
  440. return (
  441. <>
  442. {children}
  443. {suffix && suffix.length ? suffix : null}
  444. </>
  445. );
  446. }
  447. return (
  448. <span>
  449. {ellipsisContent}
  450. {/* {ELLIPSIS_STR} */}
  451. {suffix}
  452. </span>
  453. );
  454. };
  455. renderOperations() {
  456. return (
  457. <>
  458. {this.renderExpandable()}
  459. {this.renderCopy()}
  460. </>
  461. );
  462. }
  463. renderCopy() {
  464. const { copyable, children } = this.props;
  465. if (!copyable) {
  466. return null;
  467. }
  468. // If it is configured in the content of copyable, the copied content will be the content in copyable
  469. const willCopyContent = (copyable as CopyableConfig)?.content ?? children;
  470. let copyContent: string;
  471. let hasObject = false;
  472. if (Array.isArray(willCopyContent)) {
  473. copyContent = '';
  474. willCopyContent.forEach(value => {
  475. if (typeof value === 'object') {
  476. hasObject = true;
  477. }
  478. copyContent += String(value);
  479. });
  480. } else if (typeof willCopyContent !== 'object') {
  481. copyContent = String(willCopyContent);
  482. } else {
  483. hasObject = true;
  484. copyContent = String(willCopyContent);
  485. }
  486. warning(
  487. hasObject,
  488. 'Content to be copied in Typography is a object, it will case a [object Object] mistake when copy to clipboard.'
  489. );
  490. const copyConfig = {
  491. content: copyContent,
  492. duration: 3,
  493. ...(typeof copyable === 'object' ? copyable : null),
  494. };
  495. return <Copyable {...copyConfig} forwardRef={this.copyRef} />;
  496. }
  497. renderIcon() {
  498. const { icon, size } = this.props;
  499. if (!icon) {
  500. return null;
  501. }
  502. const iconSize: Size = size === 'small' ? 'small' : 'default';
  503. return (
  504. <span className={`${prefixCls}-icon`} x-semi-prop="icon">
  505. {isSemiIcon(icon) ? React.cloneElement((icon as React.ReactElement), { size: iconSize }) : icon}
  506. </span>
  507. );
  508. }
  509. renderContent() {
  510. const {
  511. component,
  512. children,
  513. className,
  514. type,
  515. spacing,
  516. disabled,
  517. style,
  518. ellipsis,
  519. icon,
  520. size,
  521. link,
  522. heading,
  523. ...rest
  524. } = this.props;
  525. const textProps = omit(rest, [
  526. 'strong',
  527. 'editable',
  528. 'mark',
  529. 'copyable',
  530. 'underline',
  531. 'code',
  532. // 'link',
  533. 'delete',
  534. ]);
  535. const iconNode = this.renderIcon();
  536. const ellipsisOpt = this.getEllipsisOpt();
  537. const { ellipsisCls, ellipsisStyle } = this.getEllipsisStyle();
  538. let textNode = ellipsis ? this.renderEllipsisText(ellipsisOpt) : children;
  539. const linkCls = cls({
  540. [`${prefixCls}-link-text`]: link,
  541. [`${prefixCls}-link-underline`]: this.props.underline && link,
  542. });
  543. textNode = wrapperDecorations(
  544. this.props,
  545. <>
  546. {iconNode}
  547. {this.props.link ? <span className={linkCls}>{textNode}</span> : textNode}
  548. </>
  549. );
  550. const hTagReg = /^h[1-6]$/;
  551. const wrapperCls = cls(className, ellipsisCls, {
  552. // [`${prefixCls}-primary`]: !type || type === 'primary',
  553. [`${prefixCls}-${type}`]: type && !link,
  554. [`${prefixCls}-${size}`]: size,
  555. [`${prefixCls}-link`]: link,
  556. [`${prefixCls}-disabled`]: disabled,
  557. [`${prefixCls}-${spacing}`]: spacing,
  558. [`${prefixCls}-${heading}`]: isString(heading) && hTagReg.test(heading),
  559. });
  560. return (
  561. <Typography
  562. className={wrapperCls}
  563. style={{ ...style, ...ellipsisStyle }}
  564. component={component}
  565. forwardRef={this.wrapperRef}
  566. {...textProps}
  567. >
  568. {textNode}
  569. {this.renderOperations()}
  570. </Typography>
  571. );
  572. }
  573. renderTipWrapper() {
  574. const { children } = this.props;
  575. const showTooltip = this.showTooltip();
  576. const content = this.renderContent();
  577. if (showTooltip) {
  578. const { type, opts } = showTooltip as ShowTooltip;
  579. if (type.toLowerCase() === 'popover') {
  580. return (
  581. <Popover content={children} position="top" {...opts}>
  582. {content}
  583. </Popover>
  584. );
  585. }
  586. return (
  587. <Tooltip content={children} position="top" {...opts}>
  588. {content}
  589. </Tooltip>
  590. );
  591. } else {
  592. return content;
  593. }
  594. }
  595. render() {
  596. const content = (
  597. <LocaleConsumer componentName="Typography">
  598. {(locale: Locale['Typography']) => {
  599. this.expandStr = locale.expand;
  600. this.collapseStr = locale.collapse;
  601. return this.renderTipWrapper();
  602. }}
  603. </LocaleConsumer>
  604. );
  605. if (this.props.ellipsis) {
  606. return (
  607. <ResizeObserver onResize={this.onResize} observeParent>
  608. {content}
  609. </ResizeObserver>
  610. );
  611. }
  612. return content;
  613. }
  614. }