diff --git a/containers/react/assets.d.ts b/containers/react/assets.d.ts new file mode 100644 index 00000000..cb5e5ab2 --- /dev/null +++ b/containers/react/assets.d.ts @@ -0,0 +1,2 @@ +declare module '*.jpg'; +declare module 'styled-components' \ No newline at end of file diff --git a/containers/react/interfaces.tsx b/containers/react/interfaces.tsx new file mode 100644 index 00000000..1faa97ec --- /dev/null +++ b/containers/react/interfaces.tsx @@ -0,0 +1,48 @@ +export interface User { + id: number; + otp_enabled: boolean; + otp_verified: boolean; + otp_base32: string; + nickname: string; + username: string; + photo: Buffer; + password: string; + win: number; + loss: number; + rank: number; + status: number; + userId: number; + friendRequest: string[]; + partyInvite: Record[]; + friends: string[]; + blocked: string[]; + } + +export interface Conv { + id: number; + members?: string[]; + name: string + group: boolean + private: boolean + banned?: string[]; + muted?: string[]; + admin?: string[]; + owner?: string; + password?: string; + } + +export interface Message { + id: number; + convId: number; + sender: string; + text: string; + createdAt?: Date; + } + +export interface Matchlog { + id: number; + opponent: string; + myScore: number; + opScore: number; + parent: User; + } \ No newline at end of file diff --git a/containers/react/src/components/Alert/GreenAlert.tsx b/containers/react/src/components/Alert/GreenAlert.tsx index 9193bcd0..11832c45 100644 --- a/containers/react/src/components/Alert/GreenAlert.tsx +++ b/containers/react/src/components/Alert/GreenAlert.tsx @@ -2,6 +2,7 @@ import Backdrop from "../Sidebar/Backdrop.tsx" import { motion } from 'framer-motion' import { AiOutlineCheckCircle } from "react-icons/ai"; import '../../styles/Messages.css' +import React from "react"; const dropIn = { @@ -16,14 +17,19 @@ const dropIn = { }, }; -function GreenAlert ({handleClose, text}){ +interface AlertProps { + handleClose: Function, + text: string + } + +function GreenAlert ({handleClose, text}: AlertProps){ return( - + e.stopPropagation()} className="greenAlert" - variant={dropIn} + // variant={dropIn} initial="hidden" animate="visible" exit="exit" diff --git a/containers/react/src/components/Alert/RedAlert.tsx b/containers/react/src/components/Alert/RedAlert.tsx index 51fae963..9ec3c4bc 100644 --- a/containers/react/src/components/Alert/RedAlert.tsx +++ b/containers/react/src/components/Alert/RedAlert.tsx @@ -2,6 +2,7 @@ import Backdrop from "../Sidebar/Backdrop.tsx" import { motion } from 'framer-motion' import { BiErrorCircle } from "react-icons/bi"; import '../../styles/Messages.css' +import React from "react"; const dropIn = { @@ -16,13 +17,18 @@ const dropIn = { }, }; -function RedAlert ({handleClose, text}) { +interface AlertProps { + handleClose: Function, + text: string + } + +function RedAlert ({handleClose, text}: AlertProps) { return( - + e.stopPropagation()} className="redAlert" - variant={dropIn} + // variant={dropIn} initial="hidden" animate="visible" exit="exit" diff --git a/containers/react/src/components/Alert/YellowAlert.tsx b/containers/react/src/components/Alert/YellowAlert.tsx index 0627e676..1537dd54 100644 --- a/containers/react/src/components/Alert/YellowAlert.tsx +++ b/containers/react/src/components/Alert/YellowAlert.tsx @@ -2,6 +2,7 @@ import Backdrop from "../Sidebar/Backdrop.tsx" import { motion } from 'framer-motion' import { GrTrophy } from "react-icons/gr"; import '../../styles/Messages.css' +import React from "react"; const dropIn = { hidden: { @@ -15,13 +16,18 @@ const dropIn = { }, }; -function YellowAlert ({handleClose, text}) { +interface AlertProps { + handleClose: Function, + text: string + } + +function YellowAlert ({handleClose, text}: AlertProps) { return( - + e.stopPropagation()} className="yellowAlert" - variant={dropIn} + // variant={dropIn} initial="hidden" animate="visible" exit="exit" diff --git a/containers/react/src/components/AnimatedRoute.tsx b/containers/react/src/components/AnimatedRoute.tsx index 5a11edb1..7201aacc 100644 --- a/containers/react/src/components/AnimatedRoute.tsx +++ b/containers/react/src/components/AnimatedRoute.tsx @@ -1,7 +1,7 @@ import React from "react"; import {Routes, Route} from 'react-router-dom'; import Home from "../pages/Home.jsx"; -import PlayButton from "../pages/PlayButton.js"; +import PlayButton from "./Game/PlayButton.tsx"; import Field from "../pages/Field"; import Login42 from "../pages/Login42.js"; import Messages from "../pages/Messages.jsx"; @@ -13,11 +13,11 @@ function AnimatedRoute () { return ( - }/> + }/> }/> - }/> - }/> - }/> + }/> + }/> + }/> ) diff --git a/containers/react/src/components/Game/PlayButton.tsx b/containers/react/src/components/Game/PlayButton.tsx index 04576ec7..7e018a04 100644 --- a/containers/react/src/components/Game/PlayButton.tsx +++ b/containers/react/src/components/Game/PlayButton.tsx @@ -1,3 +1,4 @@ +import React from 'react'; import '../../styles/field.css'; // import { useHistory } from 'react-router-dom'; import { useNavigate } from "react-router-dom"; @@ -13,18 +14,18 @@ function PlayButton() { const handleButtonClick = () => { let path = `play?`; - const superpowerCheckbox = document.querySelector('input[value="superpower"]'); - if (superpowerCheckbox.checked) { + const superpowerCheckbox = document.querySelector('input[value="superpower"]'); + if (superpowerCheckbox && superpowerCheckbox.checked) { path += 'superpower=true&'; } - const obstacleCheckbox = document.querySelector('input[value="obstacle"]'); - if (obstacleCheckbox.checked) { + const obstacleCheckbox = document.querySelector('input[value="obstacle"]'); + if (obstacleCheckbox && obstacleCheckbox.checked) { path += 'obstacle=true&'; } - const speedCheckbox = document.querySelector('input[value="speed"]'); - if (speedCheckbox.checked) { + const speedCheckbox = document.querySelector('input[value="speed"]'); + if (speedCheckbox && speedCheckbox.checked) { path += 'speed=true&'; } diff --git a/containers/react/src/components/Game/Rank.tsx b/containers/react/src/components/Game/Rank.tsx index b65e297d..4523c988 100644 --- a/containers/react/src/components/Game/Rank.tsx +++ b/containers/react/src/components/Game/Rank.tsx @@ -6,7 +6,7 @@ /* By: apommier +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/06/09 08:49:24 by apommier #+# #+# */ -/* Updated: 2023/06/19 20:35:39 by apommier ### ########.fr */ +/* Updated: 2023/06/20 13:06:35 by apommier ### ########.fr */ /* */ /* ************************************************************************** */ @@ -15,8 +15,15 @@ import React, { useState, useEffect, useRef } from "react"; // import {Rank} from '../../DataBase/DataRank.js' import DefaultPicture from '../../assets/profile.jpg' import api from '../../script/axiosApi.tsx'; +import {Matchlog, User} from "../../../interfaces.tsx" +// import { Match } from "@testing-library/react"; -function Rank({user, index}){ +interface RankProps { + user: User + index: number +} + +function Rank({user, index}: RankProps){ const [profilePicture, setProfilePicture] = useState(''); @@ -51,7 +58,7 @@ function Rank({user, index}){ {/* */} -

{user.opponent}

+ {/*

{user.opponent}

*/} ) } diff --git a/containers/react/src/components/Game/Ranking.tsx b/containers/react/src/components/Game/Ranking.tsx index aa564f08..1880abcc 100644 --- a/containers/react/src/components/Game/Ranking.tsx +++ b/containers/react/src/components/Game/Ranking.tsx @@ -3,11 +3,12 @@ import React, { useState, useEffect, useRef } from "react"; import Rank from './Rank.tsx' import defaultpic from '../../assets/profile.jpg' import api from '../../script/axiosApi.tsx'; +import {User} from "../../../interfaces.tsx" function Ranking(){ const [isLoading, setIsLoading] = useState(true); - const [ranking, setRanking] = useState([]); + const [ranking, setRanking] = useState([]); useEffect(()=> { diff --git a/containers/react/src/components/Header.tsx b/containers/react/src/components/Header.tsx index 799d1abf..05ab38db 100644 --- a/containers/react/src/components/Header.tsx +++ b/containers/react/src/components/Header.tsx @@ -62,7 +62,7 @@ function Header() { null}> - {modalOpen && } + {modalOpen && } ); diff --git a/containers/react/src/components/Messages/Chats.tsx b/containers/react/src/components/Messages/Chats.tsx index 9f5015c2..0ada4409 100644 --- a/containers/react/src/components/Messages/Chats.tsx +++ b/containers/react/src/components/Messages/Chats.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect, useRef } from "react"; -import io from 'socket.io-client'; +import io, { Socket } from 'socket.io-client'; import '../../styles/Messages.css' import styled from "styled-components"; import DefaultPic from '../../assets/profile.jpg' @@ -18,13 +18,15 @@ import { MdOutlineGroupAdd } from 'react-icons/md'; import { GrAdd } from 'react-icons/gr'; import { RiListSettingsLine } from 'react-icons/ri' -import { Rank } from "../../DataBase/DataRank"; +// import { Rank } from "../../DataBase/DataRank"; import GreenAlert from "../Alert/GreenAlert.tsx"; import RedAlert from "../Alert/RedAlert.tsx"; import YellowAlert from "../Alert/YellowAlert"; import ModalSetting from "./ModalSetting.tsx"; import PartyInvite from "./PartyInvite.tsx"; +// import {User, Conv, Message} from "../../../interfaces.tsx" +import {User, Conv} from "../../../interfaces.tsx" const TouchDiv = styled.div` margin-left: 10px; @@ -72,25 +74,32 @@ const SideP = styled.p` //======================================================================================================== //======================================================================================================== +interface MessageProps { + id: number; + convId: number; + sender: string; + text: string; + createdAt?: Date; + } function Chats(){ - const [isLoading, setIsLoading] = useState(true); + const [isLoading, setIsLoading] = useState(true); const [conversations, setConversation] = useState([]); const [partyInvite, setPartyInvite] = useState([]); - const [user, setUser] = useState(null); - const [currentChat, setCurrentChat] = useState(false); // false is good? - const [isAdmin, setIsAdmin] = useState(false); // false is good? + const [user, setUser] = useState(); + const [currentChat, setCurrentChat] = useState(); // false is good? + const [isAdmin, setIsAdmin] = useState(false); // false is good? // const [currentChat, setCurrentChat] = useState(false); // false is good? - const [messages, setMessage] = useState([]); + const [messages, setMessage] = useState([]); const [newMessages, setNewMessage] = useState(""); - const [incomingMessage, setIncomingMessage] = useState(""); + const [incomingMessage, setIncomingMessage] = useState(); - let socket; - socket = useRef(); + // let socket: Socket; + const socket = useRef(null); + // socket = useRef( useRef(null)); - useEffect(()=> { const getConv = async ()=>{ @@ -144,7 +153,7 @@ function Chats(){ } } // console.log(`result1 = ${currentChat.id !== incomingMessage.convId}`) - if (currentChat !== null && currentChat.id === incomingMessage.convId) + if (currentChat && incomingMessage && currentChat.id === incomingMessage.convId) { console.log("incoming meaasge=",incomingMessage) // if (user && !user.blocked.find(incomingMessage.sender)) @@ -160,8 +169,10 @@ function Chats(){ useEffect(()=> { const getMessage = async ()=> { + if (!currentChat) + return ; const data = {convId: currentChat.id}; - + try { const res = await api.post('/getMessage', data); setMessage(res.data); @@ -172,15 +183,19 @@ function Chats(){ getMessage(); }, [currentChat]); - const handleSubmit = async (e)=>{ + const handleSubmit = async (e: { preventDefault: () => void; })=>{ e.preventDefault(); // console.log(`e= ${e.key}`) // console.log(`name= ${user.username}`) + // let message; + if (!user || !currentChat) + return ; const message = { sender: user.username, text: newMessages, convId: currentChat.id, - members: null + members: null, + id: null, }; try{ const res = await api.post('/message', message); @@ -189,23 +204,27 @@ function Chats(){ message.id = res.data.id setMessage([...messages, res.data]); setNewMessage(""); - socket.current.emit('sendMessage', message); + if (socket.current) + socket.current.emit('sendMessage', message); } catch(err){ console.log(err) } } - const handleKeyPress = async (e)=>{ + const handleKeyPress = async (e: { key: string; })=> { // console.log(`e in press= ${e.key}`) if (e.key !== "Enter") return ; // console.log(`name= ${user.username}`) + if (!user || !currentChat) + return ; const message = { sender: user.username, text: newMessages, convId: currentChat.id, - members: null + members: null, + id: null, }; try{ const res = await api.post('/message', message); @@ -214,7 +233,8 @@ function Chats(){ message.id = res.data.id setMessage([...messages, res.data]); setNewMessage(""); - socket.current.emit('sendMessage', message); + if (socket.current) + socket.current.emit('sendMessage', message); } catch(err){ console.log(err) @@ -263,7 +283,7 @@ function Chats(){ // const closeBlock = () => setBlock(false); - const handleFriend = (event) => { + const handleFriend = (event: { target: { value: React.SetStateAction; }; }) => { setFriend(event.target.value); }; @@ -328,7 +348,7 @@ function Chats(){
profile - {isLoading ? ( + {isLoading || !user ? (

Loading...

) : (

{user.nickname}

@@ -417,7 +437,7 @@ function Chats(){ initial={false} onExitComplete={() => null} > - {setting && } + {setting && } @@ -458,7 +478,7 @@ function Chats(){ ))} - {conversations.map((c, index ) => { + {conversations.map((c: Conv, index ) => { return (
setCurrentChat(c)}> @@ -466,7 +486,7 @@ function Chats(){ User
{c.name} - Desc? + {/* Desc? */}
@@ -475,12 +495,12 @@ function Chats(){
{ - currentChat ? ( + currentChat && user ? ( <>
{messages.map(m=>( - + ))}
{/* */} diff --git a/containers/react/src/components/Messages/GameModal.tsx b/containers/react/src/components/Messages/GameModal.tsx index f05f2ffd..f1004eb3 100644 --- a/containers/react/src/components/Messages/GameModal.tsx +++ b/containers/react/src/components/Messages/GameModal.tsx @@ -2,10 +2,9 @@ import { motion } from "framer-motion"; import Backdrop from "../Sidebar/Backdrop.tsx"; import '../../styles/Messages.css'; import { useState, useEffect } from "react"; -import { GrAdd } from "react-icons/gr"; -import { Link } from "react-router-dom"; import api from "../../script/axiosApi.tsx"; import React from "react"; +import {User} from "../../../interfaces.tsx" // import { useNavigate } from "react-router-dom"; const dropIn = { @@ -23,10 +22,15 @@ const dropIn = { exit: { y: "100vh", opacity: 0 }, }; -const GameModal = ({ handleClose }) => { +interface ModalGame { + handleClose: Function, + // convId: string +} + +const GameModal = ({ handleClose }: ModalGame) => { const [users, setUsers] = useState([]); const [selectedUser, setSelectedUser] = useState(''); - const [convs, setConvs] = useState([]); +// const [convs, setConvs] = useState([]); const [channel, setChannel] = useState(''); // const history = useNavigate(); @@ -35,9 +39,9 @@ const GameModal = ({ handleClose }) => { const fetchData = async () => { try { const tmpUsers = await api.get("/users"); - const tmpConvs = await api.get("/convs"); + // const tmpConvs = await api.get("/convs"); setUsers(tmpUsers.data); - setConvs(tmpConvs.data); + // setConvs(tmpConvs.data); } catch (err) { console.log(err); } @@ -45,7 +49,7 @@ const GameModal = ({ handleClose }) => { fetchData(); }, []); - const handleUserChange = (event) => { + const handleUserChange = (event: { target: { value: React.SetStateAction; }; }) => { setSelectedUser(event.target.value); }; @@ -66,18 +70,19 @@ const GameModal = ({ handleClose }) => { // let path = `play?`; let path = `http://` + process.env.REACT_APP_BASE_URL + `/pong/play?`; - const superpowerCheckbox = document.querySelector('input[value="superpower"]'); - if (superpowerCheckbox.checked) { + + const superpowerCheckbox = document.querySelector('input[value="superpower"]'); + if (superpowerCheckbox && superpowerCheckbox.checked) { path += 'superpower=true&'; } - const obstacleCheckbox = document.querySelector('input[value="obstacle"]'); - if (obstacleCheckbox.checked) { + const obstacleCheckbox = document.querySelector('input[value="obstacle"]'); + if (obstacleCheckbox && obstacleCheckbox.checked) { path += 'obstacle=true&'; } - const speedCheckbox = document.querySelector('input[value="speed"]'); - if (speedCheckbox.checked) { + const speedCheckbox = document.querySelector('input[value="speed"]'); + if (speedCheckbox && speedCheckbox.checked) { path += 'speed=true&'; } @@ -91,18 +96,18 @@ const GameModal = ({ handleClose }) => { // console.log("path= ", path) // history(path, { replace: true }); // window.location.replace(path); - window.history.pushState({}, null, path); - window.location.reload(false); + window.history.pushState({}, '', path); + window.location.reload(); // history(path); }; return ( - + e.stopPropagation()} className="modal" - variant={dropIn} + // variant={dropIn} initial="hidden" animate="visible" exit="exit" @@ -110,7 +115,7 @@ const GameModal = ({ handleClose }) => {
Faster and Faster

- + {/* */}
{/*
diff --git a/containers/react/src/components/Messages/Input.tsx b/containers/react/src/components/Messages/Input.tsx index 15a49b21..868c1abe 100644 --- a/containers/react/src/components/Messages/Input.tsx +++ b/containers/react/src/components/Messages/Input.tsx @@ -1,3 +1,4 @@ +import React from 'react'; import { TbSend } from 'react-icons/tb'; diff --git a/containers/react/src/components/Messages/Message.tsx b/containers/react/src/components/Messages/Message.tsx index fb1f6b3c..d04e250b 100644 --- a/containers/react/src/components/Messages/Message.tsx +++ b/containers/react/src/components/Messages/Message.tsx @@ -6,7 +6,7 @@ /* By: apommier +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/06/01 18:24:46 by apommier #+# #+# */ -/* Updated: 2023/06/19 11:45:54 by apommier ### ########.fr */ +/* Updated: 2023/06/20 12:47:33 by apommier ### ########.fr */ /* */ /* ************************************************************************** */ @@ -17,6 +17,7 @@ import DefaultPicture from '../../assets/profile.jpg' // import { useRef } from "react"; // import { useEffect } from "react"; import '../../styles/Messages.css' +import {User, Conv, Message} from "../../../interfaces.tsx" import React from "react"; const MeStyleP = styled.p` @@ -27,14 +28,19 @@ const MeStyleP = styled.p` margin-right: 20px; ` -function MessageMe({message, own}){ +interface MessageMeProps { + message: Message; + own: boolean; + } + +function MessageMe({message, own}: MessageMeProps){ const [profilePicture, setProfilePicture] = useState(''); - const [sender, setSender] = useState(); - const [conv, setConv] = useState(); + const [sender, setSender] = useState(); + const [conv, setConv] = useState(); - const [user, setUser] = useState(); - const scrollRef = useRef(); + const [user, setUser] = useState(); + const scrollRef = useRef(null); useEffect(() => { if (scrollRef.current) @@ -64,23 +70,23 @@ function MessageMe({message, own}){ const handleButtonClick = () => { if (!sender) - return; + return ; let path = `http://` + process.env.REACT_APP_BASE_URL + `/profile/${sender.username}`; // console.log("path= ", path) // history(path, { replace: true }); // window.location.replace(path); - window.history.pushState({}, null, path); - window.location.reload(false); + window.history.pushState({}, '', path); + window.location.reload(); }; if (!user || !sender || !conv) - return ; + return (<>); // console.log("result includes=", conv.banned.includes(user.username)) // console.log("result includes=", conv.blocked.includes(user.username)) if (user.blocked && user.blocked.includes(message.sender)) - return ; + return (<>); else if (conv.banned && conv.banned.includes(user.username)) - return ; + return (<>); // if (user.blocked.includes(message.sender))/ return ( diff --git a/containers/react/src/components/Messages/MessageMe.tsx b/containers/react/src/components/Messages/MessageMe.tsx index a1cc13b3..82baac78 100644 --- a/containers/react/src/components/Messages/MessageMe.tsx +++ b/containers/react/src/components/Messages/MessageMe.tsx @@ -14,7 +14,8 @@ const MeStyleP = styled.p` ` function MessageMe(){ - const scrollRef = useRef(); + // const scrollRef = useRef(); + const scrollRef = useRef(null); useEffect(() => { scrollRef.current?.scrollIntoView({ behavior: "smooth"}) diff --git a/containers/react/src/components/Messages/MessageYou.tsx b/containers/react/src/components/Messages/MessageYou.tsx index b3dad724..798002a1 100644 --- a/containers/react/src/components/Messages/MessageYou.tsx +++ b/containers/react/src/components/Messages/MessageYou.tsx @@ -14,7 +14,7 @@ const StyleP = styled.p` ` function MessageYou(){ - const scrollRef = useRef(); + const scrollRef = useRef(null); useEffect(() => { scrollRef.current?.scrollIntoView({ behavior: "smooth"}) diff --git a/containers/react/src/components/Messages/Modal.tsx b/containers/react/src/components/Messages/Modal.tsx index aceb20a9..a6546944 100644 --- a/containers/react/src/components/Messages/Modal.tsx +++ b/containers/react/src/components/Messages/Modal.tsx @@ -90,7 +90,7 @@ const Modal = ({handleClose}) => { // test await api.post("/conv", data); handleClose(); - window.location.reload(false); + window.location.reload(); } catch(err) { console.log(err); } diff --git a/containers/react/src/components/Messages/ModalSetting.tsx b/containers/react/src/components/Messages/ModalSetting.tsx index 1e73932e..d0137544 100644 --- a/containers/react/src/components/Messages/ModalSetting.tsx +++ b/containers/react/src/components/Messages/ModalSetting.tsx @@ -1,12 +1,13 @@ import { motion } from "framer-motion"; import Backdrop from "../Sidebar/Backdrop.tsx"; -import { Rank } from "../../DataBase/DataRank" +// import { Rank } from "../../DataBase/DataRank" import '../../styles/Messages.css' import { useState, useEffect } from "react"; import { GrAdd } from "react-icons/gr"; import { Link } from "react-router-dom"; import api from "../../script/axiosApi.tsx"; import React from "react"; +import {User} from "../../../interfaces.tsx" const dropIn = { @@ -25,11 +26,16 @@ const dropIn = { }; -const ModalSetting = ({handleClose, convId}) => { +interface ModalSettingProps { + handleClose: Function, + convId: string +} + +const ModalSetting = ({handleClose, convId}: ModalSettingProps) => { const [password, setPassword] = useState(false); - const [users, setUsers] = useState([]); + const [users, setUsers] = useState([]); const [selectTags, setSelectTag] = useState([{ id: 1, selectedOption: ''}]); - const [selectedUser, setSelectedUser] = useState([]); + const [selectedUser, setSelectedUser] = useState(""); const [newName, setNewName] = useState(""); const [newPassword, setNewPassword] = useState(""); @@ -52,7 +58,7 @@ const ModalSetting = ({handleClose, convId}) => { // const [selectedOptionArray, setSelectedOptionArray] = useState([]); - const handleOptionChange = (selectId, selectedOption) => { + const handleOptionChange = (selectId: number, selectedOption: string) => { console.log("tag= ", selectTags) console.log("option= ", selectedOption) setSelectTag((prevTags) => @@ -63,12 +69,12 @@ const ModalSetting = ({handleClose, convId}) => { setSelectedUser(selectedOption) }; - const handleCheckPass = (e) => { + const handleCheckPass = (e: { target: { checked: boolean | ((prevState: boolean) => boolean); }; }) => { setPassword(e.target.checked); console.log("password??", e.target.checked) } - const handleCheckPriv = (e) => { + const handleCheckPriv = (e: { target: { checked: any; }; }) => { // setPassword(e.target.checked); if (e.target.checked) { @@ -90,7 +96,7 @@ const ModalSetting = ({handleClose, convId}) => { } } - const handleName = async (e)=>{ + const handleName = async (e: { key: string; })=>{ if (e.key !== "Enter") return ; try{ @@ -101,7 +107,7 @@ const ModalSetting = ({handleClose, convId}) => { handleClose(); } - const handlePassword = async (e)=>{ + const handlePassword = async (e: { key: string; })=>{ if (e.key !== "Enter") return ; try{ @@ -157,11 +163,10 @@ const ModalSetting = ({handleClose, convId}) => { }; return ( - + e.stopPropagation()} className="modalSetting" - variant={dropIn} initial="hidden" animate="visible" exit="exit" diff --git a/containers/react/src/components/Messages/PartyInvite.tsx b/containers/react/src/components/Messages/PartyInvite.tsx index e73bab4e..6bb8509d 100644 --- a/containers/react/src/components/Messages/PartyInvite.tsx +++ b/containers/react/src/components/Messages/PartyInvite.tsx @@ -6,7 +6,7 @@ /* By: apommier +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/06/19 16:44:29 by apommier #+# #+# */ -/* Updated: 2023/06/19 17:26:22 by apommier ### ########.fr */ +/* Updated: 2023/06/20 03:47:52 by apommier ### ########.fr */ /* */ /* ************************************************************************** */ @@ -16,6 +16,7 @@ import api from '../../script/axiosApi.tsx'; import DefaultPicture from '../../assets/profile.jpg' import styled from "styled-components"; +import {User} from "../../../interfaces.tsx" import { RxCheckCircled, RxCircleBackslash } from "react-icons/rx"; import React from "react"; @@ -38,10 +39,19 @@ const SideP = styled.p` margin-left: 15px; ` -export default function PartyInvite({currentInvite}) +interface InviteProps { + username: string, + gameId: string + } + +interface UserProps { + currentInvite: {username: string, gameId: string} + } + +export default function PartyInvite({currentInvite}: UserProps) { const [profilePicture, setProfilePicture] = useState(''); - const [request, setRequest] = useState(''); //user who invite + const [request, setRequest] = useState(); //user who invite const [clickEvent, setClickEvent] = useState(false); // const [user, setUser] = useState(null); @@ -65,18 +75,18 @@ export default function PartyInvite({currentInvite}) fetchProfilePicture(); }, [clickEvent]) - const handleButtonClick = (user) => { + const handleButtonClick = (user: InviteProps) => { let path = `http://` + process.env.REACT_APP_BASE_URL + `/profile/${user.username}`; // history(path, { replace: true }); // window.location.replace(path); - window.history.pushState({}, null, path); - window.location.reload(false); + window.history.pushState({}, '', path); + window.location.reload(); }; - const Accept = async (request) => { + const Accept = async (request: User) => { try{ //call canvas ?? // await api.post("/friend", {username: request.username}) @@ -85,8 +95,8 @@ export default function PartyInvite({currentInvite}) path += 'username=' + request.username; path += '&gameId=' + currentInvite.gameId; // setClickEvent(true); - window.history.pushState({}, null, path); - window.location.reload(false); + window.history.pushState({}, '', path); + window.location.reload(); } catch(err) { console.log(err); } @@ -94,7 +104,7 @@ export default function PartyInvite({currentInvite}) console.log(`request = ${request}`) } - const Refuse = async (request) => { + const Refuse = async (request: User) => { try{ await api.post("/deleteInvite", {username: request.username}) // await api.post("/refuseInvite", {username: request.username}) @@ -118,12 +128,13 @@ export default function PartyInvite({currentInvite}) ) : ( Default Profile Picture )} + {request ? (
handleButtonClick(currentInvite)}>{request.nickname} Accept(request)} color={'green'}/> Refuse(request)} color={'red'}/> -
+ ) : ( "" )} ) } \ No newline at end of file diff --git a/containers/react/src/components/Profile/EditName.tsx b/containers/react/src/components/Profile/EditName.tsx index 6b232b9c..35123169 100644 --- a/containers/react/src/components/Profile/EditName.tsx +++ b/containers/react/src/components/Profile/EditName.tsx @@ -52,7 +52,7 @@ const ModalEdit = ( handleClose ) => { console.log("nickname=" ,nickname) try{ await api.post("/nickname", {nickname: nickname}) - window.location.reload(false); + window.location.reload(); // setUser(tmpUser.data); // setIsLoading(false) } diff --git a/containers/react/src/components/Profile/Logout.tsx b/containers/react/src/components/Profile/Logout.tsx index 029078d5..81da718b 100644 --- a/containers/react/src/components/Profile/Logout.tsx +++ b/containers/react/src/components/Profile/Logout.tsx @@ -1,3 +1,4 @@ +import React from "react"; @@ -8,8 +9,9 @@ function Logout(){ // history(path, { replace: true }); // window.location.replace(path); // window.history.pushState({}, '', path); - window.history.pushState({}, null, path); - window.location.reload(false); + window.history.pushState({}, '', path); + window.location.reload(); + return (<>) } export default Logout; \ No newline at end of file diff --git a/containers/react/src/components/Profile/Win_Loss.tsx b/containers/react/src/components/Profile/Win_Loss.tsx index 26314607..99c0a969 100644 --- a/containers/react/src/components/Profile/Win_Loss.tsx +++ b/containers/react/src/components/Profile/Win_Loss.tsx @@ -4,6 +4,7 @@ // import '../DataBase/DataProfileUser.js' // import { DBWinLoss } from '../../DataBase/DummyDBWinLoss.js'; import '../../styles/Win_Loss.css' +import { User, Matchlog } from "../../../interfaces.tsx" // import { UserProfile } from '../../DataBase/DataUserProfile'; // import color from '../../utils/style/color.js'; @@ -51,7 +52,7 @@ import api from '../../script/axiosApi.tsx'; function WinLoss() { - const [user, setUser] = useState(null); + const [user, setUser] = useState(); const [history, setHistory] = useState([]); const [isLoading, setIsLoading] = useState(true); @@ -88,13 +89,13 @@ function WinLoss() {
- {isLoading ? ( + {isLoading || !history || !user ? (

Loading...

// Loading... ) : (

Match history Win/Loss

- {history.map((c, index) => { + {history.map((c: Matchlog, index) => { return (
  • diff --git a/containers/react/src/components/Sidebar/Backdrop.tsx b/containers/react/src/components/Sidebar/Backdrop.tsx index b0280956..b19352e0 100644 --- a/containers/react/src/components/Sidebar/Backdrop.tsx +++ b/containers/react/src/components/Sidebar/Backdrop.tsx @@ -1,7 +1,13 @@ +import React, { MouseEventHandler, ReactNode, HTMLAttributes } from "react"; import { motion } from "framer-motion" import "../../styles/Header.css" -const Backdrop = ({ children, onClick }) => { +interface backProps { + children: ReactNode, + onClick: any +} + +const Backdrop = ({ children, onClick }: backProps) => { return ( { +interface CloseProps { + handleclose: Function; + } + +const Modal = ({ handleclose }: CloseProps) => { return ( +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/06/09 08:18:58 by apommier #+# #+# */ -/* Updated: 2023/06/18 13:12:26 by apommier ### ########.fr */ +/* Updated: 2023/06/20 13:41:44 by apommier ### ########.fr */ /* */ /* ************************************************************************** */ @@ -18,6 +18,7 @@ import styled from "styled-components"; import { RxCircle } from "react-icons/rx"; import { CgFontSpacing } from "react-icons/cg"; import React from "react"; +import {User} from "../../../interfaces.tsx" const UserChat = styled.div ` padding: 5px; @@ -37,8 +38,12 @@ const SideP = styled.p` color: lightgray; margin-left: 15px; ` +interface UserProps { + currentUser: User + } -export default function Friend({currentUser}) +// export default function Friend({currentUser}) +export default function Friend({currentUser}: UserProps) { const [profilePicture, setProfilePicture] = useState(''); @@ -58,7 +63,7 @@ export default function Friend({currentUser}) fetchProfilePicture(); }) - function getStatus(friend) + function getStatus(friend: User) { let status = friend.status console.log(`status= ${status}`) @@ -73,19 +78,19 @@ export default function Friend({currentUser}) return statusColor; } - const handleSpectate = (user) => { + const handleSpectate = (user: User) => { //socket connection and add to party with one with username console.log(`spectate hehe`) console.log(`user= ${user}`) }; - const handleButtonClick = (user) => { + const handleButtonClick = (user: User) => { let path = `http://` + process.env.REACT_APP_BASE_URL + `/profile/${user.username}`; console.log("path= ", path) // history(path, { replace: true }); // window.location.replace(path); - window.history.pushState({}, null, path); - window.location.reload(false); + window.history.pushState({}, '', path); + window.location.reload(); }; return ( @@ -97,7 +102,7 @@ export default function Friend({currentUser}) )}
    handleButtonClick(currentUser)}>{currentUser.nickname} - + {getStatus(currentUser) !== 'blue' ? ( <> diff --git a/containers/react/src/components/Social/FriendRequest.tsx b/containers/react/src/components/Social/FriendRequest.tsx index cf9af1da..7e0eb62c 100644 --- a/containers/react/src/components/Social/FriendRequest.tsx +++ b/containers/react/src/components/Social/FriendRequest.tsx @@ -6,6 +6,7 @@ import styled from "styled-components"; import { RxCheckCircled, RxCircleBackslash } from "react-icons/rx"; import React from "react"; +import {User} from "../../../interfaces.tsx" const UserChat = styled.div ` padding: 5px; @@ -26,10 +27,14 @@ const SideP = styled.p` margin-left: 15px; ` -export default function Friend({currentUser}) +interface UserProps { + currentUser: User + } + +export default function Friend({currentUser}: UserProps) { const [profilePicture, setProfilePicture] = useState(''); - const [request, setRequest] = useState(''); //user who invite + const [request, setRequest] = useState(); //user who invite const [clickEvent, setClickEvent] = useState(false); // const [user, setUser] = useState(null); @@ -53,15 +58,15 @@ export default function Friend({currentUser}) fetchProfilePicture(); }, [clickEvent]) - const handleButtonClick = (user) => { + const handleButtonClick = (user: User) => { let path = `http://` + process.env.REACT_APP_BASE_URL + `/profile/${user.username}`; // history(path, { replace: true }); // window.location.replace(path); - window.history.pushState({}, null, path); - window.location.reload(false); + window.history.pushState({}, '', path); + window.location.reload(); }; - const Accept = async (request) => { + const Accept = async (request: User) => { try{ await api.post("/friend", {username: request.username}) setClickEvent(true); @@ -72,7 +77,7 @@ export default function Friend({currentUser}) console.log(`request = ${request}`) } - const Refuse = async (request) => { + const Refuse = async (request: User) => { try{ await api.post("/refuseInvite", {username: request.username}) setClickEvent(true); @@ -95,12 +100,13 @@ export default function Friend({currentUser}) ) : ( Default Profile Picture )} + {request ? (
    handleButtonClick(currentUser)}>{currentUser.nickname} Accept(request)} color={'green'}/> Refuse(request)} color={'red'}/> -
    + ) : ( "" )} ) } diff --git a/containers/react/src/components/Social/Social.tsx b/containers/react/src/components/Social/Social.tsx index f6aefd5e..40d6e4dc 100644 --- a/containers/react/src/components/Social/Social.tsx +++ b/containers/react/src/components/Social/Social.tsx @@ -9,6 +9,7 @@ import FriendRequest from './FriendRequest.tsx'; import { ImBlocked } from 'react-icons/im'; import { MdOutlineGroupAdd } from 'react-icons/md'; +import {User} from "../../../interfaces.tsx" // import React from "react"; @@ -34,12 +35,11 @@ function Social (){ const [friends, setFriends] = useState([]); const [invite, setInvite] = useState([]); - const [isLoading, setIsLoading] = useState(true); - const [user, setUser] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [user, setUser] = useState(); const [profilePicture, setProfilePicture] = useState(''); useEffect(()=> { - const getFriend = async ()=>{ try{ const tmpFriends = await api.get("/friends") @@ -94,7 +94,7 @@ function Social (){ Default Profile Picture )} - {isLoading ? ( + {isLoading || !user ? (

    Loading...

    ) : (

    {user.nickname}

    diff --git a/containers/react/src/pages/Field.tsx b/containers/react/src/pages/Field.tsx index 86de3807..1e2090d4 100644 --- a/containers/react/src/pages/Field.tsx +++ b/containers/react/src/pages/Field.tsx @@ -1,4 +1,4 @@ -import { useEffect, useLocation } from 'react'; +import { useEffect } from 'react'; // import { useState, useRef } from 'react'; import DrawCanvas from './canvas.tsx'; import queryString from 'query-string'; @@ -9,6 +9,12 @@ import React from 'react'; // import { withRouter } from 'react-router-dom'; +interface GameProps { + privateParty: boolean, + username?: string + gameId?: number +} + function Field() { useEffect(() => { @@ -17,7 +23,7 @@ function Field() console.log("launch canva hehe") let Modifiers = 0; - let info; + let info: GameProps; if (queryParams.superpower === 'true') { Modifiers += 1; @@ -33,16 +39,16 @@ function Field() info = { privateParty: false, + } if (queryParams.username) { console.log("user= ", queryParams.username) info = { privateParty: true, - username: queryParams.username, + username: queryParams.username as string, + gameId: queryParams.gameId as unknown as number } - if (queryParams.gameId) - info.gameId = queryParams.gameId console.log("info of param vefore canvas=", info) } @@ -50,9 +56,10 @@ function Field() return () => { console.log("Cleanup"); - cleanup(); // Call the cleanup function to stop the ongoing process or perform necessary cleanup tasks + // cleanup(); // Call the cleanup function to stop the ongoing process or perform necessary cleanup tasks + if (cleanup) + cleanup(); }; - }, []); // const [buttonClicked, setButtonClicked] = useState(false); diff --git a/containers/react/src/pages/Head.tsx b/containers/react/src/pages/Head.tsx index 0284f4c7..ebf206d9 100644 --- a/containers/react/src/pages/Head.tsx +++ b/containers/react/src/pages/Head.tsx @@ -1,3 +1,5 @@ +import React from "react"; + function Head() { return ( @@ -7,7 +9,7 @@ function Head() BEST PONG EVER {/* */} - + {/* */}
    ); diff --git a/containers/react/src/pages/Home.tsx b/containers/react/src/pages/Home.tsx index 0f5f40db..4e59a416 100644 --- a/containers/react/src/pages/Home.tsx +++ b/containers/react/src/pages/Home.tsx @@ -6,7 +6,7 @@ /* By: apommier +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/06/09 08:19:04 by apommier #+# #+# */ -/* Updated: 2023/06/19 20:27:00 by apommier ### ########.fr */ +/* Updated: 2023/06/20 15:27:00 by apommier ### ########.fr */ /* */ /* ************************************************************************** */ @@ -30,8 +30,9 @@ import { IoCloseCircleOutline } from "react-icons/io5"; // import * as React from 'react'; // import { useState, useEffect, useParams} from "react"; -import React, { useState, useEffect, useRef } from "react"; +import React, { useState, useEffect, useRef, ChangeEventHandler } from "react"; import { useParams } from 'react-router-dom'; +import {User, Conv} from "../../interfaces.tsx" // axios.get("http://localhost/api") // .then((response) => { // response = response.json() @@ -43,41 +44,89 @@ import { useParams } from 'react-router-dom'; function Profile () { - const [user, setUser] = useState(null); - const [isLoading, setIsLoading] = useState(true); - const [modalOpen, setModalOpen] = useState(false); - const [mine, setMine] = useState(false); + const [user, setUser] = useState(); + const [isLoading, setIsLoading] = useState(true); + const [modalOpen, setModalOpen] = useState(false); + const [mine, setMine] = useState(false); const close = () => setModalOpen(false); const open = () => setModalOpen(true); const { username } = useParams(); - const [selectedPhoto, setSelectedPhoto] = useState(null); + // const [selectedPhoto, setSelectedPhoto] = useState(); + // const [selectedPhoto, setSelectedPhoto] = useState(null); + const [profilePicture, setProfilePicture] = useState(''); - const handleFileChange = (event) => { - // const file = event.target.files[0]; - setSelectedPhoto(event.target.files[0]); - // try{ - // api.post("/picture", {picture: URL.createObjectURL(file)}) - // } - // catch(err){ - // console.log(err); - // } - }; + // const handleFileChange = (event: { target: { files: React.SetStateAction[]; }; }) => { + // // const file = event.target.files[0]; + // setSelectedPhoto(event.target.files[0]); + // // try{ + // // api.post("/picture", {picture: URL.createObjectURL(file)}) + // // } + // // catch(err){ + // // console.log(err); + // // } + // }; - const handleUpload = async () => { - const formData = new FormData(); - formData.append('photo', selectedPhoto); - try { - await api.post('/picture', formData); - console.log('File uploaded successfully'); - window.location.reload(false); - } catch (error) { - console.error('Error uploading file:', error); - } + // const handleFileChange = (event: { target: { files: React.SetStateAction[] | FileList; }; }) => { + // const files = event.target.files; + // if (event.target.files && event.target.files.length > 0) { + // setSelectedPhoto(event.target.files[0]); + // } + // }; + + const handleFileChange = async (event: { target: { files: any; }; }) => { + // const files = event.target.files; + // if (files && files.length > 0) { + const photo = (event.target.files[0]); + console.log("file selected") + if (photo) { + console.log("selected photo") + const formData = new FormData(); + formData.append('photo', photo); + try { + await api.post('/picture', formData); + console.log('File uploaded successfully'); + window.location.reload(); + } catch (error) { + console.error('Error uploading file:', error); + } + } + // } }; + // const handleUpload = async () => { + // const formData = new FormData(); + // formData.append('photo', selectedPhoto); + // try { + // await api.post('/picture', formData); + // console.log('File uploaded successfully'); + // window.location.reload(); + // } catch (error) { + // console.error('Error uploading file:', error); + // } + // }; + + // const handleUpload = async (event: React.FormEvent) => { + // event.preventDefault() + // console.log("up photo") + // if (selectedPhoto) { + // console.log("selected photo") + // const formData = new FormData(); + // formData.append('photo', selectedPhoto); + // try { + // await api.post('/picture', formData); + // console.log('File uploaded successfully'); + // window.location.reload(); + // } catch (error) { + // console.error('Error uploading file:', error); + // } + // } else { + // console.log('No file selected'); + // } + // }; + useEffect(()=> { const getUser = async ()=>{ console.log(`username= ${username}`) @@ -122,7 +171,7 @@ function Profile () { Default Profile Picture )} - {isLoading ? ( + {isLoading || !user ? (

    Loading...

    ) : (

    {user.nickname}

    @@ -142,7 +191,8 @@ function Profile () {
    - + {/* */} + {/* */}
  • ) : ( diff --git a/containers/react/src/pages/Login42.tsx b/containers/react/src/pages/Login42.tsx index e69c9e8e..c47c8421 100644 --- a/containers/react/src/pages/Login42.tsx +++ b/containers/react/src/pages/Login42.tsx @@ -1,6 +1,7 @@ // import GoogleLogin from 'react-google-login'; import { useEffect } from 'react'; import axios from 'axios'; +import React from 'react'; // import setupLogin from '../script/login42'; // import React, { useEffect } from 'react'; @@ -37,7 +38,7 @@ function Login42() return (
    -

    "COUCOU LOGIN$@ jeje"

    +

    "COUCOU LOGIN"

    {/* */}
    ); diff --git a/containers/react/src/pages/Messages.tsx b/containers/react/src/pages/Messages.tsx index 3130e2ab..9d3ad2f2 100644 --- a/containers/react/src/pages/Messages.tsx +++ b/containers/react/src/pages/Messages.tsx @@ -6,7 +6,7 @@ import { motion } from 'framer-motion' // import {io} from 'socket.io-client' -function Messages(params) { +function Messages() { // const socket = useRef(io("ws://localhost:8900")) // useEffect(() => { diff --git a/containers/react/src/pages/NewLogin.tsx b/containers/react/src/pages/NewLogin.tsx index 4e98f900..e87c603d 100644 --- a/containers/react/src/pages/NewLogin.tsx +++ b/containers/react/src/pages/NewLogin.tsx @@ -1,3 +1,4 @@ +import React from 'react'; import '../styles/field.css'; // import { useHistory } from 'react-router-dom'; import { useNavigate } from "react-router-dom"; diff --git a/containers/react/src/pages/QrCode.tsx b/containers/react/src/pages/QrCode.tsx index ad9f2367..2dcca83f 100644 --- a/containers/react/src/pages/QrCode.tsx +++ b/containers/react/src/pages/QrCode.tsx @@ -29,9 +29,10 @@ const qrCode = new QRCodeStyling({ function QrCode () { // const url = "https://www.youtube.com"; - const ref = useRef(null); + // const ref = useRef(null); + const ref = useRef(null); const [user, setUser] = useState(false); - const [url, setUrl] = useState(false); + const [url, setUrl] = useState(""); const [secret, setSecret] = useState(false); const [code, setCode] = useState(''); const [activated, setActivated] = useState(false); @@ -39,8 +40,8 @@ function QrCode () { // const history = useHistory(); useEffect(() => { - qrCode.append(ref.current); - + if (ref.current) + qrCode.append(ref.current); const getUser = async ()=>{ try{ const tmpUser = await api.get("/profile"); @@ -66,13 +67,11 @@ function QrCode () { }, []); useEffect(() => { - qrCode.update({ - data: url - }); + qrCode.update({data: url}); }, [url]); - const handleKeyPress = async (e)=>{ + const handleKeyPress = async (e: { key: string; })=>{ // console.log(`e in press= ${e.key}`) if (e.key !== "Enter") return ; @@ -87,8 +86,8 @@ function QrCode () { // history.push('/login') const path = 'http://' + process.env.REACT_APP_BASE_URL + '/'; - window.history.pushState({}, null, path); - window.location.reload(false); + window.history.pushState({}, '', path); + window.location.reload(); } else @@ -107,8 +106,8 @@ function QrCode () { try { await api.post("/deleteOtp") // const path = 'http://' + process.env.REACT_APP_BASE_URL + '/'; - // window.history.pushState({}, null, path); - window.location.reload(false); + // window.history.pushState({}, '', path); + window.location.reload(); } catch(err) { console.log(err); } @@ -139,6 +138,7 @@ function QrCode () {

    {secret}

    Or Scan The QRCode

    + {/*
    {ref}
    */} )} diff --git a/containers/react/src/pages/canvas.tsx b/containers/react/src/pages/canvas.tsx index b02274ae..7cef82fe 100644 --- a/containers/react/src/pages/canvas.tsx +++ b/containers/react/src/pages/canvas.tsx @@ -8,7 +8,13 @@ import io from 'socket.io-client'; // const socket = io('http://86.209.110.20:4000'); // const socket = io('http://172.29.113.91:4000'); -function DrawCanvas(option: number, gameParam) { +interface GameProps { + privateParty: boolean, + username?: string + gameId?: number +} + +function DrawCanvas(option: number, gameParam: GameProps) { console.log(`option= ${option}`); const superpowerModifier = option & 1; // Retrieves the superpower modifier @@ -23,7 +29,6 @@ function DrawCanvas(option: number, gameParam) { // const socketRef = useRef(null); // socketRef.current = io('http://localhost:4000'); - const socket = io('http://' + process.env.REACT_APP_BASE_URL + ':4000'); function launchGame() { @@ -43,17 +48,22 @@ function DrawCanvas(option: number, gameParam) { joinPrivateParty(); } } - + // const socket = socketRef.current console.log("start function"); - let canvas; - canvas = document.getElementById('myCanvas'); + // let canvas: HTMLElement | null; + const canvas = document.getElementById('myCanvas') as HTMLCanvasElement | null;; + if (!canvas) + return ; const ctx = canvas.getContext('2d'); + if(!ctx) + return ; + const socket = io('http://' + process.env.REACT_APP_BASE_URL + ':4000'); // useEffect(() => { - // console.log("useeffect?????????????????") + // console.log("useeffect?????????????????") // return () => { // console.log("000000000000000000000000000000000") // socketRef.current.disconnect(); @@ -70,8 +80,8 @@ function DrawCanvas(option: number, gameParam) { //socket let myId = 0; let gameId = 0; - let opName; - let opRank; + let opName: string + let opRank: number; //general canvas let running = true; @@ -143,7 +153,7 @@ socket.on('pong:win', async () => { socket.emit('pong:disconnect', {id: myId}); console.log("before reload") window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong"); - // window.location.reload(false); + // window.location.reload(); return ; // console.log("send all ?? win"); @@ -286,7 +296,7 @@ socket.on('pong:point', (data) => { function send_info() { - if (gameId === 0) + if (!gameId || !canvas) return ; const info = { id: myId, @@ -304,7 +314,7 @@ socket.on('pong:point', (data) => { function send_point() { - if (gameId === 0) + if (!gameId || !canvas) return ; console.log("send point"); const info = { @@ -317,7 +327,7 @@ socket.on('pong:point', (data) => { function send_paddle_info() { - if (gameId === 0) + if (!gameId || !canvas) return ; const info = { id: myId, @@ -331,6 +341,8 @@ socket.on('pong:point', (data) => { function use_power() { + if (!canvas) + return ; const info = { gameId: gameId, width: canvas.width, @@ -342,7 +354,7 @@ socket.on('pong:point', (data) => { function send_forced_info() { - if (gameId === 0) + if (!gameId || !canvas) return ; const info = { gameId: gameId, @@ -367,6 +379,8 @@ socket.on('pong:point', (data) => { function drawcenter() { // ctx.restore(); + if (!ctx || !canvas) + return ; ctx.fillStyle = 'white'; ctx.fillRect(canvas.width / 2 - ctx.lineWidth / 2, 0, canvas.width / 300, canvas.height); @@ -379,11 +393,13 @@ socket.on('pong:point', (data) => { ctx.font = canvas.width * 0.1 + "px Arial"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; - ctx.fillText(myScore, canvas.width/4, canvas.height/8); - ctx.fillText(hisScore, canvas.width/1.25, canvas.height/8); + ctx.fillText(myScore.toString(), canvas.width/4, canvas.height/8); + ctx.fillText(hisScore.toString(), canvas.width/1.25, canvas.height/8); } function drawPaddle() { + if (!ctx || !canvas) + return ; ctx.fillStyle = 'white'; ctx.fillRect(paddleX, paddleY, paddleWidth, paddleHeight); ctx.fillRect(canvas.width - paddleX - paddleWidth, oPaddleY, paddleWidth, opPaddleHeight); @@ -391,6 +407,8 @@ socket.on('pong:point', (data) => { function drawball() { + if (!ctx) + return ; ctx.beginPath(); ctx.arc(ballX, ballY, ballRadius, 0, 2 * Math.PI); // ctx.lineWidth = 2; @@ -432,17 +450,17 @@ socket.on('pong:point', (data) => { } socket.emit('pong:disconnect', {id: myId}); window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong"); - // window.location.reload(false); + // window.location.reload(); // Perform any necessary cleanup tasks // ... }; -async function draw(timestamp) +async function draw(timestamp: number) { console.log("turning, running= ", running); if (!running) return ; - if (gameId === 0 ) + if (!gameId || !canvas ) { // console.log("nogameid score= ", myScore); requestAnimationFrame(draw); @@ -473,7 +491,7 @@ async function draw(timestamp) console.log("send loose"); } window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong"); - // window.location.reload(false); + // window.location.reload(); return ; } @@ -482,6 +500,9 @@ async function draw(timestamp) ballX += vX * deltaTime * canvas.width; ballY += vY * deltaTime * canvas.height; + if (!ctx) + return ; + // requestAnimationFrame(draw); ctx.clearRect(0, 0, canvas.width, canvas.height); drawPaddle(); drawcenter(); @@ -518,14 +539,17 @@ async function draw(timestamp) } - function updatePaddlePosition(newY) + function updatePaddlePosition(newY: number) { - if (newY >= 0 && newY <= canvas.height - paddleHeight) + + if (canvas && newY >= 0 && newY <= canvas.height - paddleHeight) paddleY = newY; } function is_collision() { + if (!canvas) + return ; if (ballX <= paddleX + paddleWidth + ballRadius) { if (ballY <= paddleY + paddleHeight + ballRadius && ballY >= paddleY - ballRadius)//touch paddle @@ -559,6 +583,8 @@ async function draw(timestamp) function is_out() { + if (!canvas) + return ; if (ballX < 0) { if (ballY <= paddleY + paddleHeight + ballRadius && ballY >= paddleY - ballRadius) @@ -605,12 +631,18 @@ async function draw(timestamp) //======================================================================================================== //======================================================================================================== - document.addEventListener('resize', event => { - // event.height - // event.width - const { clientWidth, clientHeight } = canvas.parentElement; - console.log(`resize detected widht= ${clientWidth} height= ${clientHeight}`) - }); +// interface sizeProps { +// clientWidth: number, +// clientHeight: number +// } + + // document.addEventListener('resize', event => { + // // event.height + // // event.width + // const { clientWidth, clientHeight } = canvas.parentElement; + // // const { clientWidth, clientHeight } = canvas.parentElement!; + // console.log(`resize detected widht= ${clientWidth} height= ${clientHeight}`) + // }); document.addEventListener('mousemove', event => { const mouseY = event.clientY; diff --git a/containers/react/src/script/tokenSuccess.tsx b/containers/react/src/script/tokenSuccess.tsx index 5eb24530..fac964e4 100644 --- a/containers/react/src/script/tokenSuccess.tsx +++ b/containers/react/src/script/tokenSuccess.tsx @@ -68,8 +68,8 @@ function SuccessToken() { window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong"); // const path = 'http://' + process.env.REACT_APP_BASE_URL + '/'; - // window.history.pushState({}, null, path); - // window.location.reload(false); + // window.history.pushState({}, '', path); + // window.location.reload(); } else @@ -197,8 +197,8 @@ function SuccessToken() { // // history.push('/login') // const path = 'http://' + process.env.REACT_APP_BASE_URL + '/'; -// window.history.pushState({}, null, path); -// window.location.reload(false); +// window.history.pushState({}, '', path); +// window.location.reload(); // } // else diff --git a/containers/react/src/styles/Messages.css b/containers/react/src/styles/Messages.css index 0d201718..57bbe076 100644 --- a/containers/react/src/styles/Messages.css +++ b/containers/react/src/styles/Messages.css @@ -32,6 +32,7 @@ select{ display: flex; flex-direction: column; align-items: center; + overflow-x: scroll; } .scroll{ @@ -50,7 +51,8 @@ select{ .contact{ background-color: rgb(46, 46, 46); align-items: left; - height: 30.2rem; + height: 74vh; + width: 30%; overflow: scroll; /* width: 2rem; */ /* height: 4rem; */ @@ -92,6 +94,8 @@ select{ } .navbar{ + /* width: clamp(50%, 500px, 20%); */ + /* height: min(50%, 100px); */ display: flex; align-items: center; /* background-color: yellow; */ @@ -130,6 +134,7 @@ select{ background-color: rgb(26, 26, 26); /* height: calc(100% - 118px); */ width: 70%; + /* height: 300px; */ overflow: scroll; } @@ -169,11 +174,17 @@ input{ .messageContent{ display: flex; + flex-wrap: wrap; flex-direction: column; max-width: 80%; gap: 10px; } +p { + overflow-wrap: break-word; + max-width: 300px; +} + .meMessage{ display: flex; flex-direction: row-reverse; diff --git a/containers/react/src/styles/Profile.css b/containers/react/src/styles/Profile.css index aa1a90fd..6d41023c 100644 --- a/containers/react/src/styles/Profile.css +++ b/containers/react/src/styles/Profile.css @@ -54,11 +54,7 @@ - - - - - + diff --git a/containers/react/src/styles/old.css b/containers/react/src/styles/old.css index 41525064..7e15c34d 100644 --- a/containers/react/src/styles/old.css +++ b/containers/react/src/styles/old.css @@ -77,11 +77,6 @@ input{ text-decoration: none; } -label{ -} - -.login { -} .loginForm { align-items: center; diff --git a/containers/react/tsconfig.json b/containers/react/tsconfig.json new file mode 100644 index 00000000..bd4507fe --- /dev/null +++ b/containers/react/tsconfig.json @@ -0,0 +1,111 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + "jsx": "react", + "noEmit": true, + "allowImportingTsExtensions": true, + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} diff --git a/containers/test b/containers/test deleted file mode 100644 index f7eced04..00000000 --- a/containers/test +++ /dev/null @@ -1,2 +0,0 @@ -cc toi -cc 2 \ No newline at end of file