Untitled
unknown
plain_text
4 months ago
41 kB
4
Indexable
import React, { useState, useEffect, useRef, useContext, useCallback } from 'react'; import axios from 'axios'; import Swal from 'sweetalert2'; import 'sweetalert2/dist/sweetalert2.min.css'; import * as Constants from '../../../constants/Constants'; import { useAuthState, useAuthDispatch } from '../../../Context/context'; import { useNavigate, useLocation } from 'react-router-dom'; import Confirm from '../../../components/confirm/Confirm'; import { Typography, Input, Radio, RadioGroup, Grid, Button, Card, Box } from '@mui/material'; import ProgressTracker from './ProgressTracker'; // Replace with the correct path to your ProgressTracker component import "../examRules/components/ExamRules.css"; import MyTimer from 'components/timer/Timer'; import svg2 from '../../../assets/images/svg2.png'; const { Title } = Typography; const CopyNotAllowedModal = () => { return ( <div className="copy-not-allowed-modal"> <p>Copying is not allowed.</p> </div> ); }; function TeacherExam(props) { const navigate = useNavigate(); const location = useLocation(); const dispatch = useAuthDispatch(); const teacherData = location.state?.data; const teacherId = teacherData.teacherId; const taskId = teacherData.taskId; const [showCopyNotAllowedModal, setShowCopyNotAllowedModal] = useState(false); const [questions, setQuestions] = useState([]); const [currentQuestion, setCurrentQuestion] = useState(0); const [progress, setProgress] = useState(0); const [loading, setLoading] = useState(true); const [userAnswers, setUserAnswers] = useState({}); const [saveuserAnswers, setSaveUserAnswers] = useState({}); const [marksForReview, setMarksForReview] = useState({}); const [segmentAnswers, setSegmentAnswers] = useState({}); const [quesOptionSelected, setQuesOptionSelected] = useState({}); const [quesLanguageSelected, setQuesLanguageSelected] = useState({}); const [selectedLanguage, setSelectedLanguage] = useState('english'); const [timerData, setTimerData] = useState({ hours: 0, minutes: 0, seconds: 0, isRunning: false }); const [totalTimerTime, setTotalTimerTime] = useState(null); const [isAnswerSelected, setIsAnswerSelected] = useState(false); const [examInProgress, setExamInProgress] = useState(false); const [saving, setSaving] = useState(false); const userState = useAuthState(); const user = userState.user; const examStarted = userState.examStarted; const examStartedCount = userState.examStartedCount; const [current_sessions, currentSession] = useState([]); const [current_tasks, currentTask] = useState([]); // Timer const initialTimer = parseInt(localStorage.getItem('timer')) || 30 * 60; const [timer, setTimer] = useState(initialTimer); const [isTimerRunning, setIsTimerRunning] = useState(true); const [attemptLaterQuestions, setAttemptLaterQuestions] = useState([]); const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0); // initial question index const [popupInterval, setPopupInterval] = useState(null); const localStorageKey = "userAnswersKey"; // function calculateTimerDuration(endTime) { // const now = new Date(); // console.log("Now time : ", now); // // console.log("End Time :",endTime); // const examEndTime = new Date(now.toDateString() + ' ' + endTime); // // const examEndTime = new Date(now + ' ' + endTime); // // console.log("exam end time ",examEndTime); // // console.log("Diff time :",examEndTime - now); // console.log(examEndTime-now) // return examEndTime - now; // //return now + 60*10; // } // function calculateTimerDuration(endTime, serverTime) { // // Parse server time // const now = new Date(); // const [serverHours, serverMinutes, serverSeconds] = serverTime.split(":").map(Number); // const serverDate = new Date( // now.getFullYear(), // now.getMonth(), // now.getDate(), // serverHours, // serverMinutes, // serverSeconds // ); // console.log("Server Time as Date: ", serverDate); // // Construct the exam end time as a Date object // const examEndTime = new Date(serverDate.toDateString() + ' ' + endTime); // console.log("Exam End Time: ", examEndTime); // // Calculate the difference // const duration = examEndTime - serverDate; // console.log("Duration in ms: ", duration); // return duration; // } function calculateTimerDuration(endTime, serverTime) { try { // Log inputs to verify their formats console.log("Input serverTime:", serverTime); console.log("Input endTime:", endTime); if (!serverTime || !endTime) { throw new Error("Inputs cannot be null or empty."); } // Parse serverTime as ISO 8601 const serverDate = new Date(serverTime); console.log("Parsed serverDate:", serverDate); if (isNaN(serverDate)) { throw new Error("Invalid serverTime format."); } // Parse endTime (expected format: HH:mm) const [endHours, endMinutes] = endTime.split(":").map(Number); console.log("Parsed endTime components:", endHours, endMinutes); if (isNaN(endHours) || isNaN(endMinutes)) { throw new Error("Invalid endTime format."); } // Construct the end time based on the same day as serverDate const examEndTime = new Date( serverDate.getFullYear(), serverDate.getMonth(), serverDate.getDate(), endHours, endMinutes, 0 // Assume seconds are 0 for end time ); console.log("Parsed examEndTime:", examEndTime); // Calculate the duration in milliseconds const durationInMs = examEndTime - serverDate; console.log("Calculated duration (ms):", durationInMs); if (durationInMs < 0) { throw new Error("End time is earlier than server time."); } // Convert milliseconds into hours, minutes, and seconds const hours = Math.floor(durationInMs / (1000 * 60 * 60)); const minutes = Math.floor((durationInMs % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((durationInMs % (1000 * 60)) / 1000); return { hours, minutes, seconds }; } catch (error) { console.error("Error in calculateTimerDuration:", error.message); return { hours: null, minutes: null, seconds: null }; } } useEffect(() => { if (totalTimerTime === 0) { // Perform auto-save here autoSave(); } }, [totalTimerTime]); console.log(totalTimerTime) useEffect(() => { const intervalId = setInterval(() => { Swal.fire({ icon: 'info', title: 'Reminder', html: `Your time is remaining: ${formatTime(totalTimerTime)}. Save your progress!`, confirmButtonText: 'OK', }); }, 1 * 60 * 1000); // 15 minutes reminder return () => clearInterval(intervalId); }, [timer]); useEffect(() => { if (userAnswers[questions[currentQuestion]?.id]) { setIsAnswerSelected(true); // Enable the button if an answer existsdata } else { setIsAnswerSelected(false); // Disable the button otherwise } }, [currentQuestion, userAnswers, questions]); useEffect(() => { fetchCurrentSession(); fetchCurrentTask(); fetchData(); }, []); useEffect(() => { if (isTimerRunning) { const intervalId = setInterval(() => { setTimer(prevTimer => (prevTimer === 0 ? 0 : prevTimer - 1)); }, 1000); return () => clearInterval(intervalId); } }, [isTimerRunning]); useEffect(() => { localStorage.setItem('timer', timer); }, [timer]); const formatTime = (totalSeconds) => { const minutes = Math.floor(totalSeconds / 60); const seconds = totalSeconds % 60; return `${minutes}:${seconds < 10 ? `0${seconds}` : seconds}`; }; const fetchCurrentSession = async () => { try { const response = await axios.get(Constants.API_PATH + '/current_sessions'); currentSession(response.data); setLoading(true); } catch (error) { console.error('Error fetching session:', error); } }; const [servertime, setservertime] = useState("") const [comparingTime, setcomparingTime] = useState("") useEffect(() => { if (servertime) { const time = servertime.split("T")[1].slice(0, 8); setcomparingTime(comparingTime) // console.log(time); // Logs "17:26" // const dateDFKI = new Date() // console.log(dateDFKI.getHours(), dateDFKI.getMinutes(), dateDFKI.getSeconds()) } }, [servertime]); // console.log(servertime.split("T")[1]) // console.log(timeOnly) // const fetchCurrentTask = async () => { // try { // const response = await axios.get(Constants.API_PATH + '/teacher_task_by_id/' + taskId); // currentTask(response.data); // // console.log("ffff",response.data.serverTime) // setservertime(response.data.serverTime) // // console.log(response.data.end_time) // setLoading(true); // setTotalTimerTime(new Date().setSeconds(new Date().getSeconds() + calculateTimerDuration(response.data.end_time) / 1000)); // // console.log("dd",new Date().setSeconds(new Date().getSeconds() + calculateTimerDuration(response.data.end_time) / 1000)) // // console.log("hh", calculateTimerDuration(response.data.end_time) ) // } catch (error) { // console.error('Error fetching task:', error); // } // }; // const fetchCurrentTask = async () => { // try { // const response = await axios.get(Constants.API_PATH + '/teacher_task_by_id/' + taskId); // const data = response.data; // currentTask(data); // setservertime(data.serverTime); // Update the server time state // setLoading(true); // // Calculate timer duration using server time // console.log(data.end_time) // console.log(data.serverTime) // const duration = calculateTimerDuration(data.end_time, data.serverTime); // // Set the total timer time based on the calculated duration // const expiryTimestamp = new Date(); // expiryTimestamp.setSeconds(expiryTimestamp.getSeconds() + duration / 1000); // setTotalTimerTime(expiryTimestamp); // console.log("Expiry Timestamp: ", expiryTimestamp); // } catch (error) { // console.error('Error fetching task:', error); // } // }; // const fetchCurrentTask = async () => { // try { // const response = await axios.get(Constants.API_PATH + '/teacher_task_by_id/' + taskId); // const { end_time, serverTime } = response.data; // console.log("Fetched serverTime:", serverTime); // console.log("Fetched endTime:", end_time); // if (!serverTime || !end_time) { // console.error("Server or end time is missing."); // return; // } // setservertime(serverTime); // const timerDuration = calculateTimerDuration(end_time, serverTime); // if (timerDuration.hours === null) { // console.error("Failed to calculate timer duration. Please check inputs."); // return; // } // setTotalTimerTime(timerDuration); // console.log("Total Timer Time:", timerDuration); // } catch (error) { // console.error("Error fetching task:", error); // } // }; const fetchCurrentTask = async () => { try { const response = await axios.get(Constants.API_PATH + '/teacher_task_by_id/' + taskId); const { end_time, serverTime } = response.data; console.log("Fetched serverTime:", serverTime); console.log("Fetched endTime:", end_time); if (!serverTime || !end_time) { console.error("Server or end time is missing."); return; } setservertime(serverTime); const timerDuration = calculateTimerDuration(end_time, serverTime); if (timerDuration.hours === null) { console.error("Failed to calculate timer duration. Please check inputs."); return; } // Calculate expiry time based on server time and duration const serverDate = new Date(serverTime); const expiryTimestamp = new Date( serverDate.getTime() + timerDuration.hours * 60 * 60 * 1000 + timerDuration.minutes * 60 * 1000 + timerDuration.seconds * 1000 ); setTotalTimerTime(expiryTimestamp); console.log("Total Timer Expiry Time:", expiryTimestamp); } catch (error) { console.error("Error fetching task:", error); } }; const fetchData = async () => { try { const response = await axios.get(Constants.API_PATH + '/teacher_questions/' + taskId); arrangeQuestions(response.data); setQuestions((prevQuestions) => shuffleArray(prevQuestions)); setLoading(true); } catch (error) { console.error('Error fetching questions:', error); } }; const arrangeQuestions = (segmentArr) => { const transformedQuestions = segmentArr.flatMap(element => element.questions.map(question => ({ ...question, segment_id: element.id, segment_name: element.name })) ); setQuestions(transformedQuestions); }; const handlePrevious = () => { if (currentQuestion > 0) { const prevQuestion = currentQuestion - 1; setCurrentQuestion(prevQuestion); setProgress((prevQuestion / questions.length) * 100); // Update `isAnswerSelected` based on the previous question's answer if (userAnswers[questions[prevQuestion]?.id]) { setIsAnswerSelected(true); } else { setIsAnswerSelected(false); } } }; const handleAnswerSelection = (questionId, selectedAnswer, selectedOption, selectedLanguage, selectedSegment) => { setUserAnswers(prevState => ({ ...prevState, [questionId]: selectedAnswer })); setQuesOptionSelected(prevState => ({ ...prevState, [questionId]: selectedOption })); setQuesLanguageSelected(prevState => ({ ...prevState, [questionId]: selectedLanguage })); setSegmentAnswers(prevState => ({ ...prevState, [questionId]: selectedSegment })); setIsAnswerSelected(true); // Enable Save & Next button }; const handleResetAns = (questionId) => { setUserAnswers((prevAnswers) => { const { [questionId]: omitted, ...rest } = prevAnswers; // Remove answer return rest; }); setQuesOptionSelected((prevAnswers) => { const { [questionId]: omitted, ...rest } = prevAnswers; // Remove option return rest; }); setQuesLanguageSelected((prevAnswers) => { const { [questionId]: omitted, ...rest } = prevAnswers; // Remove language selection return rest; }); setSegmentAnswers((prevAnswers) => { const { [questionId]: omitted, ...rest } = prevAnswers; // Remove segment return rest; }); setIsAnswerSelected(false); // Disable Save & Next button }; const saveAnswer = async () => { // Filter out "Attempt Later" questions const filteredUserAnswers = Object.keys(saveuserAnswers) .filter((questionId) => !attemptLaterQuestions.includes(parseInt(questionId))) .reduce((acc, questionId) => { acc[questionId] = saveuserAnswers[questionId]; return acc; }, {}); // console.log("dd",saveuserAnswers) const filteredOptionsSelected = Object.keys(quesOptionSelected) .filter((questionId) => !attemptLaterQuestions.includes(parseInt(questionId))) .reduce((acc, questionId) => { acc[questionId] = quesOptionSelected[questionId]; return acc; }, {}); const filteredLangSelected = Object.keys(quesLanguageSelected) .filter((questionId) => !attemptLaterQuestions.includes(parseInt(questionId))) .reduce((acc, questionId) => { acc[questionId] = quesLanguageSelected[questionId]; return acc; }, {}); const filteredSegmentAnswers = Object.keys(segmentAnswers) .filter((questionId) => !attemptLaterQuestions.includes(parseInt(questionId))) .reduce((acc, questionId) => { acc[questionId] = segmentAnswers[questionId]; return acc; }, {}); const userData = { user_answers: filteredUserAnswers, options_selected: filteredOptionsSelected, lang_selected: filteredLangSelected, segmentAnswers: filteredSegmentAnswers, teacherId: teacherId, taskId: taskId, total_time: timerData.hours * 3600 + timerData.minutes * 60 + timerData.seconds, }; try { const response = await axios.post(Constants.API_PATH + '/teacher_answers', userData); // console.log('Answer saved:', response.data); } catch (error) { console.error('Error saving answer:', error); } }; const handleSaveNext = async () => { if (saving) return; // Prevent multiple clicks setSaving(true); // Save the current question's answer await saveAnswer(); // Navigate to the next question sequentially let nextQuestion = currentQuestion + 1; while (nextQuestion < questions.length && attemptLaterQuestions.includes(questions[nextQuestion].id)) { // console.log(`Skipping question ${questions[nextQuestion]?.id} (marked as "Attempt Later").`); nextQuestion++; } if (nextQuestion < questions.length) { setCurrentQuestion(nextQuestion); // Move to the next valid question setProgress(((nextQuestion + 1) / questions.length) * 100); // Update progress setIsAnswerSelected(false); // Reset answer selection } else { // console.log("Reached the last question or no more valid questions."); // Optionally show a message or disable navigation } setSaving(false); }; const handleLanguageChange = (e) => setSelectedLanguage(e.target.value); const handleFormData = (value, question, optionIndex) => { let answers = { ...userAnswers, [question.id]: value }; setUserAnswers((prevAnswers) => ({ ...prevAnswers, [question.id]: value, })); setSaveUserAnswers(() => ({ [question.id]: value, })); // console.log("ff",userAnswers) setQuesOptionSelected((prevAnswers) => ({ ...prevAnswers, [question.id]: optionIndex, })); setQuesLanguageSelected((prevAnswers) => ({ ...prevAnswers, [question.id]: selectedLanguage, })); setSegmentAnswers((prevAnswers) => ({ ...prevAnswers, [question.id]: question.segment_id, })); setIsAnswerSelected(true); // Enable the "Save & Next" button //let key = "userAnswersKey"; //const storedValue = localStorage.getItem(key); localStorage.setItem(localStorageKey, JSON.stringify(answers)); }; const isAnswerChecked = (questionId, option) => { // console.log("IsAnswerChecked"); let result = userAnswers[questionId] === option; if (!result) { // If not found in state, check in localStorage const localStorageAnswers = JSON.parse(localStorage.getItem(localStorageKey)) || {}; result = localStorageAnswers[questionId] === option; } // console.log("result", result); return result; } const autoSave = async () => { // Perform auto-save logic here // ... // stopRecording(); // dispatch({type:'RECORDING_STOP',payload:true}); const remainingTimeInSeconds = timerData.hours * 3600 + timerData.minutes * 60 + timerData.seconds; // console.log("Remaining time left in seconds : ",remainingTimeInSeconds); let userData = { user_answers: userAnswers, options_selected: quesOptionSelected, lang_selected: quesLanguageSelected, segmentAnswers: segmentAnswers, teacherId: teacherId, taskId: taskId, total_time: remainingTimeInSeconds, }; try { // Hit the teacher_answers API when the timer reaches 0 const response = await axios.post(Constants.API_PATH + '/teacher_answers', userData); // console.log("Auto-save triggered. Values: ", response.data); //Uploading recording.. //uncomment this line and update the uploadRecoding function with correct api // let result = await uploadRecording(teacherId,taskId); Swal.fire({ icon: 'info', title: 'Time is up. ', text: 'Your exam has been automatically submitted.', confirmButtonText: 'OK', }); // navigate('/home/liveresult'); window.location.href="/home/liveresult" } catch (error) { console.error("Auto-save Error:", error); } // Show a popup when the timer reaches 0 }; const handleTimeChange = useCallback((data) => { // // console.log("Timer data :",data); setTimerData(data); }, []); // Add dependencies here if they exist const shuffleArray = (array) => { const shuffled = [...array]; for (let i = shuffled.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; } return shuffled; }; const handleAttemptLater = (question) => { // console.log("Attempt Later clicked for question:", question.id); // Add or remove the question from the "Attempt Later" list setAttemptLaterQuestions((prev) => { if (prev.includes(question.id)) { // console.log(`Removing question ${question.id} from "Attempt Later".`); return prev.filter((id) => id !== question.id); // Remove from "Attempt Later" } else { // console.log(`Adding question ${question.id} to "Attempt Later".`); return [...prev, question.id]; // Add to "Attempt Later" } }); // Clear the selected option for the question setUserAnswers((prevAnswers) => { const { [question.id]: omitted, ...rest } = prevAnswers; return rest; // Remove the selected answer }); setQuesOptionSelected((prevOptions) => { const { [question.id]: omitted, ...rest } = prevOptions; return rest; // Remove the selected option }); setQuesLanguageSelected((prevLanguages) => { const { [question.id]: omitted, ...rest } = prevLanguages; return rest; // Remove the selected language }); setSegmentAnswers((prevSegments) => { const { [question.id]: omitted, ...rest } = prevSegments; return rest; // Remove the selected segment }); setIsAnswerSelected(false); // Reset answer selection state // Navigate to the next valid question let nextQuestion = currentQuestion + 1; while (nextQuestion < questions.length && attemptLaterQuestions.includes(questions[nextQuestion].id)) { // console.log(`Skipping question ${questions[nextQuestion]?.id} (marked as "Attempt Later").`); nextQuestion++; } if (nextQuestion < questions.length) { setCurrentQuestion(nextQuestion); // Move to the next valid question setProgress(((nextQuestion + 1) / questions.length) * 100); // Update progress } else { // console.log("Reached the last question or no more valid questions."); // Optionally show a message or disable navigation } }; const handleNext = () => { // console.log("Navigating to next question. Current question:", currentQuestion); let nextQuestion = currentQuestion + 1; // Skip questions marked as "Attempt Later" while (nextQuestion < questions.length && attemptLaterQuestions.includes(questions[nextQuestion].id)) { // console.log(`Skipping question ${questions[nextQuestion].id} (marked as "Attempt Later").`); nextQuestion++; } if (nextQuestion < questions.length) { // console.log(`Navigating to question ${questions[nextQuestion].id}.`); setCurrentQuestion(nextQuestion); // Move to the next valid question setProgress(((nextQuestion + 1) / questions.length) * 100); // Update progress setIsAnswerSelected(false); // Reset answer selection } else { // console.log("No more questions to navigate to."); // Optionally show a message or disable navigation } }; // const onSave = (values) => { const onSave = async () => { // dispatch({type:'RECORDING_STOP',payload:true}); const remainingTimeInSeconds = timerData.hours * 3600 + timerData.minutes * 60 + timerData.seconds; // console.log("Remaining time left in seconds : ",totalTimerTime); let userData = { user_answers: saveuserAnswers, options_selected: quesOptionSelected, lang_selected: quesLanguageSelected, segmentAnswers: segmentAnswers, teacherId: teacherId, taskId: taskId, total_time: remainingTimeInSeconds } try { const response = await axios.post(Constants.API_PATH + '/teacher_answers', userData); Swal.fire({ icon: 'success', title: 'Exam Submitted!', text: 'Congratulations, and best of luck with your results', confirmButtonText: 'OK', }); setExamInProgress(false); // Redirect to the result page navigate('/home/liveresult'); } catch (error) { console.error("Error:", error); Swal.fire({ icon: 'error', title: 'Please wait!', text: 'Your responses are safe, and the auto-submit process is ongoing', confirmButtonText: 'OK', }); } }; // Show popup when the component mounts useEffect(() => { const popupTimeout = setTimeout(() => { Swal.fire({ icon: 'info', title: 'Important Notice', text: 'If you are stuck at any point, please press (Ctrl/Command + Shift + R) Rest assured, your progress is securely saved with us.', confirmButtonText: 'OK', }); }, 1000); // Adjust the timeout as needed return () => { clearTimeout(popupTimeout); }; }, []); return ( <> {showCopyNotAllowedModal && <CopyNotAllowedModal />} <div className="fullscreen-content ntoexam2024 exam2"> <Grid className='teacher-exam-count' style={{ width: "88%", marginLeft: "80px", }}> <Grid> <div className='sttar-bars' > <p style={{ color: "#fff", fontSize: "26px", textAlign: "left" }}>STTAR National Teachers' Olympiad</p> </div> <div className='row'> <div className='col-md-8 leftdiv'> <Card className='teacher-exam1'> <div className='row'> <div className='col-xs-2'> <span id="select" > <select className='selectclass' required name="" label="Select exam date" placeholder="Select Exam Date" onChange={handleLanguageChange}> <option value="english">English</option> <option value="hindi">Hindi</option> </select> </span> </div> <div className='col-xs-3'> {questions.length > 0 ? ( <div> <p> <b className='question user-select-none' style={{ textAlign: "left", paddingLeft: "10px" }}>Question: <span style={{ fontWeight: "700" }}>{currentQuestion + 1}/{questions.length}</span></b> </p> </div> ) : null} </div> <div className='col-md-3'> <div className='progress' style={{ color: '#b4ae21', fontSize: '16px', fontWeight: '700' }}> {/* {progress}% */} <div className='pbar' style={{ width: '100%', background: 'lightgray' }}> <div style={{ width: `${progress}%`, background: '#32adb4', height: '5px', }} ></div> </div> </div> {/* new tracher */} <div className="timer"> <div id="countdown-timer"> {totalTimerTime != null ? <MyTimer expiryTimestamp={totalTimerTime} onExpire={autoSave} onTimeChange={handleTimeChange} /> : <div></div> } </div> </div> </div> <div className="col-md-4 timer2"> </div> </div> <Grid item xs={12} className='currentQuestion'> {questions.length > 0 && currentQuestion < questions.length && ( <div> <div className='sttar-segment-name'> <span className='uclass' level={2} style={{ color: "#1742f1", fontSize: "18px" }}> <span style={{ color: "#144684", textTransform: "uppercase" }}>SEGMENT: {questions[currentQuestion].segment_name}</span></span> </div> <div key={questions[currentQuestion].id} style={{ padding: "20px" }}> {/* <span><b>Question : {currentQuestion+1}. </b> <h5>{questions[currentQuestion].name} ?</h5></span> <span><h5>{questions[currentQuestion].name_hindi} ?</h5> </span><br/> */} <br /> <b className='pq' style={{ width: "200px" }} >Question : {currentQuestion + 1} </b> <h5> {selectedLanguage === "english" ? questions[currentQuestion].name : questions[currentQuestion].name_hindi} ? </h5> <br /> <div id="question"> <input id="choices-0" type="radio" name="choices" value={ selectedLanguage === "english" ? questions[currentQuestion].option_1 : questions[currentQuestion].hindi_option_1 } checked={isAnswerChecked(questions[currentQuestion].id, questions[currentQuestion].option_1) || isAnswerChecked(questions[currentQuestion].id, questions[currentQuestion].hindi_option_1)} onChange={(e) => handleFormData(e.target.value, questions[currentQuestion], 1)} required /> <label for="choices-0"> <span className="exam-span-border">A </span> <span className="exam-span-text"> {selectedLanguage === "english" ? questions[currentQuestion].option_1 : questions[currentQuestion].hindi_option_1} </span> </label> <input id="choices-1" type="radio" name="choices" value={ selectedLanguage === "english" ? questions[currentQuestion].option_2 : questions[currentQuestion].hindi_option_2 } checked={isAnswerChecked(questions[currentQuestion].id, questions[currentQuestion].option_2) || isAnswerChecked(questions[currentQuestion].id, questions[currentQuestion].hindi_option_2)} onChange={(e) => handleFormData(e.target.value, questions[currentQuestion], 2)} required /> <label for="choices-1"> <span className="exam-span-border">B </span> <span className="exam-span-text"> {selectedLanguage === "english" ? questions[currentQuestion].option_2 : questions[currentQuestion].hindi_option_2} </span> </label> <input id="choices-3" type="radio" name="choices" value={ selectedLanguage === "english" ? questions[currentQuestion].option_3 : questions[currentQuestion].hindi_option_3 } checked={isAnswerChecked(questions[currentQuestion].id, questions[currentQuestion].option_3) || isAnswerChecked(questions[currentQuestion].id, questions[currentQuestion].hindi_option_3)} onChange={(e) => handleFormData(e.target.value, questions[currentQuestion], 3)} required /> <label for="choices-3"> <span className="exam-span-border">C</span> <span className="exam-span-text"> {selectedLanguage === "english" ? questions[currentQuestion].option_3 : questions[currentQuestion].hindi_option_3} </span> </label> <input id="choices-4" type="radio" name="choices" value={ selectedLanguage === "english" ? questions[currentQuestion].option_4 : questions[currentQuestion].hindi_option_4 } checked={isAnswerChecked(questions[currentQuestion].id, questions[currentQuestion].option_4) || isAnswerChecked(questions[currentQuestion].id, questions[currentQuestion].hindi_option_4)} onChange={(e) => handleFormData(e.target.value, questions[currentQuestion], 4)} required /> <label for="choices-4"> <span className="exam-span-border">D </span> <span className="exam-span-text"> {selectedLanguage === "english" ? questions[currentQuestion].option_4 : questions[currentQuestion].hindi_option_4} </span> </label> </div> </div> <Button type="primary" className='pclass join-today-button4' disabled={currentQuestion === 0} onClick={handlePrevious} style={{ border: '2px solid #2a87ae', marginLeft: "12px", marginBottom: "20px" }} > Previous </Button> <Button type="primary" className="pclass join-today-button4" onClick={() => handleAttemptLater(questions[currentQuestion])} variant={attemptLaterQuestions.includes(questions[currentQuestion]?.id) ? "contained" : "outlined"} color={attemptLaterQuestions.includes(questions[currentQuestion]?.id) ? "secondary" : "primary"} style={{ border: attemptLaterQuestions.includes(questions[currentQuestion]?.id) ? '2px solid #f44336' // Red for "Unmark Attempt Later" : '2px solid #2a87ae', // Blue for "Attempt Later" marginLeft: "12px", marginBottom: "20px", }} > {attemptLaterQuestions.includes(questions[currentQuestion]?.id) ? "Unmark Attempt Later" : "Mark as Attempt Later"} </Button> {currentQuestion < questions.length - 1 ? ( <Button className="nestclass join-today-button3" type="primary" onClick={async () => { await saveAnswer(); // Save the answer when clicked handleNext(); // Move to the next question }} // disabled={!isAnswerSelected} // Enable only if an answer is selected style={{ border: '2px solid #2a87ae', marginLeft: "12px", marginBottom: "20px" }} > Save & Next </Button> ) : ( <Confirm className="conferm" title="Confirm" description="You will not be able to come back once you confirm final submit" > {(confirm) => ( <Button className="save button join-today-button3 finalbtn" type="btn btn primary" onClick={confirm(onSave)} style={{ border: '2px solid #2a87ae', marginLeft: "12px", marginBottom: "20px" }} > Submit </Button> )} </Confirm> )} </div> )} </Grid> </Card> </div> <div className='col-md-4 rightdiv'> <ProgressTracker questions={questions} count={currentQuestion} setCount={setCurrentQuestion} saveAnswer={saveAnswer} // Pass saveAnswer as a prop userAnswers={userAnswers} // Replace with the actual answer data marksForReview={marksForReview} /> </div> <div> <br /> <br /> </div> </div> </Grid> </Grid> </div> {/* </FullScreen> */} </> ); } export default TeacherExam;
Editor is loading...
Leave a Comment