index.js 5.35 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
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 {
23
    displayText = text.slice(0, length - tail.length);
niko's avatar
niko committed
24 25 26
  }

  if (tooltip) {
27
    return (
nikogu's avatar
nikogu committed
28
      <Tooltip overlayStyle={{ wordBreak: 'break-all' }} title={text}>
29 30 31 32 33 34
        <span>
          {displayText}
          {tail}
        </span>
      </Tooltip>
    );
niko's avatar
niko committed
35 36 37 38
  }

  return (
    <span {...other}>
39 40
      {displayText}
      {tail}
niko's avatar
niko committed
41 42 43 44
    </span>
  );
};

45
export default class Ellipsis extends Component {
niko's avatar
niko committed
46 47 48
  state = {
    text: '',
    targetCount: 0,
49
  };
niko's avatar
niko committed
50 51 52 53 54 55 56 57

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

  componentWillReceiveProps(nextProps) {
58
    if (this.props.lines !== nextProps.lines) {
niko's avatar
niko committed
59 60 61 62 63
      this.computeLine();
    }
  }

  computeLine = () => {
64 65
    const { lines } = this.props;
    if (lines && !isSupportLineClamp) {
niko's avatar
niko committed
66
      const text = this.shadowChildren.innerText;
67 68 69 70
      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
71 72
      const shadowNode = this.shadow.firstChild;

73 74 75 76 77 78 79 80
      if (totalHeight <= targetHeight) {
        this.setState({
          text,
          targetCount: text.length,
        });
        return;
      }

niko's avatar
niko committed
81 82 83 84
      // bisection
      const len = text.length;
      const mid = Math.floor(len / 2);

85
      const count = this.bisection(targetHeight, mid, 0, len, text, shadowNode);
niko's avatar
niko committed
86 87 88 89 90 91

      this.setState({
        text,
        targetCount: count,
      });
    }
92
  };
niko's avatar
niko committed
93

94 95
  bisection = (th, m, b, e, text, shadowNode) => {
    const suffix = '...';
niko's avatar
niko committed
96 97 98
    let mid = m;
    let end = e;
    let begin = b;
99 100
    shadowNode.innerHTML = text.substring(0, mid) + suffix;
    let sh = shadowNode.offsetHeight;
niko's avatar
niko committed
101

102
    if (sh <= th) {
103 104
      shadowNode.innerHTML = text.substring(0, mid + 1) + suffix;
      sh = shadowNode.offsetHeight;
105
      if (sh > th) {
niko's avatar
niko committed
106 107 108 109
        return mid;
      } else {
        begin = mid;
        mid = Math.floor((end - begin) / 2) + begin;
110
        return this.bisection(th, mid, begin, end, text, shadowNode);
niko's avatar
niko committed
111 112 113 114 115
      }
    } else {
      if (mid - 1 < 0) {
        return mid;
      }
116 117 118
      shadowNode.innerHTML = text.substring(0, mid - 1) + suffix;
      sh = shadowNode.offsetHeight;
      if (sh <= th) {
119
        return mid - 1;
niko's avatar
niko committed
120 121 122
      } else {
        end = mid;
        mid = Math.floor((end - begin) / 2) + begin;
123
        return this.bisection(th, mid, begin, end, text, shadowNode);
niko's avatar
niko committed
124 125
      }
    }
126
  };
niko's avatar
niko committed
127

jim's avatar
jim committed
128
  handleRoot = n => {
129
    this.root = n;
130
  };
131

jim's avatar
jim committed
132
  handleContent = n => {
133
    this.content = n;
134
  };
135

jim's avatar
jim committed
136
  handleNode = n => {
niko's avatar
niko committed
137
    this.node = n;
138
  };
niko's avatar
niko committed
139

jim's avatar
jim committed
140
  handleShadow = n => {
niko's avatar
niko committed
141
    this.shadow = n;
142
  };
niko's avatar
niko committed
143

jim's avatar
jim committed
144
  handleShadowChildren = n => {
niko's avatar
niko committed
145
    this.shadowChildren = n;
146
  };
niko's avatar
niko committed
147 148

  render() {
149
    const { text, targetCount } = this.state;
150
    const { children, lines, length, className, tooltip, ...restProps } = this.props;
niko's avatar
niko committed
151 152

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

    if (!lines && !length) {
158 159 160 161 162
      return (
        <span className={cls} {...restProps}>
          {children}
        </span>
      );
niko's avatar
niko committed
163 164 165 166
    }

    // length
    if (!lines) {
167 168 169 170 171 172 173 174 175
      return (
        <EllipsisText
          className={cls}
          length={length}
          text={children || ''}
          tooltip={tooltip}
          {...restProps}
        />
      );
niko's avatar
niko committed
176 177
    }

178 179 180 181
    const id = `antd-pro-ellipsis-${`${new Date().getTime()}${Math.floor(Math.random() * 100)}`}`;

    // support document.body.style.webkitLineClamp
    if (isSupportLineClamp) {
182
      const style = `#${id}{-webkit-line-clamp:${lines};-webkit-box-orient: vertical;}`;
niko's avatar
niko committed
183
      return (
184
        <div id={id} className={cls} {...restProps}>
niko's avatar
niko committed
185
          <style>{style}</style>
nikogu's avatar
nikogu committed
186 187 188 189 190 191 192
          {tooltip ? (
            <Tooltip overlayStyle={{ wordBreak: 'break-all' }} title={children}>
              {children}
            </Tooltip>
          ) : (
            children
          )}
193 194
        </div>
      );
niko's avatar
niko committed
195 196
    }

197
    const childNode = (
198
      <span ref={this.handleNode}>
199 200
        {targetCount > 0 && text.substring(0, targetCount)}
        {targetCount > 0 && targetCount < text.length && '...'}
201 202
      </span>
    );
niko's avatar
niko committed
203 204

    return (
205 206
      <div {...restProps} ref={this.handleRoot} className={cls}>
        <div ref={this.handleContent}>
nikogu's avatar
nikogu committed
207 208 209 210 211 212 213
          {tooltip ? (
            <Tooltip overlayStyle={{ wordBreak: 'break-all' }} title={text}>
              {childNode}
            </Tooltip>
          ) : (
            childNode
          )}
214 215 216 217 218 219
          <div className={styles.shadow} ref={this.handleShadowChildren}>
            {children}
          </div>
          <div className={styles.shadow} ref={this.handleShadow}>
            <span>{text}</span>
          </div>
220
        </div>
niko's avatar
niko committed
221 222 223 224
      </div>
    );
  }
}