EvalueTonSavoir/client/src/pages/Teacher/ManageRoom/ManageRoom.tsx

546 lines
23 KiB
TypeScript
Raw Normal View History

2024-03-29 20:08:34 -04:00
import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Socket } from 'socket.io-client';
2025-01-25 02:02:18 -05:00
import { ParsedGIFTQuestion, BaseQuestion, parse, Question } from 'gift-pegjs';
2025-02-20 00:37:01 -05:00
import {
isSimpleNumericalAnswer,
isRangeNumericalAnswer,
isHighLowNumericalAnswer
} from 'gift-pegjs/typeGuards';
2025-01-16 12:37:07 -05:00
import LiveResultsComponent from 'src/components/LiveResults/LiveResults';
2025-02-20 00:37:01 -05:00
import webSocketService, {
AnswerReceptionFromBackendType
} from '../../../services/WebsocketService';
2024-03-29 20:08:34 -04:00
import { QuizType } from '../../../Types/QuizType';
import GroupIcon from '@mui/icons-material/Group';
2024-03-29 20:08:34 -04:00
import './manageRoom.css';
import { ENV_VARIABLES } from 'src/constants';
import { StudentType, Answer } from '../../../Types/StudentType';
2025-01-16 12:37:07 -05:00
import LoadingCircle from 'src/components/LoadingCircle/LoadingCircle';
2024-03-29 20:08:34 -04:00
import { Refresh, Error } from '@mui/icons-material';
2025-01-16 12:37:07 -05:00
import StudentWaitPage from 'src/components/StudentWaitPage/StudentWaitPage';
import DisconnectButton from 'src/components/DisconnectButton/DisconnectButton';
2025-01-25 02:02:18 -05:00
import QuestionDisplay from 'src/components/QuestionsDisplay/QuestionDisplay';
2024-03-29 20:08:34 -04:00
import ApiService from '../../../services/ApiService';
2025-01-25 02:02:18 -05:00
import { QuestionType } from 'src/Types/QuestionType';
import { Button } from '@mui/material';
2025-03-08 11:05:25 -05:00
import { AnswerType } from 'src/pages/Student/JoinRoom/JoinRoom';
2024-03-29 20:08:34 -04:00
const ManageRoom: React.FC = () => {
const navigate = useNavigate();
const [socket, setSocket] = useState<Socket | null>(null);
2024-09-25 13:05:36 -04:00
const [students, setStudents] = useState<StudentType[]>([]);
const { quizId = '', roomName = '' } = useParams<{ quizId: string, roomName: string }>();
2024-03-29 20:08:34 -04:00
const [quizQuestions, setQuizQuestions] = useState<QuestionType[] | undefined>();
const [quiz, setQuiz] = useState<QuizType | null>(null);
const [quizMode, setQuizMode] = useState<'teacher' | 'student'>('teacher');
const [connectingError, setConnectingError] = useState<string>('');
const [currentQuestion, setCurrentQuestion] = useState<QuestionType | undefined>(undefined);
const [quizStarted, setQuizStarted] = useState<boolean>(false);
const [formattedRoomName, setFormattedRoomName] = useState("");
const [newlyConnectedUser, setNewlyConnectedUser] = useState<StudentType | null>(null);
// Handle the newly connected user in useEffect, because it needs state info
// not available in the socket.on() callback
useEffect(() => {
if (newlyConnectedUser) {
console.log(`Handling newly connected user: ${newlyConnectedUser.name}`);
setStudents((prevStudents) => [...prevStudents, newlyConnectedUser]);
// only send nextQuestion if the quiz has started
if (!quizStarted) {
console.log(`!quizStarted: returning.... `);
return;
}
if (quizMode === 'teacher') {
webSocketService.nextQuestion({
roomName: formattedRoomName,
questions: quizQuestions,
questionIndex: Number(currentQuestion?.question.id) - 1,
isLaunch: true // started late
});
} else if (quizMode === 'student') {
webSocketService.launchStudentModeQuiz(formattedRoomName, quizQuestions);
} else {
console.error('Invalid quiz mode:', quizMode);
}
// Reset the newly connected user state
setNewlyConnectedUser(null);
}
2025-03-09 01:19:31 -05:00
}, [newlyConnectedUser]);
useEffect(() => {
const verifyLogin = async () => {
if (!ApiService.isLoggedIn()) {
navigate('/teacher/login');
return;
}
};
verifyLogin();
}, []);
2024-03-29 20:08:34 -04:00
useEffect(() => {
if (!roomName || !quizId) {
window.alert(
`Une erreur est survenue.\n La salle ou le quiz n'a pas été spécifié.\nVeuillez réessayer plus tard.`
);
console.error(`Room "${roomName}" or Quiz "${quizId}" not found.`);
navigate('/teacher/dashboard');
}
if (roomName && !socket) {
createWebSocketRoom();
2025-02-24 03:29:36 -05:00
}
return () => {
disconnectWebSocket();
2025-02-20 00:19:32 -05:00
};
}, [roomName, navigate]);
2024-03-29 20:08:34 -04:00
useEffect(() => {
if (quizId) {
const fetchQuiz = async () => {
const quiz = await ApiService.getQuiz(quizId);
2024-03-29 20:08:34 -04:00
if (!quiz) {
2025-02-20 00:37:01 -05:00
window.alert(
`Une erreur est survenue.\n Le quiz ${quizId} n'a pas été trouvé\nVeuillez réessayer plus tard`
2025-02-20 00:37:01 -05:00
);
console.error('Quiz not found for id:', quizId);
2024-03-29 20:08:34 -04:00
navigate('/teacher/dashboard');
return;
}
setQuiz(quiz as QuizType);
};
fetchQuiz();
2024-03-29 20:08:34 -04:00
} else {
2025-02-20 00:37:01 -05:00
window.alert(
`Une erreur est survenue.\n Le quiz ${quizId} n'a pas été trouvé\nVeuillez réessayer plus tard`
2025-02-20 00:37:01 -05:00
);
console.error('Quiz not found for id:', quizId);
2024-03-29 20:08:34 -04:00
navigate('/teacher/dashboard');
return;
}
}, [quizId]);
const disconnectWebSocket = () => {
if (socket) {
webSocketService.endQuiz(formattedRoomName);
2024-03-29 20:08:34 -04:00
webSocketService.disconnect();
setSocket(null);
setQuizQuestions(undefined);
setCurrentQuestion(undefined);
2024-09-25 14:53:17 -04:00
setStudents(new Array<StudentType>());
2024-03-29 20:08:34 -04:00
}
};
const createWebSocketRoom = () => {
2025-03-04 16:43:11 -05:00
const socket = webSocketService.connect(ENV_VARIABLES.VITE_BACKEND_URL);
const roomNameUpper = roomName.toUpperCase();
setFormattedRoomName(roomNameUpper);
console.log(`Creating WebSocket room named ${roomNameUpper}`);
/**
* ATTENTION: Lire les variables d'état dans
* les .on() n'est pas une bonne pratique.
* Les valeurs sont celles au moment de la création
* de la fonction et non au moment de l'exécution.
* Il faut utiliser des refs pour les valeurs qui
* changent fréquemment. Sinon, utiliser un trigger
* de useEffect pour mettre déclencher un traitement
* (voir user-joined plus bas).
*/
2024-03-29 20:08:34 -04:00
socket.on('connect', () => {
webSocketService.createRoom(roomNameUpper);
2024-03-29 20:08:34 -04:00
});
2025-02-24 03:29:36 -05:00
2024-03-29 20:08:34 -04:00
socket.on('connect_error', (error) => {
setConnectingError('Erreur lors de la connexion... Veuillez réessayer');
2024-10-30 17:19:11 -04:00
console.error('ManageRoom: WebSocket connection error:', error);
2024-03-29 20:08:34 -04:00
});
2025-02-24 03:29:36 -05:00
socket.on('create-success', (createdRoomName: string) => {
console.log(`Room created: ${createdRoomName}`);
2024-03-29 20:08:34 -04:00
});
2025-02-24 03:29:36 -05:00
2024-09-25 13:05:36 -04:00
socket.on('user-joined', (student: StudentType) => {
setNewlyConnectedUser(student);
2024-04-09 10:10:17 -04:00
});
2024-03-29 20:08:34 -04:00
socket.on('join-failure', (message) => {
setConnectingError(message);
setSocket(null);
});
2025-02-24 03:29:36 -05:00
2024-03-29 20:08:34 -04:00
socket.on('user-disconnected', (userId: string) => {
console.log(`Student left: id = ${userId}`);
setStudents((prevUsers) => prevUsers.filter((user) => user.id !== userId));
2024-03-29 20:08:34 -04:00
});
2024-03-29 20:08:34 -04:00
setSocket(socket);
};
2024-04-06 19:25:30 -04:00
useEffect(() => {
if (socket) {
console.log(`Listening for submit-answer-room in room ${formattedRoomName}`);
socket.on('submit-answer-room', (answerData: AnswerReceptionFromBackendType) => {
const { answer, idQuestion, idUser, username } = answerData;
2025-02-24 03:29:36 -05:00
console.log(
`Received answer from ${username} for question ${idQuestion}: ${answer}`
);
if (!quizQuestions) {
console.log('Quiz questions not found (cannot update answers without them).');
return;
}
// Update the students state using the functional form of setStudents
setStudents((prevStudents) => {
console.log('Current students:');
prevStudents.forEach((student) => {
console.log(student.name);
});
let foundStudent = false;
const updatedStudents = prevStudents.map((student) => {
console.log(`Comparing ${student.id} to ${idUser}`);
if (student.id === idUser) {
foundStudent = true;
2025-02-24 03:29:36 -05:00
const existingAnswer = student.answers.find(
(ans) => ans.idQuestion === idQuestion
);
let updatedAnswers: Answer[] = [];
if (existingAnswer) {
updatedAnswers = student.answers.map((ans) => {
console.log(`Comparing ${ans.idQuestion} to ${idQuestion}`);
2025-02-24 03:29:36 -05:00
return ans.idQuestion === idQuestion
? {
...ans,
answer,
isCorrect: checkIfIsCorrect(
answer,
idQuestion,
quizQuestions!
)
}
: ans;
});
} else {
2025-02-24 03:29:36 -05:00
const newAnswer = {
idQuestion,
answer,
isCorrect: checkIfIsCorrect(answer, idQuestion, quizQuestions!)
};
updatedAnswers = [...student.answers, newAnswer];
}
return { ...student, answers: updatedAnswers };
}
return student;
});
if (!foundStudent) {
console.log(`Student ${username} not found in the list.`);
}
return updatedStudents;
});
});
setSocket(socket);
}
}, [socket, currentQuestion, quizQuestions]);
2024-03-29 20:08:34 -04:00
const nextQuestion = () => {
if (!quizQuestions || !currentQuestion || !quiz?.content) return;
const nextQuestionIndex = Number(currentQuestion?.question.id);
if (nextQuestionIndex === undefined || nextQuestionIndex > quizQuestions.length - 1) return;
setCurrentQuestion(quizQuestions[nextQuestionIndex]);
webSocketService.nextQuestion({roomName: formattedRoomName,
questions: quizQuestions,
questionIndex: nextQuestionIndex,
isLaunch: false});
2024-03-29 20:08:34 -04:00
};
const previousQuestion = () => {
if (!quizQuestions || !currentQuestion || !quiz?.content) return;
2024-03-29 20:08:34 -04:00
const prevQuestionIndex = Number(currentQuestion?.question.id) - 2; // -2 because question.id starts at index 1
2024-03-29 20:08:34 -04:00
if (prevQuestionIndex === undefined || prevQuestionIndex < 0) return;
setCurrentQuestion(quizQuestions[prevQuestionIndex]);
webSocketService.nextQuestion({roomName: formattedRoomName, questions: quizQuestions, questionIndex: prevQuestionIndex, isLaunch: false});
};
2024-03-29 20:08:34 -04:00
const initializeQuizQuestion = () => {
const quizQuestionArray = quiz?.content;
if (!quizQuestionArray) return null;
const parsedQuestions = [] as QuestionType[];
quizQuestionArray.forEach((question, index) => {
2025-01-25 02:02:18 -05:00
parsedQuestions.push({ question: parse(question)[0] as BaseQuestion });
2024-03-29 20:08:34 -04:00
parsedQuestions[index].question.id = (index + 1).toString();
});
if (parsedQuestions.length === 0) return null;
setQuizQuestions(parsedQuestions);
return parsedQuestions;
};
const launchTeacherMode = () => {
const quizQuestions = initializeQuizQuestion();
console.log('launchTeacherMode - quizQuestions:', quizQuestions);
2024-03-29 20:08:34 -04:00
if (!quizQuestions) {
console.log('Error launching quiz (launchTeacherMode). No questions found.');
return;
}
2024-03-29 20:08:34 -04:00
setCurrentQuestion(quizQuestions[0]);
webSocketService.nextQuestion({roomName: formattedRoomName, questions: quizQuestions, questionIndex: 0, isLaunch: true});
2024-03-29 20:08:34 -04:00
};
const launchStudentMode = () => {
const quizQuestions = initializeQuizQuestion();
console.log('launchStudentMode - quizQuestions:', quizQuestions);
2024-03-29 20:08:34 -04:00
if (!quizQuestions) {
console.log('Error launching quiz (launchStudentMode). No questions found.');
2024-03-29 20:08:34 -04:00
return;
}
setQuizQuestions(quizQuestions);
webSocketService.launchStudentModeQuiz(formattedRoomName, quizQuestions);
2024-03-29 20:08:34 -04:00
};
const launchQuiz = () => {
setQuizStarted(true);
if (!socket || !formattedRoomName || !quiz?.content || quiz?.content.length === 0) {
// TODO: This error happens when token expires! Need to handle it properly
2025-02-20 00:37:01 -05:00
console.log(
`Error launching quiz. socket: ${socket}, roomName: ${formattedRoomName}, quiz: ${quiz}`
2025-02-20 00:37:01 -05:00
);
2024-03-29 20:08:34 -04:00
return;
}
console.log(`Launching quiz in ${quizMode} mode...`);
2024-03-29 20:08:34 -04:00
switch (quizMode) {
case 'student':
return launchStudentMode();
case 'teacher':
return launchTeacherMode();
}
};
const showSelectedQuestion = (questionIndex: number) => {
if (quiz?.content && quizQuestions) {
setCurrentQuestion(quizQuestions[questionIndex]);
if (quizMode === 'teacher') {
webSocketService.nextQuestion({roomName: formattedRoomName, questions: quizQuestions, questionIndex, isLaunch: false});
2024-03-29 20:08:34 -04:00
}
}
};
const handleReturn = () => {
disconnectWebSocket();
navigate('/teacher/dashboard');
};
2025-02-20 00:37:01 -05:00
function checkIfIsCorrect(
2025-03-08 11:05:25 -05:00
answer: AnswerType,
2025-02-20 00:37:01 -05:00
idQuestion: number,
questions: QuestionType[]
): boolean {
const questionInfo = questions.find((q) =>
q.question.id ? q.question.id === idQuestion.toString() : false
) as QuestionType | undefined;
const answerText = answer.toString();
if (questionInfo) {
2025-01-25 02:02:18 -05:00
const question = questionInfo.question as ParsedGIFTQuestion;
if (question.type === 'TF') {
return (
(question.isTrue && answerText == 'true') ||
(!question.isTrue && answerText == 'false')
);
} else if (question.type === 'MC') {
return question.choices.some(
2025-01-25 02:02:18 -05:00
(choice) => choice.isCorrect && choice.formattedText.text === answerText
);
} else if (question.type === 'Numerical') {
2025-01-25 02:02:18 -05:00
if (isHighLowNumericalAnswer(question.choices[0])) {
const choice = question.choices[0];
const answerNumber = parseFloat(answerText);
if (!isNaN(answerNumber)) {
return (
2025-02-20 00:37:01 -05:00
answerNumber <= choice.numberHigh && answerNumber >= choice.numberLow
2025-01-25 02:02:18 -05:00
);
}
}
2025-01-25 02:02:18 -05:00
if (isRangeNumericalAnswer(question.choices[0])) {
const answerNumber = parseFloat(answerText);
const range = question.choices[0].range;
const correctAnswer = question.choices[0].number;
if (!isNaN(answerNumber)) {
return (
answerNumber <= correctAnswer + range &&
answerNumber >= correctAnswer - range
);
}
2025-01-25 02:02:18 -05:00
}
if (isSimpleNumericalAnswer(question.choices[0])) {
const answerNumber = parseFloat(answerText);
if (!isNaN(answerNumber)) {
return answerNumber === question.choices[0].number;
}
}
} else if (question.type === 'Short') {
return question.choices.some(
2025-01-25 02:02:18 -05:00
(choice) => choice.text.toUpperCase() === answerText.toUpperCase()
);
}
}
return false;
}
if (!formattedRoomName) {
2024-03-29 20:08:34 -04:00
return (
<div className="center">
{!connectingError ? (
<LoadingCircle text="Veuillez attendre la connexion au serveur..." />
) : (
<div className="center-v-align">
<Error sx={{ padding: 0 }} />
<div className="text-base">{connectingError}</div>
<Button
variant="contained"
startIcon={<Refresh />}
onClick={createWebSocketRoom}
>
Reconnecter
</Button>
</div>
)}
</div>
);
}
return (
2025-02-20 00:37:01 -05:00
<div className="room">
<h1>Salle : {formattedRoomName}</h1>
2025-02-20 00:37:01 -05:00
<div className="roomHeader">
2024-03-29 20:08:34 -04:00
<DisconnectButton
onReturn={handleReturn}
askConfirm
2025-02-20 00:37:01 -05:00
message={`Êtes-vous sûr de vouloir quitter?`}
/>
<div
className="headerContent"
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
width: '100%'
}}
>
{(
2025-02-20 00:37:01 -05:00
<div
className="userCount subtitle smallText"
style={{ display: "flex", justifyContent: "flex-end" }}
2025-02-20 00:37:01 -05:00
>
<GroupIcon style={{ marginRight: '5px' }} />
{students.length}/60
</div>
)}
2024-03-29 20:08:34 -04:00
</div>
2025-02-20 00:37:01 -05:00
<div className="dumb"></div>
2024-03-29 20:08:34 -04:00
</div>
2025-02-20 00:37:01 -05:00
{/* the following breaks the css (if 'room' classes are nested) */}
<div className="">
2024-03-29 20:08:34 -04:00
{quizQuestions ? (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<div className="title center-h-align mb-2">{quiz?.title}</div>
{!isNaN(Number(currentQuestion?.question.id)) && (
2025-02-20 00:37:01 -05:00
<strong className="number of questions">
Question {Number(currentQuestion?.question.id)}/
{quizQuestions?.length}
</strong>
)}
2024-03-29 20:08:34 -04:00
{quizMode === 'teacher' && (
<div className="mb-1">
{/* <QuestionNavigation
2024-03-29 20:08:34 -04:00
currentQuestionId={Number(currentQuestion?.question.id)}
questionsLength={quizQuestions?.length}
previousQuestion={previousQuestion}
nextQuestion={nextQuestion}
/> */}
2024-03-29 20:08:34 -04:00
</div>
)}
<div className="mb-2 flex-column-wrapper">
<div className="preview-and-result-container">
{currentQuestion && (
<QuestionDisplay
2024-03-29 20:08:34 -04:00
showAnswer={false}
2025-01-25 02:02:18 -05:00
question={currentQuestion?.question as Question}
2024-03-29 20:08:34 -04:00
/>
)}
<LiveResultsComponent
quizMode={quizMode}
socket={socket}
questions={quizQuestions}
showSelectedQuestion={showSelectedQuestion}
students={students}
2024-03-29 20:08:34 -04:00
></LiveResultsComponent>
</div>
</div>
{quizMode === 'teacher' && (
2025-02-20 00:37:01 -05:00
<div
className="questionNavigationButtons"
style={{ display: 'flex', justifyContent: 'center' }}
>
<div className="previousQuestionButton">
2025-02-20 00:37:01 -05:00
<Button
onClick={previousQuestion}
variant="contained"
2025-02-20 00:37:01 -05:00
disabled={Number(currentQuestion?.question.id) <= 1}
>
Question précédente
</Button>
</div>
<div className="nextQuestionButton">
2025-02-20 00:37:01 -05:00
<Button
onClick={nextQuestion}
variant="contained"
2025-02-20 00:37:01 -05:00
disabled={
Number(currentQuestion?.question.id) >=
quizQuestions.length
}
>
Prochaine question
</Button>
</div>
2025-02-20 00:37:01 -05:00
</div>
)}
2024-03-29 20:08:34 -04:00
</div>
) : (
2024-09-25 13:20:09 -04:00
<StudentWaitPage
2024-09-25 14:53:17 -04:00
students={students}
2024-03-29 20:08:34 -04:00
launchQuiz={launchQuiz}
setQuizMode={setQuizMode}
/>
)}
</div>
</div>
);
};
export default ManageRoom;