|
1 | 1 | import React from 'react';
|
2 |
| -import Radium from 'radium'; |
3 |
| -import moment from 'moment-timezone'; |
4 | 2 | import { sprintf } from 'sprintf-js/src/sprintf';
|
5 | 3 |
|
6 | 4 | export class Stopwatch extends React.Component {
|
| 5 | + |
7 | 6 | static propTypes = {
|
8 | 7 | style: React.PropTypes.object,
|
9 |
| - } |
| 8 | + className: React.PropTypes.string, |
| 9 | + start: React.PropTypes.instanceOf(Date), |
| 10 | + }; |
10 | 11 |
|
11 | 12 | static defaultProps = {
|
12 | 13 | style: {},
|
13 |
| - } |
| 14 | + }; |
| 15 | + |
| 16 | + state = { |
| 17 | + elapsed: 0, |
| 18 | + startTime: new Date(), |
| 19 | + timer: null, |
| 20 | + }; |
14 | 21 |
|
15 | 22 | componentWillMount() {
|
| 23 | + const startTime = this.props.start || new Date(); |
16 | 24 | this.setState({
|
17 |
| - elapsed: 0, |
18 |
| - startTime: moment(), |
| 25 | + elapsed: this.calculateElapsedSeconds(startTime), |
| 26 | + startTime: startTime, |
19 | 27 | timer: setInterval(() => {
|
20 | 28 | this.setState({
|
21 |
| - elapsed: moment.duration( |
22 |
| - moment().diff(this.state.startTime) |
23 |
| - ).asSeconds(), |
| 29 | + elapsed: this.calculateElapsedSeconds(this.state.startTime), |
24 | 30 | });
|
25 | 31 | }, 500),
|
26 | 32 | });
|
27 | 33 | }
|
| 34 | + |
| 35 | + calculateElapsedSeconds = (startTime) => { |
| 36 | + const now = new Date(); |
| 37 | + const timeDiff = now.getTime() - startTime.getTime(); |
| 38 | + |
| 39 | + return Math.abs(timeDiff / 1000); |
| 40 | + }; |
| 41 | + |
28 | 42 | componentWillUnmount() {
|
29 | 43 | clearInterval(this.state.timer);
|
30 | 44 | }
|
31 | 45 |
|
32 |
| - getDiffString = () => { |
33 |
| - const duration = moment.duration(this.state.elapsed, 'seconds'); |
| 46 | + getTimeDiffString = () => { |
| 47 | + const seconds = Math.floor(this.state.elapsed % 60); |
| 48 | + const minutes = Math.floor(this.state.elapsed / 60) % 60; |
| 49 | + const hours = Math.floor(this.state.elapsed / 3600); |
| 50 | + |
| 51 | + let timeString = ''; |
34 | 52 |
|
35 |
| - if (duration.hours() > 0) { |
36 |
| - return duration.hours() + ':' + sprintf('%02d', duration.minutes()) + ':' + sprintf('%02d', duration.seconds()); |
| 53 | + if(hours > 0) { |
| 54 | + timeString += sprintf('%02d', hours) + ':'; |
37 | 55 | }
|
38 | 56 |
|
39 |
| - return duration.minutes() + ':' + sprintf('%02d', duration.seconds()); |
40 |
| - } |
| 57 | + timeString += sprintf('%02d', minutes) + ':' + sprintf('%02d', seconds); |
| 58 | + |
| 59 | + return timeString; |
| 60 | + }; |
41 | 61 |
|
42 | 62 | render() {
|
43 | 63 | return (
|
44 |
| - <span style={this.props.style}> |
45 |
| - {this.getDiffString()} |
| 64 | + <span style={this.props.style} className={this.props.className}> |
| 65 | + {this.getTimeDiffString()} |
46 | 66 | </span>
|
47 | 67 | );
|
48 | 68 | }
|
49 | 69 | }
|
50 | 70 |
|
51 |
| -export default Radium(Stopwatch); |
| 71 | +export default Stopwatch; |
0 commit comments