Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: handle player id, name on both frontend and backend #34

Merged
merged 20 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
458e40a
Auth validates handshake, and verify old and new players, added funct…
Dec 30, 2024
a8a63a5
refactor: move types directory to src
Aleks334 Jan 5, 2025
a9a08a5
refactor: move socket constant to separate folder
Aleks334 Jan 5, 2025
d0168a9
refactor: move provider component and context to features/connection
Aleks334 Jan 5, 2025
ba7de54
feat(connection): add methods to connect and disconnect
Aleks334 Jan 6, 2025
7f65616
refactor(ConnectionProvider): extract logic for event handlers into s…
Aleks334 Jan 6, 2025
6bf0b1b
chore: add script in package.json to install new packages in root dir…
Aleks334 Jan 6, 2025
fd5b4d1
refactor: store server url on client in .env
Aleks334 Jan 9, 2025
afe8a53
feat: store sid in localStorage and retrieve it on backend (early stage)
Aleks334 Jan 11, 2025
9bea8a3
refactor: remove unnecessary console logs
Aleks334 Jan 11, 2025
dc58bb0
refactor(RoomManager): generate player id using node:crypto
Aleks334 Jan 11, 2025
5689785
refactor(Room): change removePlayer method name to disconnectPlayer
Aleks334 Jan 11, 2025
b368a22
fix: remove err data from phase_updated in Server2ClientEvents
Aleks334 Jan 11, 2025
ae9dd9a
refactor: organize files in server directory in the appropriate folders
Aleks334 Jan 11, 2025
72f5a36
fix(package.json): use concurrently for instDeps script
Aleks334 Jan 11, 2025
5c18ca3
fix(Character): remove unnecessary code that was used for testing
Aleks334 Jan 11, 2025
8f12cf3
feat: add modal component
Aleks334 Feb 14, 2025
808a164
feat: emit player name to backend
Aleks334 Feb 14, 2025
2981208
refactor: move clsx to client package & minor modal style change
Aleks334 Feb 15, 2025
9111f4e
Merge branch 'main' into feature/F-32-reconnection
Aleks334 Feb 18, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions client/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_SERVER_URL="ws://localhost:5000"
1 change: 1 addition & 0 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion client/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BrowserRouter, Route, Routes } from "react-router";

import ConnectionProvider from "./ConnectionProvider";
import { ConnectionProvider } from "@/features/connection";
import { GameScreen, MenuScreen } from "@/pages";

function App() {
Expand Down
11 changes: 0 additions & 11 deletions client/src/ConnectionProvider/Context.ts

This file was deleted.

32 changes: 0 additions & 32 deletions client/src/ConnectionProvider/index.tsx

This file was deleted.

2 changes: 2 additions & 0 deletions client/src/components/Button/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ function Button({
"focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-black",
customClassName
)}
disabled={disabled}
aria-disabled={disabled}
type="button"
disabled={disabled}
aria-disabled={disabled}
Expand Down
13 changes: 8 additions & 5 deletions client/src/components/Input/index.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { forwardRef, type ComponentPropsWithoutRef } from "react";

import clsx from "clsx";
import React, { forwardRef, type ComponentPropsWithoutRef } from "react";

type InputProps = ComponentPropsWithoutRef<"input">;

const Input = forwardRef<HTMLInputElement, InputProps>(({ ...props }, ref) => (
const Input = forwardRef<HTMLInputElement, InputProps>(({ className, ...props }, ref) => (
<input
{...props}
ref={ref}
className={
"rounded-md border-2 border-black px-2 py-2 text-black focus-visible:outline focus-visible:outline-2 focus-visible:outline-black"
}
className={clsx(
"rounded-md border-2 border-black px-2 py-2 text-black focus-visible:outline focus-visible:outline-2 focus-visible:outline-black",
className
)}
/>
));

Expand Down
61 changes: 61 additions & 0 deletions client/src/components/Modal/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React, { useEffect, useRef } from "react";

interface ModalProps {
onClose?: () => void;
children: React.ReactNode;
showCloseIcon?: boolean;
canBeDismissed?: boolean;
isOpened: boolean;
}

function Modal({ onClose, showCloseIcon = true, canBeDismissed = true, children, isOpened }: ModalProps) {
const dialogRef = useRef<HTMLDialogElement | null>(null);

const handleKeyDown = (e: React.KeyboardEvent<HTMLDialogElement>) => {
if (e.key === "Escape" && !canBeDismissed) e.preventDefault();
};

const handleModalClose = () => {
onClose?.();
dialogRef.current?.close();
};

const handleBackdropClick = (e: React.MouseEvent<HTMLDialogElement>) => {
if (e.target === e.currentTarget && canBeDismissed) {
handleModalClose();
}
};

useEffect(() => {
if (isOpened) {
dialogRef.current?.showModal();
} else {
dialogRef.current?.close();
}
}, [isOpened]);

return (
<dialog
ref={dialogRef}
onKeyDown={handleKeyDown}
onClick={handleBackdropClick}
className="mx-2 max-w-lg rounded-md bg-white backdrop:bg-black/70 backdrop:backdrop-blur-sm sm:mx-auto"
>
<div className="flex flex-col items-center justify-center gap-3 p-8">
{showCloseIcon && (
<button onClick={handleModalClose} className="absolute right-6 top-5 aspect-square w-6">
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M20.7457 3.32851C20.3552 2.93798 19.722 2.93798 19.3315 3.32851L12.0371 10.6229L4.74275 3.32851C4.35223 2.93798 3.71906 2.93798 3.32854 3.32851C2.93801 3.71903 2.93801 4.3522 3.32854 4.74272L10.6229 12.0371L3.32856 19.3314C2.93803 19.722 2.93803 20.3551 3.32856 20.7457C3.71908 21.1362 4.35225 21.1362 4.74277 20.7457L12.0371 13.4513L19.3315 20.7457C19.722 21.1362 20.3552 21.1362 20.7457 20.7457C21.1362 20.3551 21.1362 19.722 20.7457 19.3315L13.4513 12.0371L20.7457 4.74272C21.1362 4.3522 21.1362 3.71903 20.7457 3.32851Z"
fill="#0F0F0F"
/>
</svg>
</button>
)}
{children}
</div>
</dialog>
);
}

export default Modal;
3 changes: 2 additions & 1 deletion client/src/components/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Button from "./Button";
import Input from "./Input";
import Modal from "./Modal";

export { Button, Input };
export { Button, Input, Modal };
5 changes: 5 additions & 0 deletions client/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { socket } from "./socket";

const PLAYER_ID_KEY_NAME = "player_id";

export { socket, PLAYER_ID_KEY_NAME };
6 changes: 6 additions & 0 deletions client/src/constants/socket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { CustomSocket } from "@/types/Socket";
import { io } from "socket.io-client";

export const socket: CustomSocket = io(import.meta.env.VITE_SERVER_URL, {
autoConnect: false,
});
10 changes: 10 additions & 0 deletions client/src/features/connection/ConnectionContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { createContext } from "react";
import type { ConnectionContext } from "@/types/Socket";
import { socket } from "@/constants";
import { connect, disconnect } from "./utils";

export const ConnContext = createContext<ConnectionContext>({
socket,
connect,
disconnect,
});
18 changes: 18 additions & 0 deletions client/src/features/connection/ConnectionProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useMemo } from "react";
import { useParams } from "react-router";
import { ConnContext } from "./ConnectionContext";
import { socket } from "@/constants";
import { connect, disconnect } from "./utils";
import useConnection from "./useConnection";

function ConnectionProvider(props: { children: React.ReactNode }) {
// Get the code from the URL
const { code } = useParams();
useConnection(code);

const contextValue = useMemo(() => ({ socket, connect, disconnect }), []);

return <ConnContext.Provider value={contextValue}>{props.children}</ConnContext.Provider>;
}

export default ConnectionProvider;
4 changes: 4 additions & 0 deletions client/src/features/connection/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import ConnectionProvider from "./ConnectionProvider";
import { ConnContext } from "./ConnectionContext";

export { ConnContext, ConnectionProvider };
26 changes: 26 additions & 0 deletions client/src/features/connection/useConnection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { PLAYER_ID_KEY_NAME, socket } from "@/constants";
import { useEffect } from "react";
import { connect, disconnect } from "./utils";

function useConnection(code: string | undefined) {
useEffect(() => {
if (code === undefined) return;

socket.on("connect", () => console.log("Connected to server"));
socket.on("connect_error", (err) => console.error(err));
socket.on("disconnect", () => console.log("Disconnected from server"));

socket.on("conn_info_data", ({ playerId }) => {
localStorage.setItem(PLAYER_ID_KEY_NAME, playerId);
});

connect(code);

return () => {
disconnect();
//TODO: remove registered listeners
};
}, [code]);
}

export default useConnection;
20 changes: 20 additions & 0 deletions client/src/features/connection/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { PLAYER_ID_KEY_NAME, socket } from "@/constants";

const connect = (roomCode: string) => {
if (socket.connected) return;

const playerId = localStorage.getItem(PLAYER_ID_KEY_NAME);

if (playerId) {
socket.auth = { playerId };
}

socket.io.opts.query = { roomCode };
socket.connect();
};

const disconnect = () => {
socket.disconnect();
};

export { connect, disconnect };
6 changes: 4 additions & 2 deletions client/src/pages/Game/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useContext, useEffect, useState } from "react";
import { ConnContext } from "../../ConnectionProvider/Context";
import { ConnContext } from "@/features/connection";
import { Phases } from "@global/Game";
import Lobby from "@/pages/Lobby";

Expand All @@ -9,7 +9,9 @@ function Game() {
const [phase, setPhase] = useState(Phases.GAME_END);

useEffect(() => {
socket.on("phaseChange", (data: Phases) => setPhase(data));
socket.on("phase_updated", (phase) => {
setPhase(phase);
});
}, [socket]);

// Render certain components based on the game phase
Expand Down
71 changes: 47 additions & 24 deletions client/src/pages/Lobby/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import Character from "./Character";
import Seat from "./Seats";
import Waiting from "./Waiting";
import useKeyDown from "@/hooks/useKeyDown";
import { Button, Input, Modal } from "@/components";
import { socket } from "@/constants";

enum Panels {
Character = "Character",
Expand Down Expand Up @@ -53,35 +55,56 @@ function Lobby() {
});
};

const [playerName, setPlayerName] = useState<string>("");
const [isModalOpened, setIsModalOpened] = useState(true);
const playerNameLength = playerName?.trim().length;

const handleNameConfirmation = () => {
if (playerNameLength > 1) {
socket.emit("send_player_name", playerName);
setIsModalOpened(false);
}
};

return (
<div className="flex h-full max-w-md select-none flex-col border-2">
<div className="flex justify-between p-4">
<h1>MafiAKAI</h1>
<>
<Modal canBeDismissed={false} showCloseIcon={false} isOpened={isModalOpened}>
<h2 className="mt-3 text-2xl font-bold">Enter your name</h2>
<p className="text-center">This will help other players bind your name with your character.</p>
<Input type="text" value={playerName} onChange={(e) => setPlayerName(e.target.value)} className="my-2" />
<Button disabled={!(playerNameLength > 1)} onClick={handleNameConfirmation}>
Confirm
</Button>
</Modal>

<div className="">Options</div>
</div>
<div className="flex h-full max-w-md select-none flex-col border-2">
<div className="flex justify-between p-4">
<h1>MafiAKAI</h1>
<div className="">Options</div>
</div>

<div className="flex border-b-2 border-neutral-800">
{panelsValues.map((panelName, i) => (
<button
className={`w-full rounded-t-2xl py-1 transition-colors ${i === panelId ? "bg-neutral-800 text-white" : ""}`}
onClick={() => setPanel(i)}
key={panelName}
>
{panelName}
</button>
))}
</div>
<div className="flex border-b-2 border-neutral-800">
{panelsValues.map((panelName, i) => (
<button
className={`w-full rounded-t-2xl py-1 transition-colors ${i === panelId ? "bg-neutral-800 text-white" : ""}`}
onClick={() => setPanel(i)}
key={panelName}
>
{panelName}
</button>
))}
</div>

<div className="h-full" ref={swipeRef}>
{panelsValues[panelId] === Panels.Seat && (
<Seat players={players} selectSeat={handleSetPosition} yourSeat={null} />
)}
{panelsValues[panelId] === Panels.Character ? <Character /> : <></>}
{panelsValues[panelId] === Panels.Waiting ? <Waiting playername={players} /> : <></>}
{panelsValues[panelId] === Panels.Character && <Character />}
<div className="h-full" ref={swipeRef}>
{panelsValues[panelId] === Panels.Seat && (
<Seat players={players} selectSeat={handleSetPosition} yourSeat={null} />
)}
{panelsValues[panelId] === Panels.Character ? <Character /> : <></>}
{panelsValues[panelId] === Panels.Waiting ? <Waiting playername={players} /> : <></>}
{panelsValues[panelId] === Panels.Character && <Character />}
</div>
</div>
</div>
</>
);
}

Expand Down
7 changes: 3 additions & 4 deletions client/types/Socket.ts → client/src/types/Socket.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import {
type Client2ServerEvents,
type Server2ClientEvents,
} from "@global/Sockets";
import { type Client2ServerEvents, type Server2ClientEvents } from "@global/Sockets";
import { Socket } from "socket.io-client";

export type CustomSocket = Socket<Server2ClientEvents, Client2ServerEvents>;

export interface ConnectionContext {
socket: CustomSocket;
connect: (roomCode: string) => void;
disconnect: () => void;
}
8 changes: 8 additions & 0 deletions client/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
/// <reference types="vite/client" />

interface ImportMetaEnv {
readonly VITE_SERVER_URL: string;
}

interface ImportMeta {
readonly env: ImportMetaEnv;
}
Loading