Index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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/king.svg"
  37. width="50"
  38. height="50"
  39. className="knight" />
  40. <h1>How about a nice game of 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. </div>
  57. );
  58. },
  59. _onChangeForm(e) {
  60. this.setState({[e.target.name]: e.target.value});
  61. },
  62. _createGame(e) {
  63. e.preventDefault();
  64. const {time, inc} = this.state;
  65. const isInvalid = [time, inc].some(val => {
  66. val = parseInt(val, 10);
  67. return isNaN(val) || val < 0 || val > 50;
  68. });
  69. if (isInvalid) {
  70. // fallback for old browsers
  71. return window.alert('Form is invalid. Enter numbers between 0 and 50.');
  72. } else {
  73. this.props.io.emit('start');
  74. }
  75. }
  76. });
  77. export default Index;