// MultipleChoiceQuestionDisplay.tsx import React, { useEffect, useState } from 'react'; import '../questionStyle.css'; import { Button } from '@mui/material'; import { FormattedTextTemplate } from '../../GiftTemplate/templates/TextTypeTemplate'; import { MultipleChoiceQuestion } from 'gift-pegjs'; import { AnswerType } from 'src/pages/Student/JoinRoom/JoinRoom'; import { useQuizContext } from 'src/pages/Student/JoinRoom/QuizContext'; import { QuizContext } from 'src/pages/Student/JoinRoom/QuizContext'; const MultipleChoiceQuestionDisplay: React.FC = () => { const { questions, index, answer, submitAnswer } = useQuizContext(); console.log('MultipleChoiceQuestionDisplay: passedAnswer', JSON.stringify(answer)); const question = questions[Number(index)].question as MultipleChoiceQuestion; const [actualAnswer, setActualAnswer] = useState(() => { if (answer && answer.length > 0) { return answer; } return []; }); let disableButton = false; if (submitAnswer === undefined) { disableButton = true; } useEffect(() => { console.log('MultipleChoiceQuestionDisplay: passedAnswer', JSON.stringify(answer)); if (answer !== undefined) { setActualAnswer(answer); } else { setActualAnswer([]); } }, [answer, index]); const handleOnClickAnswer = (choice: string) => { setActualAnswer((answer) => { console.log(`handleOnClickAnswer -- setAnswer(): prevAnswer: ${answer}, choice: ${choice}`); const correctAnswersCount = question.choices.filter((c) => c.isCorrect).length; if (correctAnswersCount === 1) { // If only one correct answer, replace the current selection return answer.includes(choice) ? [] : [choice]; } else { // Allow multiple selections if there are multiple correct answers if (answer.includes(choice)) { // Remove the choice if it's already selected return answer.filter((selected) => selected !== choice); } else { // Add the choice if it's not already selected return [...answer, choice]; } } }); }; const alpha = Array.from(Array(26)).map((_e, i) => i + 65); const alphabet = alpha.map((x) => String.fromCharCode(x)); return ( {({ showAnswer }) => (
{question.choices.map((choice, i) => { console.log(`answer: ${actualAnswer}, choice: ${choice.formattedText.text}`); const selected = actualAnswer.includes(choice.formattedText.text) ? 'selected' : ''; return (
); })}
{question.formattedGlobalFeedback && showAnswer && (
)} {!showAnswer && submitAnswer && ( )}
)} ); }; export default MultipleChoiceQuestionDisplay;