index.js 5.04 KB
Newer Older
1
import React, { Component } from 'react';
niko's avatar
niko committed
2 3 4 5 6 7 8
import { Tooltip } from 'antd';
import classNames from 'classnames';
import styles from './index.less';

/* eslint react/no-did-mount-set-state: 0 */
/* eslint no-param-reassign: 0 */

9
const isSupportLineClamp = (document.body.style.webkitLineClamp !== undefined);
10

niko's avatar
niko committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
const EllipsisText = ({ text, length, tooltip, ...other }) => {
  if (typeof text !== 'string') {
    throw new Error('Ellipsis children must be string.');
  }
  if (text.length <= length || length < 0) {
    return <span {...other}>{text}</span>;
  }
  const tail = '...';
  let displayText;
  if (length - tail.length <= 0) {
    displayText = '';
  } else {
    displayText = text.slice(0, (length - tail.length));
  }

  if (tooltip) {
27
    return <Tooltip title={text}><span>{displayText}{tail}</span></Tooltip>;
niko's avatar
niko committed
28 29 30 31 32 33 34 35 36
  }

  return (
    <span {...other}>
      {displayText}{tail}
    </span>
  );
};

37
export default class Ellipsis extends Component {
niko's avatar
niko committed
38 39 40 41 42 43 44 45 46 47 48 49
  state = {
    text: '',
    targetCount: 0,
  }

  componentDidMount() {
    if (this.node) {
      this.computeLine();
    }
  }

  componentWillReceiveProps(nextProps) {
50
    if (this.props.lines !== nextProps.lines) {
niko's avatar
niko committed
51 52 53 54 55
      this.computeLine();
    }
  }

  computeLine = () => {
56 57
    const { lines } = this.props;
    if (lines && !isSupportLineClamp) {
niko's avatar
niko committed
58
      const text = this.shadowChildren.innerText;
59 60 61 62
      const lineHeight = parseInt(getComputedStyle(this.root).lineHeight, 10);
      const targetHeight = lines * lineHeight;
      this.content.style.height = `${targetHeight}px`;
      const totalHeight = this.shadowChildren.offsetHeight;
niko's avatar
niko committed
63 64
      const shadowNode = this.shadow.firstChild;

65 66 67 68 69 70 71 72
      if (totalHeight <= targetHeight) {
        this.setState({
          text,
          targetCount: text.length,
        });
        return;
      }

niko's avatar
niko committed
73 74 75 76
      // bisection
      const len = text.length;
      const mid = Math.floor(len / 2);

77
      const count = this.bisection(targetHeight, mid, 0, len, text, shadowNode);
niko's avatar
niko committed
78 79 80 81 82 83 84 85

      this.setState({
        text,
        targetCount: count,
      });
    }
  }

86 87
  bisection = (th, m, b, e, text, shadowNode) => {
    const suffix = '...';
niko's avatar
niko committed
88 89 90
    let mid = m;
    let end = e;
    let begin = b;
91 92
    shadowNode.innerHTML = text.substring(0, mid) + suffix;
    let sh = shadowNode.offsetHeight;
niko's avatar
niko committed
93

94
    if (sh <= th) {
95 96
      shadowNode.innerHTML = text.substring(0, mid + 1) + suffix;
      sh = shadowNode.offsetHeight;
97
      if (sh > th) {
niko's avatar
niko committed
98 99 100 101
        return mid;
      } else {
        begin = mid;
        mid = Math.floor((end - begin) / 2) + begin;
102
        return this.bisection(th, mid, begin, end, text, shadowNode);
niko's avatar
niko committed
103 104 105 106 107
      }
    } else {
      if (mid - 1 < 0) {
        return mid;
      }
108 109 110
      shadowNode.innerHTML = text.substring(0, mid - 1) + suffix;
      sh = shadowNode.offsetHeight;
      if (sh <= th) {
111
        return mid - 1;
niko's avatar
niko committed
112 113 114
      } else {
        end = mid;
        mid = Math.floor((end - begin) / 2) + begin;
115
        return this.bisection(th, mid, begin, end, text, shadowNode);
niko's avatar
niko committed
116 117 118 119
      }
    }
  }

120 121 122 123
  handleRoot = (n) => {
    this.root = n;
  }

124 125 126 127
  handleContent = (n) => {
    this.content = n;
  }

128
  handleNode = (n) => {
niko's avatar
niko committed
129 130 131 132 133 134 135 136 137 138 139 140
    this.node = n;
  }

  handleShadow = (n) => {
    this.shadow = n;
  }

  handleShadowChildren = (n) => {
    this.shadowChildren = n;
  }

  render() {
141
    const { text, targetCount } = this.state;
niko's avatar
niko committed
142 143 144 145 146 147 148 149 150 151
    const {
      children,
      lines,
      length,
      className,
      tooltip,
      ...restProps
    } = this.props;

    const cls = classNames(styles.ellipsis, className, {
152 153
      [styles.lines]: (lines && !isSupportLineClamp),
      [styles.lineClamp]: (lines && isSupportLineClamp),
niko's avatar
niko committed
154 155 156 157 158 159 160 161 162 163 164
    });

    if (!lines && !length) {
      return (<span className={cls} {...restProps}>{children}</span>);
    }

    // length
    if (!lines) {
      return (<EllipsisText className={cls} length={length} text={children || ''} tooltip={tooltip} {...restProps} />);
    }

165 166 167 168 169
    const id = `antd-pro-ellipsis-${`${new Date().getTime()}${Math.floor(Math.random() * 100)}`}`;

    // support document.body.style.webkitLineClamp
    if (isSupportLineClamp) {
      const style = `#${id}{-webkit-line-clamp:${lines};}`;
niko's avatar
niko committed
170
      return (
171
        <div id={id} className={cls} {...restProps}>
niko's avatar
niko committed
172
          <style>{style}</style>
173 174 175 176
          {
            tooltip ? (<Tooltip title={text}>{children}</Tooltip>) : children
          }
        </div>);
niko's avatar
niko committed
177 178
    }

179
    const childNode = (
180
      <span ref={this.handleNode}>
181 182 183 184 185 186 187 188
        {
          (targetCount > 0) && text.substring(0, targetCount)
        }
        {
          (targetCount > 0) && (targetCount < text.length) && '...'
        }
      </span>
    );
niko's avatar
niko committed
189 190 191 192

    return (
      <div
        {...restProps}
193
        ref={this.handleRoot}
niko's avatar
niko committed
194 195
        className={cls}
      >
196 197 198 199 200 201 202 203 204 205 206
        <div
          ref={this.handleContent}
        >
          {
            tooltip ? (
              <Tooltip title={text}>{childNode}</Tooltip>
            ) : childNode
          }
          <div className={styles.shadow} ref={this.handleShadowChildren}>{children}</div>
          <div className={styles.shadow} ref={this.handleShadow}><span>{text}</span></div>
        </div>
niko's avatar
niko committed
207 208 209 210
      </div>
    );
  }
}