Index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. <p style={{margin: '50px 0'}} className="center">
  39. A lightweight real-time chess app build in Node, Express,
  40. Socket.IO, React, Flux and Immutable.
  41. </p>
  42. <div id="create-game">
  43. <CreateGameForm
  44. link={this.state.link}
  45. time={this.state.time}
  46. inc={this.state.inc}
  47. onChangeForm={this._onChangeForm}
  48. createGame={this._createGame} />
  49. <p id="game-status">
  50. {this.state.link ?
  51. 'Waiting for opponent to connect'
  52. :this.state.hasExpired ?
  53. 'Game link has expired, generate a new one'
  54. :null}
  55. </p>
  56. </div>
  57. <p>
  58. Click the button to create a game. Send the link to your friend.
  59. Once the link is opened your friend‘s browser, game should begin
  60. shortly. Colors are picked randomly by computer.
  61. </p>
  62. <p>
  63. <a href="/about" className="alpha">Read more about Reti Chess</a>
  64. </p>
  65. </div>
  66. );
  67. },
  68. _onChangeForm(e) {
  69. this.setState({[e.target.name]: e.target.value});
  70. },
  71. _createGame(e) {
  72. e.preventDefault();
  73. const {time, inc} = this.state;
  74. const isInvalid = [time, inc].some(val => {
  75. val = parseInt(val, 10);
  76. return isNaN(val) || val < 0 || val > 50;
  77. });
  78. if (isInvalid) {
  79. // fallback for old browsers
  80. return window.alert('Form is invalid.');
  81. } else {
  82. this.props.io.emit('start');
  83. }
  84. }
  85. });
  86. export default Index;