1
0

base.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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 } 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. export interface BaseTypographyProps extends BaseProps {
  22. copyable?: CopyableConfig | boolean;
  23. delete?: boolean;
  24. disabled?: boolean;
  25. icon?: React.ReactNode;
  26. ellipsis?: Ellipsis | boolean;
  27. mark?: boolean;
  28. underline?: boolean;
  29. link?: LinkType;
  30. strong?: boolean;
  31. type?: TypographyBaseType;
  32. size?: TypographyBaseSize;
  33. style?: React.CSSProperties;
  34. className?: string;
  35. code?: boolean;
  36. children?: React.ReactNode;
  37. component?: React.ElementType;
  38. spacing?: string;
  39. heading?: string;
  40. }
  41. interface BaseTypographyState {
  42. editable: boolean;
  43. copied: boolean;
  44. isOverflowed: boolean;
  45. ellipsisContent: string;
  46. expanded: boolean;
  47. isTruncated: boolean;
  48. first: 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: null,
  155. expanded: false,
  156. // if text is truncated with js
  157. isTruncated: false,
  158. // record if has click expanded
  159. first: true,
  160. prevChildren: null,
  161. };
  162. this.wrapperRef = React.createRef();
  163. this.expandRef = React.createRef();
  164. this.copyRef = React.createRef();
  165. }
  166. componentDidMount() {
  167. if (this.props.ellipsis) {
  168. this.getEllipsisState();
  169. window.addEventListener('resize', this.onResize);
  170. }
  171. }
  172. static getDerivedStateFromProps(props: BaseTypographyProps, prevState: BaseTypographyState) {
  173. const { prevChildren } = prevState;
  174. const newState: Partial<BaseTypographyState> = {};
  175. newState.prevChildren = props.children;
  176. if (props.ellipsis && prevChildren !== props.children) {
  177. // reset ellipsis state if children update
  178. newState.isOverflowed = true;
  179. newState.ellipsisContent = null;
  180. newState.expanded = false;
  181. newState.isTruncated = false;
  182. newState.first = true;
  183. }
  184. return newState;
  185. }
  186. componentDidUpdate(prevProps: BaseTypographyProps) {
  187. // Render was based on outdated refs and needs to be rerun
  188. if (this.props.children !== prevProps.children) {
  189. this.forceUpdate();
  190. if (this.props.ellipsis) {
  191. this.getEllipsisState();
  192. }
  193. }
  194. }
  195. componentWillUnmount() {
  196. if (this.props.ellipsis) {
  197. window.removeEventListener('resize', this.onResize);
  198. }
  199. if (this.rafId) {
  200. window.cancelAnimationFrame(this.rafId);
  201. }
  202. }
  203. onResize = () => {
  204. if (this.rafId) {
  205. window.cancelAnimationFrame(this.rafId);
  206. }
  207. this.rafId = window.requestAnimationFrame(this.getEllipsisState.bind(this));
  208. };
  209. // if need to use js overflowed:
  210. // 1. text is expandable 2. expandText need to be shown 3. has extra operation 4. text need to ellipse from mid
  211. canUseCSSEllipsis = () => {
  212. const { copyable } = this.props;
  213. const { expandable, expandText, pos, suffix } = this.getEllipsisOpt();
  214. return !expandable && isUndefined(expandText) && !copyable && pos === 'end' && !suffix.length;
  215. };
  216. /**
  217. * whether truncated
  218. * rows < = 1 if there is overflow content, return true
  219. * rows > 1 if there is overflow height, return true
  220. * @param {Number} rows
  221. * @returns {Boolean}
  222. */
  223. shouldTruncated = (rows: number) => {
  224. if (!rows || rows < 1) {
  225. return false;
  226. }
  227. const updateOverflow =
  228. rows <= 1 ?
  229. this.wrapperRef.current.scrollWidth > this.wrapperRef.current.clientWidth :
  230. this.wrapperRef.current.scrollHeight > this.wrapperRef.current.offsetHeight;
  231. return updateOverflow;
  232. };
  233. showTooltip = () => {
  234. const { isOverflowed, isTruncated, expanded } = this.state;
  235. const { showTooltip, expandable, expandText } = this.getEllipsisOpt();
  236. const overflowed = !expanded && (isOverflowed || isTruncated);
  237. const noExpandText = !expandable && isUndefined(expandText);
  238. const show = noExpandText && overflowed && showTooltip;
  239. if (!show) {
  240. return show;
  241. }
  242. const defaultOpts = {
  243. type: 'tooltip',
  244. opts: {},
  245. };
  246. if (typeof showTooltip === 'object') {
  247. if (showTooltip.type && showTooltip.type.toLowerCase() === 'popover') {
  248. return merge(
  249. {
  250. opts: {
  251. style: { width: '240px' },
  252. showArrow: true,
  253. },
  254. },
  255. showTooltip
  256. );
  257. }
  258. return { ...defaultOpts, ...showTooltip };
  259. }
  260. return defaultOpts;
  261. };
  262. getEllipsisState() {
  263. const { rows, suffix, pos } = this.getEllipsisOpt();
  264. const { children } = this.props;
  265. // wait until element mounted
  266. if (!this.wrapperRef || !this.wrapperRef.current) {
  267. this.onResize();
  268. return false;
  269. }
  270. const { ellipsisContent, isOverflowed, isTruncated, expanded } = this.state;
  271. const updateOverflow = this.shouldTruncated(rows);
  272. const canUseCSSEllipsis = this.canUseCSSEllipsis();
  273. const needUpdate = updateOverflow !== isOverflowed;
  274. if (!rows || rows < 0 || expanded) {
  275. return undefined;
  276. }
  277. if (canUseCSSEllipsis) {
  278. if (needUpdate) {
  279. this.setState({ expanded: !updateOverflow });
  280. }
  281. return undefined;
  282. }
  283. const extraNode = [this.expandRef.current, this.copyRef && this.copyRef.current];
  284. warning(
  285. 'children' in this.props && typeof children !== 'string',
  286. "[Semi Typography] 'Only children with pure text could be used with ellipsis at this moment."
  287. );
  288. const content = getRenderText(
  289. ReactDOM.findDOMNode(this.wrapperRef.current) as HTMLElement,
  290. rows,
  291. children as string,
  292. extraNode,
  293. ELLIPSIS_STR,
  294. suffix,
  295. pos
  296. );
  297. if (children === content) {
  298. this.setState({ expanded: true });
  299. } else if (ellipsisContent !== content || isOverflowed !== updateOverflow) {
  300. this.setState({
  301. ellipsisContent: content,
  302. isOverflowed: updateOverflow,
  303. isTruncated: children !== content,
  304. });
  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, first: false });
  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 { expandText, expandable, collapseText, collapsible } = this.getEllipsisOpt();
  340. const { expanded, first } = this.state;
  341. const noExpandText = !expandable && isUndefined(expandText);
  342. const noCollapseText = !collapsible && isUndefined(collapseText);
  343. let text;
  344. if (!expanded && !noExpandText) {
  345. text = expandText;
  346. } else if (expanded && !first && !noCollapseText) {
  347. // if expanded is true but the text is initally mounted, we dont show collapseText
  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 } = this.props;
  409. const { expandable } = this.getEllipsisOpt();
  410. if (!ellipsis) {
  411. return {
  412. ellipsisCls: '',
  413. ellipsisStyle: {},
  414. // ellipsisAttr: {}
  415. };
  416. }
  417. const { rows } = this.getEllipsisOpt();
  418. const { isOverflowed, expanded, isTruncated } = 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. [`${prefixCls}-ellipsis-overflow-ellipsis`]: rows === 1 && useCSS,
  425. });
  426. const ellipsisStyle = useCSS && rows > 1 ? { WebkitLineClamp: rows } : {};
  427. return {
  428. ellipsisCls,
  429. ellipsisStyle: isOverflowed ? ellipsisStyle : {},
  430. };
  431. };
  432. renderEllipsisText = (opt: Ellipsis) => {
  433. const { suffix } = opt;
  434. const { children } = this.props;
  435. const { isTruncated, expanded, isOverflowed, ellipsisContent } = this.state;
  436. if (expanded || !isTruncated) {
  437. return (
  438. <>
  439. {children}
  440. {suffix && suffix.length ? suffix : null}
  441. </>
  442. );
  443. }
  444. return (
  445. <span>
  446. {ellipsisContent}
  447. {/* {ELLIPSIS_STR} */}
  448. {suffix}
  449. </span>
  450. );
  451. };
  452. renderOperations() {
  453. return (
  454. <>
  455. {this.renderExpandable()}
  456. {this.renderCopy()}
  457. </>
  458. );
  459. }
  460. renderCopy() {
  461. const { copyable, children } = this.props;
  462. if (!copyable) {
  463. return null;
  464. }
  465. let copyContent: string;
  466. let hasObject = false;
  467. if (Array.isArray(children)) {
  468. copyContent = '';
  469. children.forEach(value => {
  470. if (typeof value === 'object') {
  471. hasObject = true;
  472. }
  473. copyContent += String(value);
  474. });
  475. } else if (typeof children !== 'object') {
  476. copyContent = String(children);
  477. } else {
  478. hasObject = true;
  479. copyContent = String(children);
  480. }
  481. warning(
  482. hasObject,
  483. 'Children in Typography is a object, it will case a [object Object] mistake when copy to clipboard.'
  484. );
  485. const copyConfig = {
  486. content: copyContent,
  487. duration: 3,
  488. ...(typeof copyable === 'object' ? copyable : null),
  489. };
  490. return <Copyable {...copyConfig} forwardRef={this.copyRef} />;
  491. }
  492. renderIcon() {
  493. const { icon, size } = this.props;
  494. if (!icon) {
  495. return null;
  496. }
  497. const iconSize: Size = size === 'small' ? 'small' : 'default';
  498. return (
  499. <span className={`${prefixCls}-icon`} x-semi-prop="icon">
  500. {isSemiIcon(icon) ? React.cloneElement((icon as React.ReactElement), { size: iconSize }) : icon}
  501. </span>
  502. );
  503. }
  504. renderContent() {
  505. const {
  506. component,
  507. children,
  508. className,
  509. type,
  510. spacing,
  511. disabled,
  512. style,
  513. ellipsis,
  514. icon,
  515. size,
  516. link,
  517. heading,
  518. ...rest
  519. } = this.props;
  520. const textProps = omit(rest, [
  521. 'strong',
  522. 'editable',
  523. 'mark',
  524. 'copyable',
  525. 'underline',
  526. 'code',
  527. // 'link',
  528. 'delete',
  529. ]);
  530. const iconNode = this.renderIcon();
  531. const ellipsisOpt = this.getEllipsisOpt();
  532. const { ellipsisCls, ellipsisStyle } = this.getEllipsisStyle();
  533. let textNode = ellipsis ? this.renderEllipsisText(ellipsisOpt) : children;
  534. const linkCls = cls({
  535. [`${prefixCls}-link-text`]: link,
  536. [`${prefixCls}-link-underline`]: this.props.underline && link,
  537. });
  538. textNode = wrapperDecorations(
  539. this.props,
  540. <>
  541. {iconNode}
  542. {this.props.link ? <span className={linkCls}>{textNode}</span> : textNode}
  543. </>
  544. );
  545. const hTagReg = /^h[1-6]$/;
  546. const wrapperCls = cls(className, ellipsisCls, {
  547. // [`${prefixCls}-primary`]: !type || type === 'primary',
  548. [`${prefixCls}-${type}`]: type && !link,
  549. [`${prefixCls}-${size}`]: size,
  550. [`${prefixCls}-link`]: link,
  551. [`${prefixCls}-disabled`]: disabled,
  552. [`${prefixCls}-${spacing}`]: spacing,
  553. [`${prefixCls}-${heading}`]: isString(heading) && hTagReg.test(heading),
  554. });
  555. return (
  556. <Typography
  557. className={wrapperCls}
  558. style={{ ...style, ...ellipsisStyle }}
  559. component={component}
  560. forwardRef={this.wrapperRef}
  561. {...textProps}
  562. >
  563. {textNode}
  564. {this.renderOperations()}
  565. </Typography>
  566. );
  567. }
  568. renderTipWrapper() {
  569. const { children } = this.props;
  570. const showTooltip = this.showTooltip();
  571. const content = this.renderContent();
  572. if (showTooltip) {
  573. const { type, opts } = showTooltip as ShowTooltip;
  574. if (type.toLowerCase() === 'popover') {
  575. return (
  576. <Popover content={children} position="top" {...opts}>
  577. {content}
  578. </Popover>
  579. );
  580. }
  581. return (
  582. <Tooltip content={children} position="top" {...opts}>
  583. {content}
  584. </Tooltip>
  585. );
  586. } else {
  587. return content;
  588. }
  589. }
  590. render() {
  591. return (
  592. <LocaleConsumer componentName="Typography">
  593. {(locale: Locale['Typography']) => {
  594. this.expandStr = locale.expand;
  595. this.collapseStr = locale.collapse;
  596. return this.renderTipWrapper();
  597. }}
  598. </LocaleConsumer>
  599. );
  600. }
  601. }