pre-game.component.jsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import React, { useState } from "react";
  2. import Loading from "../loading.component";
  3. import { createGame, joinGame } from "../../services/ggsh.service";
  4. // TODO set round timer for new game
  5. const initialState = playerName => ({
  6. loading: false,
  7. gameId: null,
  8. playerName,
  9. });
  10. const PlayerName = ({ playerName, onChangePlayerName }) => (
  11. <div style={{
  12. display: "flex",
  13. flexFlow: "column nowrap",
  14. justifyContent: "center",
  15. alignItems: "center",
  16. }}>
  17. <span style={{ padding: "0.2em" }}>Player Name</span>
  18. <input style={{ padding: "0.1em" }} type="text" value={playerName} onChange={onChangePlayerName} />
  19. </div>
  20. );
  21. const NewGame = ({ onCreateGame, cannotCreateGame }) => (
  22. <button onClick={onCreateGame} disabled={cannotCreateGame}>
  23. Create New Game
  24. </button>
  25. );
  26. const JoinGame = ({ gameId, onChangeGameId, onJoinGame, cannotJoinGame }) => (
  27. <div style={{
  28. display: "flex",
  29. flexFlow: "column nowrap",
  30. justifyContent: "center",
  31. alignItems: "center",
  32. }}>
  33. <span style={{ padding: "0.1em" }}>Game ID:</span>
  34. <input style={{ margin: "0.1em" }} type="text" value={gameId} onChange={onChangeGameId} />
  35. <button style={{ margin: "0.1em" }} onClick={onJoinGame} disabled={cannotJoinGame}>
  36. Join Existing Game
  37. </button>
  38. </div>
  39. );
  40. const PreGame = ({ initPlayerName, onGameJoined }) => {
  41. const [state, setState] = useState(initialState(initPlayerName));
  42. const { loading, gameId, playerName } = state;
  43. if (loading) {
  44. return <Loading/>
  45. }
  46. const onChangePlayerName = ({ target }) => setState({ ...state, playerName: target.value.trim() });
  47. const onChangeGameId = ({ target }) => setState({ ...state, gameId: target.value.trim() });
  48. const onCreateGame = async () => {
  49. setState({ ...state, loading: true })
  50. const gameId = await createGame(playerName, 300);
  51. onGameJoined({ gameId, playerName });
  52. };
  53. const cannotCreateGame = !playerName || playerName.length === 0;
  54. const onJoinGame = async () => {
  55. // TODO would like to support re-joining a game you left
  56. setState({ ...state, loading: true })
  57. await joinGame(gameId, playerName);
  58. onGameJoined({ gameId, playerName });
  59. };
  60. const cannotJoinGame = cannotCreateGame || !gameId || gameId.length === 0;
  61. return (
  62. <div>
  63. <PlayerName {...{ playerName, onChangePlayerName }} />
  64. <hr/>
  65. <NewGame {...{ onCreateGame, cannotCreateGame }} />
  66. <hr/>
  67. <JoinGame {...{ gameId, onChangeGameId, onJoinGame, cannotJoinGame }} />
  68. </div>
  69. );
  70. }
  71. export default PreGame;