summaryrefslogtreecommitdiff
path: root/frontend/src/App.tsx
blob: b3203bcb3ab871ff173e9a3d7bc065df39e64e00 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import React, { useEffect, useState } from "react";
import logo from "./kaistevenson_white.svg";
import "./App.css";

import { Grid } from "./Grid";
import { getCategory, getWords } from "./serverHelper";

export type GameState = {
  words: { word: string; selected: boolean; used: boolean }[];
  groups: {
    title: string;
    reason: string;
    words: string[];
    flipped: boolean;
  }[];
};

const loadingGameState: GameState = {
  words: new Array(16).fill({
    word: "Loading...",
    selected: false,
    used: false,
  }),
  groups: [],
};

const initializeGameState = async (): Promise<GameState> => ({
  words: (await getWords()).map((word) => ({
    word,
    selected: false,
    used: false,
  })),
  groups: [],
});

const Game = () => {
  //state
  const [gameState, setGameState] = useState<GameState | undefined>(undefined);

  //initialize
  useEffect(() => {
    if (!gameState) {
      initializeGameState()
        .then((state) => setGameState(state))
        .catch(console.error);
    }
  });

  //handlers
  const selectWordHandler = (idx: number) => {
    const candidateState = { ...gameState! };
    if (candidateState.words.filter((word) => word.selected).length === 4) {
      if (!candidateState.words[idx].selected) {
        //if we've already selected 4 words and we would select another,
        //do nothing
        return;
      }
    }
    //FIXME don't mutate state
    candidateState.words[idx].selected = !candidateState.words[idx].selected;
    setGameState(candidateState);
  };
  const flipGroupHandler = (idx: number) => {
    const candidateState = { ...gameState! };
    //FIXME don't mutate state
    candidateState.groups[idx].flipped = !candidateState.groups[idx].flipped;
    setGameState(candidateState);
  };
  const submitSelectionHandler = () => {
    const candidateState = { ...gameState! };

    const selectedWords = candidateState.words
      .filter(({ selected }) => selected)
      .map(({ word }) => word);

    if (selectedWords.length !== 4) {
      return;
    }

    candidateState.words = candidateState.words.map(
      ({ selected, word, used }) => ({
        used: used || selected,
        selected: false,
        word,
      })
    );

    const loadingGroup: GameState["groups"][number] = {
      title: "LOADING",
      words: selectedWords,
      reason: "LOADING",
      flipped: false,
    };

    setGameState((prevState) => ({
      ...candidateState!,
      groups: [...prevState!.groups, loadingGroup],
    }));

    getCategory(selectedWords).then(({ categoryName, reason }) => {
      setGameState((prevState) => {
        const updatedGroups = prevState!.groups.map((group) =>
          group === loadingGroup
            ? { ...group, title: categoryName, reason }
            : group
        );
        return { ...candidateState!, groups: updatedGroups };
      });
    });
  };

  //display logic
  return (
    <div className="Game-main">
      <Grid
        selectWordHandler={selectWordHandler}
        flipGroupHandler={flipGroupHandler}
        submitSelectionHandler={submitSelectionHandler}
        gameState={gameState ?? loadingGameState}
      />
    </div>
  );
};

export const App = () => (
  <div className="App">
    <div className="App-bg">
      <div className="Logo-container">
        <img src={logo} className="App-logo" alt="logo" />
      </div>
      <div className="App-main">
        <Game />
      </div>
    </div>
  </div>
);