All files / src/components HomePage.jsx

91.37% Statements 53/58
80% Branches 20/25
83.33% Functions 10/12
90.9% Lines 50/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167                  12x 12x 12x 12x 12x 12x 12x 12x 12x   12x   12x 5x 1x 1x   1x 1x 1x 1x       12x 7x 2x 2x           12x 3x 3x           3x 1x 1x     2x   2x               2x   1x 1x       12x 2x 6x       2x     12x 2x 2x       1x 1x   1x   1x 1x       12x             12x                                       2x             2x                             6x                                        
import React, { useContext, useState, useEffect } from 'react';
import Lobby from "./Lobby/Lobby";
import ErrorModal from './Modal/ErrorModal';
import "./HomePage.css";
import { WebSocketContext } from '../WebSocketContext';
import IngredientScrollPicker from "./IngredientScrollPicker/IngredientScrollPicker";
import {playPopSound} from "./SoundEffects/playPopSound";
 
function HomePage() {
    const API_PROTOCOL = window.location.protocol === "https:" ? "https://" : "http://";
    const API_HOST = process.env.REACT_APP_BACKEND_DOMAIN;
    const API_BASE = `${API_PROTOCOL}${API_HOST}`;
    const [lobbyCode, setLobbyCode] = useState(null);
    const [errorMsg, setErrorMsg] = useState(null);
    const [ingredient1, setIngredient1] = useState('Bottom Bun');
    const [ingredient2, setIngredient2] = useState('Bottom Bun');
    const [ingredient3, setIngredient3] = useState('Bottom Bun');
    const { send } = useContext(WebSocketContext);
 
    const [isErrorModalOpen, setIsModalErrorOpen] = useState(false);
 
    useEffect(() => {
        if (window.location.pathname !== "/"){
            const pathname = window.location.pathname.slice(1);
            console.log("Pathname is " + pathname);
 
            const ingredients = decodeURIComponent(pathname).split('-')
            setIngredient1(ingredients[0] ?? 'Bottom Bun');
            setIngredient2(ingredients[1] ?? 'Bottom Bun');
            setIngredient3(ingredients[2] ?? 'Bottom Bun');
        }
    },[])
 
    useEffect(() => {
        if(errorMsg){
            setIsModalErrorOpen(true)
            setTimeout(() => {
                handleHideErrorModal()
            }, 5000);
        }
    }, [errorMsg])
 
    const handleJoin = async (codeArray) => {
        try {
            const response = await fetch(`/api/lobby/join`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ code: codeArray }),
            });
 
            if (!response.ok) {
                const body =  await response.json();
                throw new Error(body.detail);
            }
 
            const { id } = await response.json();
 
            send({
                data: {
                    type: "initializer",
                    code: codeArray,
                    id
                }
            });
 
            setLobbyCode(codeArray.join('-'));
        } catch (err) {
            console.error("Join failed:", err);
            setErrorMsg(err.message);
        }
    };
 
    const joinLobby = () => {
        const codeArray = [ingredient1, ingredient2, ingredient3];
        Iif (codeArray.some(c => !c)) {
            alert("Please select all 3 ingredients.");
            return;
        }
        handleJoin(codeArray);
    };
 
    const createLobby = async () => {
        try {
            const response = await fetch(`/api/lobby`, {
                method: "POST",
            });
 
            const responseJson = await response.json();
            const code = responseJson.code;
 
            await handleJoin(code);
        } catch (err) {
            console.error("Create lobby failed:", err);
            setErrorMsg("Failed to create lobby.");
        }
    };
 
    const handleHideErrorModal = () => {
        setIsModalErrorOpen(false)
        setErrorMsg(null)
    }
 
 
 
    return (
        <div className="homepage-container">
            <div className="lobby-header">
                <h1 className="lobby-title">Order Up!</h1>
                <div className="lobby-subtitle">A Collaborative Cooking Experience</div>
            </div>
            {isErrorModalOpen && <ErrorModal msg={errorMsg} handleClick={handleHideErrorModal} />}
            {!lobbyCode && (
                <>
                    <div className="wheel-picker-row">
                        <IngredientScrollPicker selected={ingredient1} setSelected={setIngredient1} />
                        <IngredientScrollPicker selected={ingredient2} setSelected={setIngredient2} />
                        <IngredientScrollPicker selected={ingredient3} setSelected={setIngredient3} />
                    </div>
 
 
 
                    <div className="homepage-actions">
                        <button
                            className="create-button"
                            onClick={() => {createLobby(); playPopSound()}}
                        >
                            Create Lobby
                        </button>
 
                        <button
                            className="join-button"
                            onClick={() => {joinLobby(); playPopSound()}}
                            disabled={!ingredient1 || !ingredient2 || !ingredient3}
                        >
                            Join Lobby
                        </button>
 
                    </div>
                </>
            )}
 
            {lobbyCode && (
                <>
                    <div className="lobby-code-display">
                        <div className="code-images">
                            {lobbyCode.split('-').map((name, i) => (
                                <img
                                    key={i}
                                    src={`/images/aac_icons/${name.toLowerCase().replace(' ', '_')}.png`}
                                    alt={name}
                                    className="code-image"
                                />
                            ))}
                        </div>
                    </div>
                    <Lobby lobbyCode={lobbyCode} />
                </>
            )}
            <div className="game-description">
                <h3>Cook delicious food with your friends!</h3>
            </div>
        </div>
    );
}
 
export default HomePage;