// MultipleChoiceQuestionDisplay.tsx import React, { useState, useEffect } from 'react'; import '../questionStyle.css'; import { Button } from '@mui/material'; import { FormattedTextTemplate } from '../../GiftTemplate/templates/TextTypeTemplate'; import { MultipleChoiceQuestion } from 'gift-pegjs'; import { StudentType } from 'src/Types/StudentType'; interface Props { question: MultipleChoiceQuestion; handleOnSubmitAnswer?: (answer: string) => void; showAnswer?: boolean; students?: StudentType[]; isDisplayOnly?: boolean; } const MultipleChoiceQuestionDisplay: React.FC = (props) => { const { question, showAnswer, handleOnSubmitAnswer, students, isDisplayOnly } = props; const [answer, setAnswer] = useState(); const [pickRates, setPickRates] = useState([]); const [showCorrectAnswers, setShowCorrectAnswers] = useState(false); const handleOnClickAnswer = (choice: string) => { setAnswer(choice); }; const toggleShowCorrectAnswers = () => { setShowCorrectAnswers(!showCorrectAnswers); }; const calculatePickRates = () => { if (!students || students.length === 0) { setPickRates(new Array(question.choices.length).fill(0)); // Fill with 0 for each choice return; } const rates = question.choices.map(choice => { const choiceAnswers = students.filter(student => student.answers.some(ans => ans.idQuestion === Number(question.id) && ans.answer === choice.formattedText.text ) ).length; return (choiceAnswers / students.length) * 100; }); setPickRates(rates); }; useEffect(() => { setAnswer(undefined); calculatePickRates(); }, [students, question, showCorrectAnswers]); 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) => { const selected = answer === choice.formattedText.text ? 'selected' : ''; const rateStyle = showCorrectAnswers ? { backgroundImage: `linear-gradient(to right, ${choice.isCorrect ? 'lightgreen' : 'lightcoral'} ${pickRates[i]}%, transparent ${pickRates[i]}%)`, color: 'black' } : {}; return (
{/* */}
); })}
{question.formattedGlobalFeedback && showAnswer && (
)} {!showAnswer && handleOnSubmitAnswer && ( )} {isDisplayOnly && (
)}
); }; export default MultipleChoiceQuestionDisplay;