ChangeGameModal.jsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import React from "react";
  2. import { useTranslation } from "react-i18next";
  3. import styled from "styled-components";
  4. import { useQuery } from "react-query";
  5. import Modal from "../../ui/Modal";
  6. import { getGames } from "../../utils/api";
  7. import useSession from "../../hooks/useSession";
  8. import GameListItem from "../GameListItem";
  9. const StyledGameList = styled.ul`
  10. list-style: none;
  11. margin: 0;
  12. padding: 0;
  13. display: flex;
  14. flex-direction: column;
  15. `;
  16. const ChangeGameModalContent = ({ onLoad }) => {
  17. const { t } = useTranslation();
  18. const { changeGame } = useSession();
  19. const { isLoading, data: gameList } = useQuery("games", async () =>
  20. (await getGames())
  21. .filter((game) => game.board.published)
  22. .sort((a, b) => {
  23. const [nameA, nameB] = [
  24. a.board.defaultName || a.board.name,
  25. b.board.defaultName || b.board.name,
  26. ];
  27. if (nameA < nameB || a.id === "demo") {
  28. return -1;
  29. }
  30. if (nameA > nameB || b.id === "demo") {
  31. return 1;
  32. }
  33. return 0;
  34. })
  35. );
  36. const onGameClick = React.useCallback(
  37. (id) => {
  38. changeGame(id);
  39. onLoad();
  40. },
  41. [changeGame, onLoad]
  42. );
  43. return (
  44. <>
  45. <header>
  46. <h3>{t("Choose a new game")}</h3>
  47. </header>
  48. <section>
  49. <StyledGameList>
  50. {!isLoading &&
  51. gameList.map((game) => (
  52. <GameListItem key={game.id} game={game} onClick={onGameClick} />
  53. ))}
  54. </StyledGameList>
  55. </section>
  56. </>
  57. );
  58. };
  59. const ChangeGameModal = ({ show, setShow }) => {
  60. const { t } = useTranslation();
  61. const closeModal = React.useCallback(() => setShow(false), [setShow]);
  62. return (
  63. <Modal
  64. title={t("Change game")}
  65. setShow={setShow}
  66. show={show}
  67. position="left"
  68. >
  69. <ChangeGameModalContent onLoad={closeModal} />
  70. </Modal>
  71. );
  72. };
  73. export default ChangeGameModal;