Index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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
  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. });
  24. });
  25. io.on('ready', () => {
  26. window.location = this.state.link;
  27. });
  28. io.on('token-expired', () => this.setState({hasExpired: true}));
  29. },
  30. render() {
  31. return (
  32. <div>
  33. <img src="/img/knight.png"
  34. width="122"
  35. height="122"
  36. className="knight" />
  37. <h1>Reti Chess</h1>
  38. <div id="create-game">
  39. <CreateGameForm
  40. link={this.state.link}
  41. time={this.state.time}
  42. inc={this.state.inc}
  43. onChangeForm={this._onChangeForm}
  44. createGame={this._createGame} />
  45. <p id="game-status">
  46. {this.state.hasExpired ?
  47. 'Game link has expired, generate a new one'
  48. :this.state.link ?
  49. 'Waiting for opponent to connect'
  50. :null}
  51. </p>
  52. </div>
  53. <p>
  54. Click the button to create a game. Send the link to your friend.
  55. Once the link is opened your friend‘s browser, game should begin
  56. shortly. Colors are picked randomly by computer.
  57. </p>
  58. <p>
  59. <a href="/about" className="alpha">Read more about Reti Chess</a>
  60. </p>
  61. </div>
  62. );
  63. },
  64. _onChangeForm(e) {
  65. this.setState({[e.target.name]: e.target.value});
  66. },
  67. _createGame(e) {
  68. e.preventDefault();
  69. const {time, inc} = this.state;
  70. const isInvalid = [time, inc].some(val => {
  71. val = parseInt(val, 10);
  72. return isNaN(val) || val < 0 || val > 50;
  73. });
  74. if (isInvalid) {
  75. // fallback for old browsers
  76. return window.alert('Form is invalid.');
  77. } else {
  78. this.props.io.emit('start');
  79. }
  80. }
  81. });
  82. export default Index;