base.tsx 22 KB

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