Clock.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. import React from 'react/addons';
  3. import GameActions from '../actions/GameActions';
  4. const PureRenderMixin = React.addons.PureRenderMixin;
  5. const Clock = React.createClass({
  6. propTypes: {
  7. io: React.PropTypes.object.isRequired,
  8. params: React.PropTypes.array.isRequired
  9. },
  10. mixins: [PureRenderMixin],
  11. getInitialState() {
  12. const [_, time, inc] = this.props.params;
  13. return {
  14. white: time * 60,
  15. black: time * 60,
  16. inc: inc,
  17. countdown: null
  18. };
  19. },
  20. componentDidMount() {
  21. const io = this.props.io;
  22. io.on('countdown', data => this.setState({
  23. [data.color]: data.time,
  24. countdown: data.color
  25. }));
  26. io.on('countdown-gameover', data => {
  27. this.setState({countdown: null});
  28. GameActions.gameOver({
  29. type: 'timeout',
  30. winner: data.color === 'black' ? 'White' : 'Black'
  31. });
  32. });
  33. io.on('rematch-accepted', () => {
  34. this.setState({
  35. white: this.props.params[1] * 60,
  36. black: this.props.params[1] * 60
  37. });
  38. });
  39. },
  40. render() {
  41. return (
  42. <ul id="clock">
  43. <Timer
  44. color="white"
  45. time={this.state.white}
  46. countdown={this.state.countdown} />
  47. <Timer
  48. color="black"
  49. time={this.state.black}
  50. countdown={this.state.countdown} />
  51. </ul>
  52. );
  53. }
  54. });
  55. const Timer = React.createClass({
  56. mixins: [PureRenderMixin],
  57. render() {
  58. const {time, color, countdown} = this.props;
  59. const min = Math.floor(time / 60);
  60. const sec = time % 60;
  61. const timeLeft = `${min}:${sec < 10 ? '0' + sec : sec}`;
  62. return (
  63. <li className={color + (color === countdown ? ' ticking' : '')}>
  64. {timeLeft}
  65. </li>
  66. );
  67. }
  68. });
  69. export default Clock;