index.js 6.24 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

twisger's avatar
twisger committed
11
export const getStrFullLength = (str = '') => {
12 13 14 15 16 17 18 19 20 21
  return str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0);
    if (charCode >= 0 && charCode <= 128) {
      return pre + 1;
    } else {
      return pre + 2;
    }
  }, 0);
};

twisger's avatar
twisger committed
22
export const cutStrByFullLength = (str = '', maxLength) => {
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
  let showLength = 0;
  return str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0);
    if (charCode >= 0 && charCode <= 128) {
      showLength += 1;
    } else {
      showLength += 2;
    }
    if (showLength <= maxLength) {
      return pre + cur;
    } else {
      return pre;
    }
  }, '');
};

twisger's avatar
twisger committed
39
const EllipsisText = ({ text, length, tooltip, fullWidthRecognition, ...other }) => {
niko's avatar
niko committed
40 41 42
  if (typeof text !== 'string') {
    throw new Error('Ellipsis children must be string.');
  }
twisger's avatar
twisger committed
43
  const textLength = fullWidthRecognition ? getStrFullLength(text) : text.length;
44
  if (textLength <= length || length < 0) {
niko's avatar
niko committed
45 46 47 48 49 50 51
    return <span {...other}>{text}</span>;
  }
  const tail = '...';
  let displayText;
  if (length - tail.length <= 0) {
    displayText = '';
  } else {
twisger's avatar
twisger committed
52
    displayText = fullWidthRecognition ? cutStrByFullLength(text, length) : text.slice(0, length);
niko's avatar
niko committed
53 54 55
  }

  if (tooltip) {
56
    return (
nikogu's avatar
nikogu committed
57
      <Tooltip overlayStyle={{ wordBreak: 'break-all' }} title={text}>
58 59 60 61 62 63
        <span>
          {displayText}
          {tail}
        </span>
      </Tooltip>
    );
niko's avatar
niko committed
64 65 66 67
  }

  return (
    <span {...other}>
68 69
      {displayText}
      {tail}
niko's avatar
niko committed
70 71 72 73
    </span>
  );
};

74
export default class Ellipsis extends Component {
niko's avatar
niko committed
75 76 77
  state = {
    text: '',
    targetCount: 0,
78
  };
niko's avatar
niko committed
79 80 81 82 83 84 85 86

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

  componentWillReceiveProps(nextProps) {
87
    if (this.props.lines !== nextProps.lines) {
niko's avatar
niko committed
88 89 90 91 92
      this.computeLine();
    }
  }

  computeLine = () => {
93 94
    const { lines } = this.props;
    if (lines && !isSupportLineClamp) {
niko's avatar
niko committed
95
      const text = this.shadowChildren.innerText;
96 97 98 99
      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
100 101
      const shadowNode = this.shadow.firstChild;

102 103 104 105 106 107 108 109
      if (totalHeight <= targetHeight) {
        this.setState({
          text,
          targetCount: text.length,
        });
        return;
      }

niko's avatar
niko committed
110 111
      // bisection
      const len = text.length;
112
      const mid = Math.ceil(len / 2);
niko's avatar
niko committed
113

114
      const count = this.bisection(targetHeight, mid, 0, len, text, shadowNode);
niko's avatar
niko committed
115 116 117 118 119 120

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

123 124
  bisection = (th, m, b, e, text, shadowNode) => {
    const suffix = '...';
niko's avatar
niko committed
125 126 127
    let mid = m;
    let end = e;
    let begin = b;
128 129
    shadowNode.innerHTML = text.substring(0, mid) + suffix;
    let sh = shadowNode.offsetHeight;
niko's avatar
niko committed
130

131
    if (sh <= th) {
132 133
      shadowNode.innerHTML = text.substring(0, mid + 1) + suffix;
      sh = shadowNode.offsetHeight;
134
      if (sh > th) {
niko's avatar
niko committed
135 136 137 138
        return mid;
      } else {
        begin = mid;
        mid = Math.floor((end - begin) / 2) + begin;
139
        return this.bisection(th, mid, begin, end, text, shadowNode);
niko's avatar
niko committed
140 141 142 143 144
      }
    } else {
      if (mid - 1 < 0) {
        return mid;
      }
145 146 147
      shadowNode.innerHTML = text.substring(0, mid - 1) + suffix;
      sh = shadowNode.offsetHeight;
      if (sh <= th) {
148
        return mid - 1;
niko's avatar
niko committed
149 150 151
      } else {
        end = mid;
        mid = Math.floor((end - begin) / 2) + begin;
152
        return this.bisection(th, mid, begin, end, text, shadowNode);
niko's avatar
niko committed
153 154
      }
    }
155
  };
niko's avatar
niko committed
156

jim's avatar
jim committed
157
  handleRoot = n => {
158
    this.root = n;
159
  };
160

jim's avatar
jim committed
161
  handleContent = n => {
162
    this.content = n;
163
  };
164

jim's avatar
jim committed
165
  handleNode = n => {
niko's avatar
niko committed
166
    this.node = n;
167
  };
niko's avatar
niko committed
168

jim's avatar
jim committed
169
  handleShadow = n => {
niko's avatar
niko committed
170
    this.shadow = n;
171
  };
niko's avatar
niko committed
172

jim's avatar
jim committed
173
  handleShadowChildren = n => {
niko's avatar
niko committed
174
    this.shadowChildren = n;
175
  };
niko's avatar
niko committed
176 177

  render() {
178
    const { text, targetCount } = this.state;
179 180 181 182 183 184
    const {
      children,
      lines,
      length,
      className,
      tooltip,
twisger's avatar
twisger committed
185
      fullWidthRecognition,
186 187
      ...restProps
    } = this.props;
niko's avatar
niko committed
188 189

    const cls = classNames(styles.ellipsis, className, {
190 191
      [styles.lines]: lines && !isSupportLineClamp,
      [styles.lineClamp]: lines && isSupportLineClamp,
niko's avatar
niko committed
192 193 194
    });

    if (!lines && !length) {
195 196 197 198 199
      return (
        <span className={cls} {...restProps}>
          {children}
        </span>
      );
niko's avatar
niko committed
200 201 202 203
    }

    // length
    if (!lines) {
204 205 206 207 208 209
      return (
        <EllipsisText
          className={cls}
          length={length}
          text={children || ''}
          tooltip={tooltip}
twisger's avatar
twisger committed
210
          fullWidthRecognition={fullWidthRecognition}
211 212 213
          {...restProps}
        />
      );
niko's avatar
niko committed
214 215
    }

216 217 218 219
    const id = `antd-pro-ellipsis-${`${new Date().getTime()}${Math.floor(Math.random() * 100)}`}`;

    // support document.body.style.webkitLineClamp
    if (isSupportLineClamp) {
220
      const style = `#${id}{-webkit-line-clamp:${lines};-webkit-box-orient: vertical;}`;
niko's avatar
niko committed
221
      return (
222
        <div id={id} className={cls} {...restProps}>
niko's avatar
niko committed
223
          <style>{style}</style>
nikogu's avatar
nikogu committed
224 225 226 227 228 229 230
          {tooltip ? (
            <Tooltip overlayStyle={{ wordBreak: 'break-all' }} title={children}>
              {children}
            </Tooltip>
          ) : (
            children
          )}
231 232
        </div>
      );
niko's avatar
niko committed
233 234
    }

235
    const childNode = (
236
      <span ref={this.handleNode}>
237 238
        {targetCount > 0 && text.substring(0, targetCount)}
        {targetCount > 0 && targetCount < text.length && '...'}
239 240
      </span>
    );
niko's avatar
niko committed
241 242

    return (
243 244
      <div {...restProps} ref={this.handleRoot} className={cls}>
        <div ref={this.handleContent}>
nikogu's avatar
nikogu committed
245 246 247 248 249 250 251
          {tooltip ? (
            <Tooltip overlayStyle={{ wordBreak: 'break-all' }} title={text}>
              {childNode}
            </Tooltip>
          ) : (
            childNode
          )}
252 253 254 255 256 257
          <div className={styles.shadow} ref={this.handleShadowChildren}>
            {children}
          </div>
          <div className={styles.shadow} ref={this.handleShadow}>
            <span>{text}</span>
          </div>
258
        </div>
niko's avatar
niko committed
259 260 261 262
      </div>
    );
  }
}