Skip to content

Commit 9044f0f

Browse files
committed
Merge pull request #15 from SeeThruHead/raf
adds request animation frame option
2 parents dbdd694 + 409cd26 commit 9044f0f

File tree

3 files changed

+26
-9
lines changed

3 files changed

+26
-9
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
"babel-loader": "^6.2.0",
3131
"babel-plugin-add-module-exports": "^0.1.2",
3232
"babel-plugin-react-transform": "^1.1.1",
33+
"babel-plugin-transform-es2015-modules-umd": "^6.6.5",
3334
"babel-preset-es2015": "^6.1.18",
3435
"babel-preset-react": "^6.1.18",
3536
"babel-preset-stage-0": "^6.1.18",

src/App.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ export class App extends Component {
1010
truncateText: '…',
1111
showTitle: true,
1212
textTruncateChild: <a className='pull-right' onClick={this.showAll}>show more</a>,
13-
showAll: false
13+
showAll: false,
14+
raf: true
1415
};
1516
}
1617

src/TextTruncate.js

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,6 @@ export default class TextTruncate extends Component {
1616
showTitle: true
1717
};
1818

19-
constructor() {
20-
super();
21-
this.onResize = this.onResize.bind(this);
22-
}
2319
componentWillMount() {
2420
let canvas = document.createElement('canvas');
2521
let docFragment = document.createDocumentFragment();
@@ -35,14 +31,33 @@ export default class TextTruncate extends Component {
3531
font.push(style['font-family']);
3632
this.canvas.font = font.join(' ');
3733
this.forceUpdate();
38-
window.addEventListener('resize', this.onResize);
34+
35+
if (this.props.raf) {
36+
this.loopId = window.requestAnimationFrame(this.animationStep);
37+
} else {
38+
window.addEventListener('resize', this.onResize);
39+
}
3940
}
4041
componentWillUnmount() {
41-
window.removeEventListener('resize', this.onResize);
42+
if (this.props.raf) {
43+
window.cancelAnimationFrame(this.loopId);
44+
} else {
45+
window.removeEventListener('resize', this.onResize);
46+
}
4247
}
43-
onResize() {
48+
animationStep = timeStamp => {
49+
if ((timeStamp - this.lastTime) < 150) {
50+
this.loopId = window.requestAnimationFrame(this.animationStep);
51+
return;
52+
}
53+
54+
this.lastTime = timeStamp;
55+
this.onResize();
56+
this.loopId = window.requestAnimationFrame(this.animationStep);
57+
};
58+
onResize = () => {
4459
this.forceUpdate();
45-
}
60+
};
4661
measureWidth(text) {
4762
return this.canvas.measureText(text).width;
4863
}

0 commit comments

Comments
 (0)