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

11 12 13 14 15
const TooltipOverlayStyle = {
  overflowWrap: 'break-word',
  wordWrap: 'break-word',
};

16 17
export const getStrFullLength = (str = '') =>
  str.split('').reduce((pre, cur) => {
18 19 20 21
    const charCode = cur.charCodeAt(0);
    if (charCode >= 0 && charCode <= 128) {
      return pre + 1;
    }
22
    return pre + 2;
23 24
  }, 0);

twisger's avatar
twisger committed
25
export const cutStrByFullLength = (str = '', maxLength) => {
26 27 28 29 30 31 32 33 34 35 36
  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;
    }
37
    return pre;
38 39 40
  }, '');
};

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

  if (tooltip) {
58
    return (
59
      <Tooltip overlayStyle={TooltipOverlayStyle} title={text}>
60 61 62 63 64 65
        <span>
          {displayText}
          {tail}
        </span>
      </Tooltip>
    );
niko's avatar
niko committed
66 67 68 69
  }

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

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

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

jim's avatar
jim committed
88
  componentDidUpdate(perProps) {
陈帅's avatar
陈帅 committed
89 90
    const { lines } = this.props;
    if (lines !== perProps.lines) {
niko's avatar
niko committed
91 92 93 94 95
      this.computeLine();
    }
  }

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

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

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

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

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

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

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

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

jim's avatar
jim committed
165
  handleContent = n => {
166
    this.content = n;
167
  };
168

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

jim's avatar
jim committed
173
  handleShadow = n => {
niko's avatar
niko committed
174
    this.shadow = n;
175
  };
niko's avatar
niko committed
176

jim's avatar
jim committed
177
  handleShadowChildren = n => {
niko's avatar
niko committed
178
    this.shadowChildren = n;
179
  };
niko's avatar
niko committed
180 181

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

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

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

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

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

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

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

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