Clock.js 1.7 KB

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