Index.js 2.4 KB

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