-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (87 loc) · 2.41 KB
/
index.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
// @flow
import React from 'react';
import truncate from '@konforti/truncate';
import type {
LongText,
Lines,
TruncFrom,
Ellipsis,
WrapperOffset,
WrapperElement,
} from './types.js';
type Props = {
children: string,
style?: Object,
lines?: Lines,
onTruncate?: Function,
truncFrom?: TruncFrom,
ellipsis?: Ellipsis,
wrapperOffset?: WrapperOffset,
};
class ReactTruncate extends React.Component<Props> {
componentDidMount() {
this.handleLongText();
if (this.longTextWrapper) {
window.addEventListener('resize', this.onResize, false);
}
}
componentDidUpdate(prevProps: Props) {
if (prevProps.children !== this.props.children) {
this.handleLongText();
}
}
componentWillUnmount() {
window.removeEventListener('resize', this.onResize, false);
}
onResize = () => {
this.ticking = this.ticking || requestAnimationFrame(this.handleResize);
};
handleResize = () => {
this.ticking = false;
this.handleLongText();
};
// Function reference for
// add/remove event listener.
ticking = false;
async handleLongText() {
if (this.longTextWrapper) {
const res = truncate(
this.longTextWrapper,
this.props.children,
this.props.lines,
this.props.truncFrom,
this.props.ellipsis,
this.props.wrapperOffset
);
this.props.onTruncate && this.props.onTruncate(res);
}
}
// Reference to self wrapper element.
longTextWrapper: ?WrapperElement = null;
render() {
const style = {
...{
wordBreak: 'break-all',
whiteSpace: 'normal',
// Allow word-break in Firefox.
wordWrap: 'break-word',
// Proper calculation of this element's
// clientHeight, offsetHeight, scrollHeight (Firefox).
display: 'inline-block',
},
...this.props.style,
};
return (
<span
className="truncate-wrapper"
style={style}
ref={r => {
this.longTextWrapper = r;
}}
>
{this.props.children}
</span>
);
}
}
export default ReactTruncate;