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

41
const getTooltip = ({ tooltip, overlayStyle, title, children }) => {
陈帅's avatar
陈帅 committed
42
  if (tooltip) {
43
    const props = tooltip === true ? { overlayStyle, title } : { ...tooltip, overlayStyle, title };
陈帅's avatar
陈帅 committed
44
    return <Tooltip {...props}>{children}</Tooltip>;
45 46
  }
  return children;
陈帅's avatar
陈帅 committed
47
};
48

twisger's avatar
twisger committed
49
const EllipsisText = ({ text, length, tooltip, fullWidthRecognition, ...other }) => {
niko's avatar
niko committed
50 51 52
  if (typeof text !== 'string') {
    throw new Error('Ellipsis children must be string.');
  }
twisger's avatar
twisger committed
53
  const textLength = fullWidthRecognition ? getStrFullLength(text) : text.length;
54
  if (textLength <= length || length < 0) {
niko's avatar
niko committed
55 56 57 58 59 60 61
    return <span {...other}>{text}</span>;
  }
  const tail = '...';
  let displayText;
  if (length - tail.length <= 0) {
    displayText = '';
  } else {
twisger's avatar
twisger committed
62
    displayText = fullWidthRecognition ? cutStrByFullLength(text, length) : text.slice(0, length);
niko's avatar
niko committed
63 64
  }

65
  const spanAttrs = tooltip ? {} : { ...other };
陈帅's avatar
陈帅 committed
66 67 68 69 70 71 72 73 74 75 76
  return getTooltip({
    tooltip,
    overlayStyle: TooltipOverlayStyle,
    title: text,
    children: (
      <span {...spanAttrs}>
        {displayText}
        {tail}
      </span>
    ),
  });
niko's avatar
niko committed
77 78
};

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) {
宜鑫's avatar
宜鑫 committed
101
      const text = this.shadowChildren.innerText || this.shadowChildren.textContent;
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
        return mid;
      }
143 144 145
      begin = mid;
      if (end - begin === 1) {
        mid = 1 + begin;
niko's avatar
niko committed
146 147 148
      } else {
        mid = Math.floor((end - begin) / 2) + begin;
      }
149 150 151 152 153 154 155 156 157
      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
158
    }
159 160 161
    end = mid;
    mid = Math.floor((end - begin) / 2) + begin;
    return this.bisection(th, mid, begin, end, text, shadowNode);
162
  };
niko's avatar
niko committed
163

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

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

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

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

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

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

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

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

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

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

    // support document.body.style.webkitLineClamp
    if (isSupportLineClamp) {
227
      const style = `#${id}{-webkit-line-clamp:${lines};-webkit-box-orient: vertical;}`;
228 229

      const node = (
230
        <div id={id} className={cls} {...restProps}>
niko's avatar
niko committed
231
          <style>{style}</style>
232
          {children}
233 234
        </div>
      );
235

陈帅's avatar
陈帅 committed
236 237 238 239 240 241
      return getTooltip({
        tooltip,
        overlayStyle: TooltipOverlayStyle,
        title: children,
        children: node,
      });
niko's avatar
niko committed
242 243
    }

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

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