Clock.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. const React = require('react/addons');
  3. const GameActions = require('../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. },
  34. render() {
  35. return (
  36. <ul id="clock">
  37. <Timer
  38. color="white"
  39. time={this.state.white}
  40. countdown={this.state.countdown} />
  41. <Timer
  42. color="black"
  43. time={this.state.black}
  44. countdown={this.state.countdown} />
  45. </ul>
  46. );
  47. }
  48. });
  49. const Timer = React.createClass({
  50. mixins: [PureRenderMixin],
  51. render() {
  52. const {time, color, countdown} = this.props;
  53. const min = Math.floor(time / 60);
  54. const sec = time % 60;
  55. const timeLeft = `${min}:${sec < 10 ? '0' + sec : sec}`;
  56. return (
  57. <li className={color + (color === countdown ? ' ticking' : '')}>
  58. {timeLeft}
  59. </li>
  60. );
  61. }
  62. });
  63. module.exports = Clock;