// 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'; interface Props { question: MultipleChoiceQuestion; handleOnSubmitAnswer?: (answer: AnswerType) => void; showAnswer?: boolean; passedAnswer?: AnswerType; } const MultipleChoiceQuestionDisplay: React.FC = (props) => { const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } = props; console.log('MultipleChoiceQuestionDisplay: passedAnswer', JSON.stringify(passedAnswer)); const [answer, setAnswer] = useState(() => { if (passedAnswer && passedAnswer.length > 0) { return passedAnswer; } return []; }); let disableButton = false; if (handleOnSubmitAnswer === undefined) { disableButton = true; } useEffect(() => { console.log('MultipleChoiceQuestionDisplay: passedAnswer', JSON.stringify(passedAnswer)); if (passedAnswer !== undefined) { setAnswer(passedAnswer); } else { setAnswer([]); } }, [passedAnswer, question.id]); const handleOnClickAnswer = (choice: string) => { setAnswer((prevAnswer) => { console.log(`handleOnClickAnswer -- setAnswer(): prevAnswer: ${prevAnswer}, choice: ${choice}`); const correctAnswersCount = question.choices.filter((c) => c.isCorrect).length; if (correctAnswersCount === 1) { // If only one correct answer, replace the current selection return prevAnswer.includes(choice) ? [] : [choice]; } else { // Allow multiple selections if there are multiple correct answers if (prevAnswer.includes(choice)) { // Remove the choice if it's already selected return prevAnswer.filter((selected) => selected !== choice); } else { // Add the choice if it's not already selected return [...prevAnswer, choice]; } } }); }; const alpha = Array.from(Array(26)).map((_e, i) => i + 65); const alphabet = alpha.map((x) => String.fromCharCode(x)); return (
{question.choices.map((choice, i) => { console.log(`answer: ${answer}, choice: ${choice.formattedText.text}`); const selected = answer.includes(choice.formattedText.text) ? 'selected' : ''; return (
); })}
{question.formattedGlobalFeedback && showAnswer && (
)} {!showAnswer && handleOnSubmitAnswer && ( )}
); }; export default MultipleChoiceQuestionDisplay;