Index.js 2.4 KB

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