-
Notifications
You must be signed in to change notification settings - Fork 129
/
Truncate.js
333 lines (269 loc) · 8.52 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
import React, { Component, PropTypes } from 'react';
export default class Truncate extends Component {
static propTypes = {
children: PropTypes.node,
ellipsis: PropTypes.node,
lines: PropTypes.oneOfType([
PropTypes.oneOf([false]),
PropTypes.number
]),
onTruncate: PropTypes.func
};
static defaultProps = {
children: '',
ellipsis: '…',
lines: 1
};
state = {};
constructor(...args) {
super(...args);
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 {
refs: {
text,
ellipsis
},
calcTargetWidth,
onResize
} = this;
const canvas = document.createElement('canvas');
this.canvas = canvas.getContext('2d');
// Keep node in document body to read .offsetWidth
document.body.appendChild(ellipsis);
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();
}
}
componentWillUnmount() {
const {
refs: {
ellipsis
},
onResize,
timeout
} = this;
ellipsis.parentNode.removeChild(ellipsis);
window.removeEventListener('resize', onResize);
cancelAnimationFrame(timeout);
}
// Shim innerText to consistently break lines at <br/> but not at \n
innerText(node) {
const div = document.createElement('div');
div.innerHTML = node.innerHTML.replace(/\r\n|\r|\n/g, ' ');
let text = div.innerText;
const test = document.createElement('div');
test.innerHTML = 'foo<br/>bar';
if (test.innerText.replace(/\r\n|\r/g, '\n') !== 'foo\nbar') {
div.innerHTML = div.innerHTML.replace(/<br.*?[\/]?>/gi, '\n');
text = div.innerText;
}
return text;
}
onResize() {
this.calcTargetWidth();
}
onTruncate(didTruncate) {
const {
onTruncate
} = this.props;
if (typeof onTruncate === 'function') {
this.timeout = requestAnimationFrame(() => {
onTruncate(didTruncate);
});
}
}
calcTargetWidth(callback) {
const {
refs: {
target
},
calcTargetWidth,
canvas
} = this;
// Calculation is no longer relevant, since node has been removed
if (!target) {
return;
}
const targetWidth = target.parentNode.getBoundingClientRect().width;
// Delay calculation until parent node is inserted to the document
// Mounting order in React is ChildComponent, ParentComponent
if (!targetWidth) {
return requestAnimationFrame(() => calcTargetWidth(callback));
}
const style = window.getComputedStyle(target);
const font = [
style['font-weight'],
style['font-style'],
style['font-size'],
style['font-family']
].join(' ');
canvas.font = font;
this.setState({
targetWidth
}, callback);
}
measureWidth(text) {
return this.canvas.measureText(text).width;
}
ellipsisWidth(node) {
return node.offsetWidth;
}
getLines() {
const {
refs,
props: {
lines: numLines,
ellipsis
},
state: {
targetWidth
},
innerText,
measureWidth,
onTruncate
} = this;
const lines = [];
const text = innerText(refs.text);
const textLines = text.split('\n').map(line => line.split(' '));
let didTruncate = true;
const ellipsisWidth = this.ellipsisWidth(this.refs.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;
}
}
resultLine = <span>{textRest.slice(0, lower)}{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 {
refs: {
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;
return (
<span {...spanProps} ref='target'>
{text}
<span ref='text'>{children}</span>
<span ref='ellipsis' style={this.styles.ellipsis}>
{ellipsis}
</span>
</span>
);
}
styles = {
ellipsis: {
position: 'fixed',
visibility: 'hidden',
top: 0,
left: 0
}
};
};