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

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

jim's avatar
jim committed
91
  componentDidUpdate(perProps) {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
92 93
    const { lines } = this.props;
    if (lines !== perProps.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) {
niko's avatar
niko committed
141 142 143 144
        return mid;
      } else {
        begin = mid;
        mid = Math.floor((end - begin) / 2) + begin;
145
        return this.bisection(th, mid, begin, end, text, shadowNode);
niko's avatar
niko committed
146 147 148 149 150
      }
    } else {
      if (mid - 1 < 0) {
        return mid;
      }
151 152 153
      shadowNode.innerHTML = text.substring(0, mid - 1) + suffix;
      sh = shadowNode.offsetHeight;
      if (sh <= th) {
154
        return mid - 1;
niko's avatar
niko committed
155 156 157
      } else {
        end = mid;
        mid = Math.floor((end - begin) / 2) + begin;
158
        return this.bisection(th, mid, begin, end, text, shadowNode);
niko's avatar
niko committed
159 160
      }
    }
161
  };
niko's avatar
niko committed
162

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

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

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

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

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

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

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

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

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

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

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

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

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