index.js 6.44 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',
};

twisger's avatar
twisger committed
16
export const getStrFullLength = (str = '') => {
17 18 19 20 21 22 23 24 25 26
  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
27
export const cutStrByFullLength = (str = '', maxLength) => {
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
  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
44
const EllipsisText = ({ text, length, tooltip, fullWidthRecognition, ...other }) => {
niko's avatar
niko committed
45 46 47
  if (typeof text !== 'string') {
    throw new Error('Ellipsis children must be string.');
  }
twisger's avatar
twisger committed
48
  const textLength = fullWidthRecognition ? getStrFullLength(text) : text.length;
49
  if (textLength <= length || length < 0) {
niko's avatar
niko committed
50 51 52 53 54 55 56
    return <span {...other}>{text}</span>;
  }
  const tail = '...';
  let displayText;
  if (length - tail.length <= 0) {
    displayText = '';
  } else {
twisger's avatar
twisger committed
57
    displayText = fullWidthRecognition ? cutStrByFullLength(text, length) : text.slice(0, length);
niko's avatar
niko committed
58 59 60
  }

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

  return (
    <span {...other}>
73 74
      {displayText}
      {tail}
niko's avatar
niko committed
75 76 77 78
    </span>
  );
};

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

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

  componentWillReceiveProps(nextProps) {
92 93
    const { lines } = this.props;
    if (lines !== nextProps.lines) {
niko's avatar
niko committed
94 95 96 97 98
      this.computeLine();
    }
  }

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

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

niko's avatar
niko committed
116 117
      // bisection
      const len = text.length;
118
      const mid = Math.ceil(len / 2);
niko's avatar
niko committed
119

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

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

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

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

jim's avatar
jim committed
167
  handleRoot = n => {
168
    this.root = n;
169
  };
170

jim's avatar
jim committed
171
  handleContent = n => {
172
    this.content = n;
173
  };
174

jim's avatar
jim committed
175
  handleNode = n => {
niko's avatar
niko committed
176
    this.node = n;
177
  };
niko's avatar
niko committed
178

jim's avatar
jim committed
179
  handleShadow = n => {
niko's avatar
niko committed
180
    this.shadow = n;
181
  };
niko's avatar
niko committed
182

jim's avatar
jim committed
183
  handleShadowChildren = n => {
niko's avatar
niko committed
184
    this.shadowChildren = n;
185
  };
niko's avatar
niko committed
186 187

  render() {
188
    const { text, targetCount } = this.state;
189 190 191 192 193 194
    const {
      children,
      lines,
      length,
      className,
      tooltip,
twisger's avatar
twisger committed
195
      fullWidthRecognition,
196 197
      ...restProps
    } = this.props;
niko's avatar
niko committed
198 199

    const cls = classNames(styles.ellipsis, className, {
200 201
      [styles.lines]: lines && !isSupportLineClamp,
      [styles.lineClamp]: lines && isSupportLineClamp,
niko's avatar
niko committed
202 203 204
    });

    if (!lines && !length) {
205 206 207 208 209
      return (
        <span className={cls} {...restProps}>
          {children}
        </span>
      );
niko's avatar
niko committed
210 211 212 213
    }

    // length
    if (!lines) {
214 215 216 217 218 219
      return (
        <EllipsisText
          className={cls}
          length={length}
          text={children || ''}
          tooltip={tooltip}
twisger's avatar
twisger committed
220
          fullWidthRecognition={fullWidthRecognition}
221 222 223
          {...restProps}
        />
      );
niko's avatar
niko committed
224 225
    }

226 227 228 229
    const id = `antd-pro-ellipsis-${`${new Date().getTime()}${Math.floor(Math.random() * 100)}`}`;

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

245
    const childNode = (
246
      <span ref={this.handleNode}>
247 248
        {targetCount > 0 && text.substring(0, targetCount)}
        {targetCount > 0 && targetCount < text.length && '...'}
249 250
      </span>
    );
niko's avatar
niko committed
251 252

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