-
Notifications
You must be signed in to change notification settings - Fork 129
/
Truncate.js
373 lines (302 loc) · 9.92 KB
/
Truncate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class Truncate extends Component {
static propTypes = {
children: PropTypes.node,
ellipsis: PropTypes.node,
lines: PropTypes.oneOfType([
PropTypes.oneOf([false]),
PropTypes.number
]),
trimWhitespace: PropTypes.bool,
width: PropTypes.number,
onTruncate: PropTypes.func
};
static defaultProps = {
children: '',
ellipsis: '…',
lines: 1,
trimWhitespace: false,
width: 0
};
state = {};
constructor(...args) {
super(...args);
this.elements = {};
this.onResize = this.onResize.bind(this);
this.onTruncate = this.onTruncate.bind(this);
this.calcTargetWidth = this.calcTargetWidth.bind(this);
this.measureWidth = this.measureWidth.bind(this);
this.getLines = this.getLines.bind(this);
this.renderLine = this.renderLine.bind(this);
}
componentDidMount() {
const {
elements: {
text
},
calcTargetWidth,
onResize
} = this;
const canvas = document.createElement('canvas');
this.canvasContext = canvas.getContext('2d');
calcTargetWidth(() => {
// Node not needed in document tree to read its content
if (text) {
text.parentNode.removeChild(text);
}
});
window.addEventListener('resize', onResize);
}
componentDidUpdate(prevProps) {
// Render was based on outdated refs and needs to be rerun
if (this.props.children !== prevProps.children) {
this.forceUpdate();
}
// If the width prop has changed, recalculate size of contents
if (this.props.width !== prevProps.width) {
this.calcTargetWidth();
}
}
componentWillUnmount() {
const {
elements: {
ellipsis
},
onResize,
timeout
} = this;
if (ellipsis && ellipsis.parentNode) {
ellipsis.parentNode.removeChild(ellipsis);
}
window.removeEventListener('resize', onResize);
window.cancelAnimationFrame(timeout);
}
// Shim innerText to consistently break lines at <br/> but not at \n
innerText(node) {
const div = document.createElement('div');
const contentKey = 'innerText' in window.HTMLElement.prototype ? 'innerText' : 'textContent';
div.innerHTML = node.innerHTML.replace(/\r\n|\r|\n/g, ' ');
let text = div[contentKey];
const test = document.createElement('div');
test.innerHTML = 'foo<br/>bar';
if (test[contentKey].replace(/\r\n|\r/g, '\n') !== 'foo\nbar') {
div.innerHTML = div.innerHTML.replace(/<br.*?[\/]?>/gi, '\n');
text = div[contentKey];
}
return text;
}
onResize() {
this.calcTargetWidth();
}
onTruncate(didTruncate) {
const {
onTruncate
} = this.props;
if (typeof onTruncate === 'function') {
this.timeout = window.requestAnimationFrame(() => {
onTruncate(didTruncate);
});
}
}
calcTargetWidth(callback) {
const {
elements: {
target
},
calcTargetWidth,
canvasContext,
props: {
width
}
} = this;
// Calculation is no longer relevant, since node has been removed
if (!target) {
return;
}
const targetWidth = (
width ||
// Floor the result to deal with browser subpixel precision
Math.floor(target.parentNode.getBoundingClientRect().width)
);
// Delay calculation until parent node is inserted to the document
// Mounting order in React is ChildComponent, ParentComponent
if (!targetWidth) {
return window.requestAnimationFrame(() => calcTargetWidth(callback));
}
const style = window.getComputedStyle(target);
const font = [
style['font-weight'],
style['font-style'],
style['font-size'],
style['font-family']
].join(' ');
canvasContext.font = font;
this.setState({
targetWidth
}, callback);
}
measureWidth(text) {
return this.canvasContext.measureText(text).width;
}
ellipsisWidth(node) {
return node.offsetWidth;
}
trimRight(text) {
return text.replace(/\s+$/, '');
}
getLines() {
const {
elements,
props: {
lines: numLines,
ellipsis,
trimWhitespace
},
state: {
targetWidth
},
innerText,
measureWidth,
onTruncate,
trimRight
} = this;
const lines = [];
const text = innerText(elements.text);
const textLines = text.split('\n').map(line => line.split(' '));
let didTruncate = true;
const ellipsisWidth = this.ellipsisWidth(this.elements.ellipsis);
for (let line = 1; line <= numLines; line++) {
const textWords = textLines[0];
// Handle newline
if (textWords.length === 0) {
lines.push();
textLines.shift();
line--;
continue;
}
let resultLine = textWords.join(' ');
if (measureWidth(resultLine) <= targetWidth) {
if (textLines.length === 1) {
// Line is end of text and fits without truncating
didTruncate = false;
lines.push(resultLine);
break;
}
}
if (line === numLines) {
// Binary search determining the longest possible line inluding truncate string
const textRest = textWords.join(' ');
let lower = 0;
let upper = textRest.length - 1;
while (lower <= upper) {
const middle = Math.floor((lower + upper) / 2);
const testLine = textRest.slice(0, middle + 1);
if (measureWidth(testLine) + ellipsisWidth <= targetWidth) {
lower = middle + 1;
} else {
upper = middle - 1;
}
}
let lastLineText = textRest.slice(0, lower);
if (trimWhitespace) {
lastLineText = trimRight(lastLineText);
// Remove blank lines from the end of text
while (!lastLineText.length && lines.length) {
const prevLine = lines.pop();
lastLineText = trimRight(prevLine);
}
}
resultLine = <span>{lastLineText}{ellipsis}</span>;
} else {
// Binary search determining when the line breaks
let lower = 0;
let upper = textWords.length - 1;
while (lower <= upper) {
const middle = Math.floor((lower + upper) / 2);
const testLine = textWords.slice(0, middle + 1).join(' ');
if (measureWidth(testLine) <= targetWidth) {
lower = middle + 1;
} else {
upper = middle - 1;
}
}
// The first word of this line is too long to fit it
if (lower === 0) {
// Jump to processing of last line
line = numLines - 1;
continue;
}
resultLine = textWords.slice(0, lower).join(' ');
textLines[0].splice(0, lower);
}
lines.push(resultLine);
}
onTruncate(didTruncate);
return lines;
}
renderLine(line, i, arr) {
if (i === arr.length - 1) {
return <span key={i}>{line}</span>;
} else {
const br = <br key={i + 'br'} />;
if (line) {
return [
<span key={i}>{line}</span>,
br
];
} else {
return br;
}
}
}
render() {
const {
elements: {
target
},
props: {
children,
ellipsis,
lines,
...spanProps
},
state: {
targetWidth
},
getLines,
renderLine,
onTruncate
} = this;
let text;
const mounted = !!(target && targetWidth);
if (typeof window !== 'undefined' && mounted) {
if (lines > 0) {
text = getLines().map(renderLine);
} else {
text = children;
onTruncate(false);
}
}
delete spanProps.onTruncate;
delete spanProps.trimWhitespace;
delete spanProps.width;
return (
<span {...spanProps} ref={(targetEl) => { this.elements.target = targetEl; }}>
<span>{text}</span>
<span ref={(textEl) => { this.elements.text = textEl; }}>{children}</span>
<span ref={(ellipsisEl) => { this.elements.ellipsis = ellipsisEl; }} style={this.styles.ellipsis}>
{ellipsis}
</span>
</span>
);
}
styles = {
ellipsis: {
position: 'fixed',
visibility: 'hidden',
top: 0,
left: 0
}
};
};