All files / src/app/student-page/page/assignments/take-assignment/question-list/single-stimulus SingleStimulus.jsx

70.21% Statements 33/47
47.19% Branches 42/89
53.33% Functions 8/15
76.92% Lines 30/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263                              130x   5x                 5x                             5x 4x 4x   4x 4x 4x   4x 4x         4x 2x     4x 4x 4x   4x               4x                     4x                           4x   4x   4x 8x             8x     8x     4x                           8x 8x 8x         1x                                                                                                                                                                                                                                                              
import { Box, Chip, Paper, Stack, Typography } from "@mui/material";
import { useTheme } from "@mui/material/styles";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import ReadOnlyMathEditor from "@/utils/components/TinyMCETextEditorReadOnly";
import TinyMCEAnswerEditor from "@/utils/components/TinyMCEAnswerEditor";
import GroupGraphAnswer from "@/utils/components/question-bank/question-content/utils/GroupGraphAnswer";
import GroupDropdownAnswer from "../GroupDropdownAnswer";
import GroupDragAndDropAnswer from "../GroupDragAndDropAnswer";
import { _addMyAnswer } from "@/store/slices/student/StudentQuestionPage";
import StudentChoiceRow from "../StudentChoiceRow";
import { STUDENT_QUESTION_FONT_SIZE, questionContentBg } from "../studentQuestionSurfaces";
import "../StudentQuestion.scss";
 
const letters = Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i));
 
const GROUP_TYPE_LABELS = {
    "multiple-choice": "Multiple Choice",
    checkbox: "Checkbox",
    "free-response": "Free Response",
    graph: "Graph",
    "drop-down": "Drop-down",
    "drag-and-drop": "Drag and Drop",
};
 
const formatGroupType = (type) => GROUP_TYPE_LABELS[type] ?? type;
 
/**
 * Student renderer for a Single-Stimulus question — one shared main
 * question (rendered once, above), then one group's own choices at a time.
 * Groups are NOT separate questions (see
 * docs/implementation/single-stimulus-questions.md): this single
 * component owns its own internal "Group X of N" navigation instead of the
 * outer take-assignment pagination advancing once per group.
 *
 * The combined answer for every group lives in ONE `_addMyAnswer` entry for
 * this question, shaped `{ [group_id]: <that group's own answer> }` — a
 * string for a "multiple-choice" group, an array of strings for "checkbox" —
 * so switching groups never touches another group's already-saved answer.
 */
const SingleStimulus = ({ question }) => {
    const theme = useTheme();
    const dispatch = useDispatch();
 
    const { myAnswers } = useSelector((state) => state.StudentQuestionPage);
    const currentAnswer = myAnswers?.data?.find((item) => item.questionId === question._id)?.answer;
    const answerByGroup = currentAnswer && typeof currentAnswer === "object" ? currentAnswer : {};
 
    const groups = Array.isArray(question.groups) ? question.groups : [];
    const [groupIndex, setGroupIndex] = useState(0);
 
    // Reset to the first group whenever the question itself changes — this
    // component is reused across question switches in the paginated layout,
    // same cross-question-bleed defense every sibling renderer uses. (EI-2906)
    useEffect(() => {
        setGroupIndex(0);
    }, [question._id]);
 
    const group = groups[groupIndex];
    const selectionMode = group?.type === "checkbox" ? "multiple" : "single";
    const groupAnswer = group ? answerByGroup[group.group_id] : undefined;
    const selectedValues =
        selectionMode === "multiple"
            ? Array.isArray(groupAnswer)
                ? groupAnswer
                : []
            : typeof groupAnswer === "string" && groupAnswer
              ? [groupAnswer]
              : [];
 
    const updateGroupAnswer = (newValue) => {
        if (!group) return;
        dispatch(
            _addMyAnswer({
                questionId: question._id,
                questionType: "single-stimulus",
                answer: { ...answerByGroup, [group.group_id]: newValue },
            })
        );
    };
 
    const handleChoiceClick = (choiceText) => {
        if (!group) return;
        const newValue =
            selectionMode === "single"
                ? selectedValues[0] === choiceText
                    ? ""
                    : choiceText
                : selectedValues.includes(choiceText)
                  ? selectedValues.filter((value) => value !== choiceText)
                  : [...selectedValues, choiceText];
 
        updateGroupAnswer(newValue);
    };
 
    const questionBg = questionContentBg(theme);
 
    Iif (!group) return null;
 
    const isGroupAnswered = (g) => {
        const value = answerByGroup[g.group_id];
        // Both "drop-down" and "drag-and-drop" groups always report the FULL
        // {id, answer} array for every blank (see GroupDropdownAnswer.jsx /
        // GroupDragAndDropAnswer.jsx), so — unlike checkbox, whose array only
        // ever contains actually-selected choices — a plain
        // `value.length > 0` would be true from the group's very first
        // interaction, even after every blank is cleared back to empty.
        Iif (g.type === "drop-down" || g.type === "drag-and-drop") {
            return Array.isArray(value) && value.some((v) => v?.answer);
        }
        return Array.isArray(value) ? value.length > 0 : Boolean(value);
    };
 
    return (
        <Box>
            <Paper variant="outlined" className="student-question-content" sx={{ bgcolor: questionBg }}>
                <Typography variant="h6">
                    <ReadOnlyMathEditor
                        content={question?.question}
                        backgroundColor={questionBg}
                        fontSize={STUDENT_QUESTION_FONT_SIZE}
                    />
                </Typography>
            </Paper>
 
            <Stack direction="row" spacing={1.5} flexWrap="wrap" sx={{ mb: 2, rowGap: 1.5 }}>
                {groups.map((g, index) => {
                    const isActive = index === groupIndex;
                    const answered = isGroupAnswered(g);
                    return (
                        <Box
                            key={g.group_id ?? index}
                            component="button"
                            type="button"
                            onClick={() => setGroupIndex(index)}
                            aria-pressed={isActive}
                            sx={{
                                display: "flex",
                                alignItems: "center",
                                gap: 0.75,
                                px: 1.5,
                                py: 0.75,
                                border: "2px solid",
                                borderColor: isActive ? "primary.main" : answered ? "success.main" : "divider",
                                borderRadius: 2,
                                bgcolor: isActive ? "primary.main" : "transparent",
                                color: isActive ? "primary.contrastText" : answered ? "success.main" : "text.secondary",
                                cursor: "pointer",
                                fontFamily: "inherit",
                                transition: "border-color 0.15s ease, background-color 0.15s ease",
                                "&:hover": {
                                    borderColor: isActive ? "primary.main" : "primary.main",
                                },
                            }}
                        >
                            {answered && !isActive ? (
                                <CheckCircleIcon sx={{ fontSize: 18 }} />
                            ) : (
                                <Box
                                    sx={{
                                        width: 20,
                                        height: 20,
                                        borderRadius: "50%",
                                        display: "flex",
                                        alignItems: "center",
                                        justifyContent: "center",
                                        fontSize: 12,
                                        fontWeight: 700,
                                        bgcolor: isActive ? "rgba(255,255,255,0.3)" : "action.selected",
                                        color: "inherit",
                                    }}
                                >
                                    {index + 1}
                                </Box>
                            )}
                            <Typography variant="body2" sx={{ fontWeight: 600, whiteSpace: "nowrap" }}>
                                Group {index + 1}
                            </Typography>
                        </Box>
                    );
                })}
            </Stack>
 
            <Box
                sx={{
                    display: "grid",
                    gridTemplateColumns: "1fr auto 1fr",
                    alignItems: "center",
                    mb: 1.5,
                }}
            >
                <Box />
                <Typography variant="subtitle2" color="text.secondary" sx={{ textAlign: "center" }}>
                    Group {groupIndex + 1} of {groups.length}
                </Typography>
                <Stack direction="row" spacing={1} justifyContent="flex-end">
                    <Chip label={formatGroupType(group.type)} size="small" variant="outlined" color="primary" />
                    <Chip
                        label={`${group.points ?? 1} ${(group.points ?? 1) > 1 ? "Points" : "Point"}`}
                        size="small"
                        variant="outlined"
                    />
                </Stack>
            </Box>
 
            {(group.type === "multiple-choice" || group.type === "checkbox") && (
                <Box className="student-choices-list">
                    {(group.choices || []).map((choice, index) => (
                        <StudentChoiceRow
                            key={choice.id ?? index}
                            letter={letters[index]}
                            text={choice.text}
                            isSelected={selectedValues.includes(choice.text)}
                            onClick={() => handleChoiceClick(choice.text)}
                        />
                    ))}
                </Box>
            )}
 
            {group.type === "free-response" && (
                <TinyMCEAnswerEditor
                    key={group.group_id}
                    content={typeof groupAnswer === "string" ? groupAnswer : ""}
                    onChange={updateGroupAnswer}
                    backgroundColor={questionBg}
                    fontSize={STUDENT_QUESTION_FONT_SIZE}
                />
            )}
 
            {group.type === "graph" && (
                <GroupGraphAnswer
                    key={group.group_id}
                    value={typeof groupAnswer === "string" ? groupAnswer : ""}
                    onChange={updateGroupAnswer}
                />
            )}
 
            {group.type === "drop-down" && (
                <GroupDropdownAnswer
                    key={group.group_id}
                    content={group.content}
                    choices={group.choices}
                    value={Array.isArray(groupAnswer) ? groupAnswer : undefined}
                    onChange={updateGroupAnswer}
                />
            )}
 
            {group.type === "drag-and-drop" && (
                <GroupDragAndDropAnswer
                    key={group.group_id}
                    content={group.content}
                    choices={group.choices}
                    value={Array.isArray(groupAnswer) ? groupAnswer : undefined}
                    onChange={updateGroupAnswer}
                />
            )}
        </Box>
    );
};
 
export default SingleStimulus;