index.js 6.5 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 42 43 44 45 46 47 48 49 50 51 52
const getTooltip = ({ tooltip, overlayStyle, title, children }) => {
  if(tooltip) {
    const props = tooltip === true ? { overlayStyle, title } : { ...tooltip, overlayStyle, title };
    return (
      <Tooltip {...props}>
        {children}
      </Tooltip>
    )
  }
  return children;
}

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

69 70 71 72 73 74 75 76
  const spanAttrs = tooltip ? {} : { ...other };
  return getTooltip(
    {
      tooltip,
      overlayStyle:TooltipOverlayStyle,
      title: text,
      children: (
        <span {...spanAttrs}>
77 78 79
          {displayText}
          {tail}
        </span>
80 81
      )
    });
niko's avatar
niko committed
82 83
};

84
export default class Ellipsis extends Component {
niko's avatar
niko committed
85 86 87
  state = {
    text: '',
    targetCount: 0,
88
  };
niko's avatar
niko committed
89 90 91 92 93 94 95

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

jim's avatar
jim committed
96
  componentDidUpdate(perProps) {
陈帅's avatar
陈帅 committed
97 98
    const { lines } = this.props;
    if (lines !== perProps.lines) {
niko's avatar
niko committed
99 100 101 102 103
      this.computeLine();
    }
  }

  computeLine = () => {
104 105
    const { lines } = this.props;
    if (lines && !isSupportLineClamp) {
宜鑫's avatar
宜鑫 committed
106
      const text = this.shadowChildren.innerText || this.shadowChildren.textContent;
107 108 109 110
      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
111 112
      const shadowNode = this.shadow.firstChild;

113 114 115 116 117 118 119 120
      if (totalHeight <= targetHeight) {
        this.setState({
          text,
          targetCount: text.length,
        });
        return;
      }

niko's avatar
niko committed
121 122
      // bisection
      const len = text.length;
123
      const mid = Math.ceil(len / 2);
niko's avatar
niko committed
124

125
      const count = this.bisection(targetHeight, mid, 0, len, text, shadowNode);
niko's avatar
niko committed
126 127 128 129 130 131

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

134 135
  bisection = (th, m, b, e, text, shadowNode) => {
    const suffix = '...';
niko's avatar
niko committed
136 137 138
    let mid = m;
    let end = e;
    let begin = b;
139 140
    shadowNode.innerHTML = text.substring(0, mid) + suffix;
    let sh = shadowNode.offsetHeight;
niko's avatar
niko committed
141

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

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

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

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

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

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

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

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

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

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

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

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

      const node = (
235
        <div id={id} className={cls} {...restProps}>
niko's avatar
niko committed
236
          <style>{style}</style>
237
          {children}
238 239
        </div>
      );
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

niko's avatar
niko committed
252
    return (
253 254
      <div {...restProps} ref={this.handleRoot} className={cls}>
        <div ref={this.handleContent}>
255 256 257
          {
            getTooltip({ tooltip, overlayStyle:TooltipOverlayStyle, title: text, children: 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>
    );
  }
}