index.js 6.27 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 88
    const { lines } = this.props;
    if (lines !== nextProps.lines) {
niko's avatar
niko committed
89 90 91 92 93
      this.computeLine();
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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