Index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 'use strict';
  2. import React from 'react';
  3. import CreateGameForm from './CreateGameForm';
  4. import io from '../io';
  5. const Index = React.createClass({
  6. propTypes: {
  7. io: React.PropTypes.object.isRequired
  8. },
  9. getInitialState() {
  10. return {
  11. link: '',
  12. hasExpired: false,
  13. time: '30',
  14. inc: '0'
  15. };
  16. },
  17. componentDidMount() {
  18. const io = this.props.io;
  19. io.on('created', data => {
  20. const {time, inc} = this.state;
  21. this.setState({
  22. link: `${document.location.origin}/play/${data.token}/${time}/${inc}`,
  23. hasExpired: false
  24. });
  25. });
  26. io.on('ready', () => {
  27. window.location = this.state.link;
  28. });
  29. io.on('token-expired', () => this.setState({hasExpired: true}));
  30. },
  31. render() {
  32. return (
  33. <div>
  34. <img src="/img/knight.png"
  35. width="122"
  36. height="122"
  37. className="knight" />
  38. <h1>Reti Chess</h1>
  39. <div id="create-game">
  40. <CreateGameForm
  41. link={this.state.link}
  42. time={this.state.time}
  43. inc={this.state.inc}
  44. onChangeForm={this._onChangeForm}
  45. createGame={this._createGame} />
  46. <p id="game-status">
  47. {this.state.hasExpired ?
  48. 'Game link has expired, generate a new one'
  49. :this.state.link ?
  50. 'Waiting for opponent to connect'
  51. :null}
  52. </p>
  53. </div>
  54. <p>
  55. Click the button to create a game. Send the link to your friend.
  56. Once the link is opened your friend‘s browser, game should begin
  57. shortly. Colors are picked randomly by computer.
  58. </p>
  59. <p>
  60. <a href="/about" className="alpha">Read more about Reti Chess</a>
  61. </p>
  62. </div>
  63. );
  64. },
  65. _onChangeForm(e) {
  66. this.setState({[e.target.name]: e.target.value});
  67. },
  68. _createGame(e) {
  69. e.preventDefault();
  70. const {time, inc} = this.state;
  71. const isInvalid = [time, inc].some(val => {
  72. val = parseInt(val, 10);
  73. return isNaN(val) || val < 0 || val > 50;
  74. });
  75. if (isInvalid) {
  76. // fallback for old browsers
  77. return window.alert('Form is invalid. Enter numbers between 0 and 50.');
  78. } else {
  79. this.props.io.emit('start');
  80. }
  81. }
  82. });
  83. export default Index;