Skip to content

Commit

Permalink
Merge pull request #5 from Web2Bizz/dev-da-b1rmuda
Browse files Browse the repository at this point in the history
refactoring
  • Loading branch information
da-b1rmuda authored Jun 23, 2024
2 parents 1883338 + fe5f88f commit 23d2a23
Show file tree
Hide file tree
Showing 13 changed files with 252 additions and 189 deletions.
3 changes: 2 additions & 1 deletion trapWord-client/.env
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
VITE_API_URL='http://localhost:3000/api'
VITE_API_URL='http://localhost:3000'
VITE_CLIENT_URL='http://localhost:5173'
2 changes: 1 addition & 1 deletion trapWord-client/src/entitys/Room/api/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const roomAPI = createApi({
tagTypes: ['Room'],
reducerPath: 'roomAPI',
baseQuery: fetchBaseQuery({
baseUrl: import.meta.env.VITE_API_URL + '/rooms',
baseUrl: import.meta.env.VITE_API_URL + '/api/rooms',
keepalive: false,
}),
endpoints: builder => ({
Expand Down
68 changes: 36 additions & 32 deletions trapWord-client/src/pages/HomePage/HomePage.jsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,43 @@
import { Button } from "antd";
import { useNavigate } from "react-router-dom";
import { roomAPI } from "../../entitys/Room/api/service.js";
import { Button } from 'antd'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { roomAPI } from '../../entitys/Room/api/service.js'
import { ModalJoin } from '../../widgets/index.js'

const HomePage = () => {
const navigate = useNavigate();
const [createRoom, {}] = roomAPI.useCreateRoomMutation();
const navigate = useNavigate()
const [createRoom, {}] = roomAPI.useCreateRoomMutation()
const [isModalJoin, setIsModalJoin] = useState(false)

const onCreateRoomClick = async () => {
try {
const response = await createRoom();
if (response.error) {
// Обработка ошибки, если она есть
console.error("Ошибка при создании комнаты:", data.roomCode.error);
} else {
// Переходим на страницу лобби с roomCode, если все в порядке
const { roomCode } = response.data;
navigate(`/lobby/${roomCode}`);
}
} catch (error) {
console.error("Ошибка при создании комнаты:", error);
}
};
const onCreateRoomClick = async () => {
try {
const response = await createRoom()
if (response.error) {
console.error('Ошибка при создании комнаты:', data.roomCode.error)
} else {
const { roomCode } = response.data
navigate(`/lobby/${roomCode}`)
}
} catch (error) {
console.error('Ошибка при создании комнаты:', error)
}
}

return (
<div className="flex items-center flex-col gap-5">
<h1 className="mb-20">Опасные слова</h1>
return (
<>
<div className='flex items-center flex-col gap-5'>
<h1 className='mb-20'>Опасные слова</h1>

<Button type="primary" onClick={onCreateRoomClick}>
Создать комнату
</Button>
<Button type="primary">Присоединиться</Button>
<h1>Главный разраб на этой свиноферме⚡</h1>
<img width={300} src="/1.jpg" />
</div>
);
};
<Button type='primary' onClick={onCreateRoomClick}>
Создать комнату
</Button>
<Button type='primary' onClick={() => setIsModalJoin(true)}>
Присоединиться
</Button>
<ModalJoin isModalJoin={isModalJoin} setIsModalJoin={setIsModalJoin} />
</div>
</>
)
}

export default HomePage;
182 changes: 28 additions & 154 deletions trapWord-client/src/pages/LobbyPage/LobbyPage.jsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,32 @@
import { CopyOutlined } from '@ant-design/icons'
import { Avatar, Button, Input, Modal, Space } from 'antd'
import React, { useEffect, useState } from 'react'
import { Outlet, useLocation, useNavigate, useParams } from 'react-router-dom'
import { Outlet, useLocation, useParams } from 'react-router-dom'
import io from 'socket.io-client'
import { roomAPI } from '../../entitys/Room/api/service'

const socket = io('http://localhost:3000')
import {
InviteButton,
ModalRefer,
ParticipantList,
SelectName,
StartGameButton,
AbsentPage,
} from '../../widgets'

const socket = io(import.meta.env.VITE_API_URL)

const LobbyPage = () => {
const { id } = useParams()
const location = useLocation()

const isGamePage = location.pathname.endsWith('game')
const isRoundPage = location.pathname.endsWith('round')

const { data: existRoom } = roomAPI.useCheckRoomExistenceQuery(id)
const { data: participants, refetch } = roomAPI.useGetPlayersInRoomQuery(id)
const [roomExists, setRoomExists] = useState(false)

const [isModalRefer, setIsModalRefer] = useState(false)

const [userName, setUserName] = useState('')
const minPlayers = 4

Expand All @@ -25,13 +39,8 @@ const LobbyPage = () => {

useEffect(() => {
socket.on('playerJoined', data => {
console.log('playerJoined', data)

if (data.roomCode === id) {
refetch()
}
if (data.roomCode === id) refetch()
})

return () => {
socket.off('playerJoined')
}
Expand All @@ -43,20 +52,14 @@ const LobbyPage = () => {
}
if (participants && participants.length >= minPlayers) {
return <StartGameButton roomCode={id} />
} else {
return <InviteButton setIsModalRefer={setIsModalRefer} />
}
return <InviteButton setIsModalRefer={setIsModalRefer} />
}

const location = useLocation()
const isGamePage = location.pathname.endsWith('game')
const isRoundPage = location.pathname.endsWith('round')

return (
<>
{isGamePage || isRoundPage ? (
<Outlet />
) : roomExists ? (
const CheckCurrentPage = () => {
if (isGamePage || isRoundPage) return <Outlet />
if (roomExists) {
return (
<div className='flex justify-between h-screen flex-col p-5 '>
<ParticipantList participants={participants} />
{renderConditions()}
Expand All @@ -66,142 +69,13 @@ const LobbyPage = () => {
setIsModalRefer={setIsModalRefer}
/>
</div>
) : (
<div>Данной игры не существует</div>
)}
</>
)
}

const ParticipantList = ({ participants }) => {
if (!participants || participants.length === 0) {
return (
<div>
<h1>Участники (0)</h1>
</div>
)
}

return (
<div className='flex flex-col'>
<div className='flex justify-center'>
<h1>Участники ({participants.length}) </h1>
</div>
<div className='px-8 mt-10 flex flex-col gap-5 max-h-60 '>
{participants &&
participants.map((participant, index) => (
<div key={index} className='flex items-center'>
<Avatar
src={participant.avatar}
size={48}
alt={`Аватарка ${participant.name}`}
/>
<span className='text-3xl ml-10'>{participant.name}</span>
</div>
))}
</div>
</div>
)
}

const SelectName = ({ setUserName, roomCode }) => {
const [inputValue, setInputValue] = useState('')
const [connectRoom, {}] = roomAPI.useConnectRoomMutation()

const handleSelectName = () => {
const player = {
name: inputValue,
}
console.log(roomCode)
setUserName(inputValue)
const data = {
roomCode,
player,
)
} else {
return <AbsentPage />
}
connectRoom(data)
socket.emit('joinRoom', { roomCode, playerName: inputValue })
}

useEffect(() => {
socket.on('playerJoined', data => {
console.log('recived', data)
})
}, [])

return (
<div className='flex'>
<Input
className='text-2xl'
placeholder='Введите ваше имя...'
onChange={e => setInputValue(e.target.value)}
/>
<Button className='text-2xl' onClick={handleSelectName}>
ОК
</Button>
</div>
)
}

const InviteButton = ({ setIsModalRefer }) => {
const handleReferPeople = () => {
setIsModalRefer(true)
}

return (
<Button className='text-2xl' type='primary' onClick={handleReferPeople}>
Пригласить людей
</Button>
)
}

const StartGameButton = ({ roomCode }) => {
const navigate = useNavigate()

const handleStartGame = () => {
navigate(`/lobby/${roomCode}/game`)
}

return (
<div className=''>
<Button
className='text-3xl w-full'
type='primary'
onClick={handleStartGame}
>
Начать игру
</Button>
</div>
)
}

const ModalRefer = ({ isModalRefer, roomCode, setIsModalRefer }) => {
const roomRef = `http://ip/lobby/${roomCode}`

const handleCancel = () => {
setIsModalRefer(false)
}

return (
<Modal
title='Приглашение людей'
open={isModalRefer}
onCancel={handleCancel}
footer={[]}
>
<p>Код комнаты: {roomCode}</p>
<p>Пригласительная ссылка: </p>
<Space.Compact style={{ width: '100%' }}>
<Input disabled value={roomRef} />
<Button
onClick={() => {
navigator.clipboard.writeText(roomRef)
}}
>
<CopyOutlined />
</Button>
</Space.Compact>
</Modal>
)
return CheckCurrentPage()
}

export default LobbyPage
2 changes: 1 addition & 1 deletion trapWord-client/src/pages/RoundPage/RoundPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ const RoundPage = () => {
return (
<div style={{ height: 'calc(100vh - 80px)' }} className='flex flex-col'>
<GameHeader currentRound={1} />
<ProposeWord />
<ProposeWord word={'Голубь'} />

{/* <GuessPlacementTrap traps={traps} /> */}
<GuessTrapWord />
Expand Down
31 changes: 31 additions & 0 deletions trapWord-client/src/widgets/HomeWidgets/ModalJoin.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Button, Input, Modal } from 'antd'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'

export const ModalJoin = ({ isModalJoin, setIsModalJoin }) => {
const [value, setValue] = useState()
const navigate = useNavigate()

const handleCancel = () => {
setIsModalJoin(false)
}

const handleConnect = () => {
navigate(`/lobby/${value}`)
setIsModalJoin(false)
}

return (
<Modal
title='Введите код комнаты'
open={isModalJoin}
onCancel={handleCancel}
footer={[]}
>
<Input value={value} onChange={e => setValue(e.target.value)} />
<Button className='text-2xl w-full mt-5' onClick={handleConnect}>
Присоединиться
</Button>
</Modal>
)
}
7 changes: 7 additions & 0 deletions trapWord-client/src/widgets/LobbyWidgets/AbsentPage.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const AbsentPage = () => {
return (
<div className='flex justify-center items-center text-2xl'>
<p>Данной игры не существует</p>
</div>
)
}
13 changes: 13 additions & 0 deletions trapWord-client/src/widgets/LobbyWidgets/InviteButton.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Button } from 'antd'

export const InviteButton = ({ setIsModalRefer }) => {
const handleReferPeople = () => {
setIsModalRefer(true)
}

return (
<Button className='text-2xl' type='primary' onClick={handleReferPeople}>
Пригласить людей
</Button>
)
}
Loading

0 comments on commit 23d2a23

Please sign in to comment.