All files / src/utils/components/question-bank/question-content/drop-down-menu DropdownMenuV2.jsx

97.36% Statements 74/76
90.47% Branches 38/42
95.23% Functions 20/21
98.5% Lines 66/67

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          6x 415x 415x 415x   415x 534x 534x 534x 534x 534x           534x 534x       534x                       415x 415x 534x     415x 415x 415x 415x   415x 534x 534x 12x 12x                   12x         534x 534x     415x 2x     534x                                 415x 40x 40x 40x 27x 27x 22x 22x 29x   22x   5x 1x   4x           415x 40x 40x 40x 27x 27x 22x 22x 29x   22x   5x 1x   4x       415x 415x 415x   415x                                                                                         21x 21x         9x 12x   9x                                                
import React, { useEffect, useRef, useState } from "react";
import { Box, MenuItem, Popover } from "@mui/material";
import tinyMCEUtility from "@/utils/helpers/tinyMCEUtility";
import { sanitizeRichText } from "@/utils/helpers/sanitizeHtml";
 
const DropdownMenu = ({ isQuestionText, isChoices, setChoices, isBlanks, setBlanks }) => {
    const { regexMenuHere } = tinyMCEUtility();
    const containerRef = useRef(null);
    const [openDropdown, setOpenDropdown] = useState(null); // { index, anchorPosition }
 
    const buildTriggerHTML = (index) => {
        const answerText = isBlanks[index]?.answer || "";
        const items = isChoices[index]?.items || [];
        const borderColor = answerText ? "#2e7d32" : "#bdbdbd";
        const bgColor = answerText ? "#e8f5e9" : "#fff";
        const textColor = answerText ? "#2e7d32" : "#9e9e9e";
        // Match by the choice's raw HTML (isBlanks[i].answer now stores that
        // verbatim — see the Popover onClick below), not tinyMCEtoString'd
        // plain text: textContent collapses MathLive's rendered math markup
        // (convertLatexToMarkup output) into garbled/lossy text, so a math
        // formula choice could never be found again by that comparison.
        const selectedItem = answerText ? items.find((c) => c.text === answerText) : null;
        const displayContent = selectedItem
            ? `<span style="color:#2e7d32;">${selectedItem.text}</span>`
            : `<span style="color:#9e9e9e;">Select answer...</span>`;
 
        return (
            `<button data-menu-index="${index}" ` +
            `style="display:inline-flex;align-items:center;gap:4px;` +
            `padding:5px 8px;border:1px solid ${borderColor};` +
            `border-radius:4px;background-color:${bgColor};font-size:inherit;cursor:pointer;` +
            `text-align:left;color:${textColor};vertical-align:middle;margin:0 4px;">` +
            `<span style="flex:1;">${displayContent}</span>` +
            `<span style="font-size:18px;color:#666;flex-shrink:0;">▾</span>` +
            `</button>`
        );
    };
 
    const buildContent = () => {
        let blankIndex = 0;
        return isQuestionText.replace(regexMenuHere, () => buildTriggerHTML(blankIndex++));
    };
 
    useEffect(() => {
        const container = containerRef.current;
        Iif (!container) return;
        const cleanup = [];
 
        container.querySelectorAll("button[data-menu-index]").forEach((btn) => {
            const index = parseInt(btn.getAttribute("data-menu-index"), 10);
            const onClick = (e) => {
                e.stopPropagation();
                const rect = btn.getBoundingClientRect();
                // Popover's `anchorPosition` is consumed the same way its
                // `anchorEl` mode computes a position — straight off
                // getBoundingClientRect(), with no scroll offset added (see
                // @mui/material/Popover's getAnchorOffset/getPositioningStyle).
                // Adding window.scrollY/scrollX here double-counted the
                // scroll: at the top of the page it happened to look right
                // (scrollY was 0), but the menu drifted further down/right
                // than the trigger button the more the page had been
                // scrolled when it was clicked.
                setOpenDropdown({
                    index,
                    anchorPosition: { top: rect.bottom, left: rect.left },
                });
            };
            btn.addEventListener("click", onClick);
            cleanup.push(() => btn.removeEventListener("click", onClick));
        });
 
        if (window.MathJax?.typesetPromise) {
            window.MathJax.typesetPromise([container]).catch(() => {});
        }
 
        return () => cleanup.forEach((fn) => fn());
    });
 
    // Initialize isBlanks entries for new blanks, and drop entries for blanks
    // that are no longer in the question text.
    //
    // This used to only ever grow the array (append new blanks, keep the
    // rest as-is), never shrink it. If a teacher removed a __blank__ marker
    // from the question text, the trailing entry it left behind was never
    // pruned: it stays in the saved correctAnswer.answers with a real answer,
    // but DropDownMenu.jsx (the student-facing renderer) only builds one
    // <select> per __blank__ actually present in the text, so that entry can
    // never be selected. The id-map comparison in the backend's
    // is_answer_correct requires every correct-answer id to be matched, so
    // that unreachable entry made the WHOLE question permanently unscoreable
    // — every student's submission failed it, with nothing in the editor UI
    // hinting why.
    useEffect(() => {
        const parts = isQuestionText.split(regexMenuHere);
        const blankCount = parts.length - 1;
        setBlanks((prev) => {
            const current = prev || [];
            if (blankCount > current.length) {
                const additions = [];
                for (let index = current.length; index < blankCount; index++) {
                    additions.push({ id: index, answer: "" });
                }
                return [...current, ...additions];
            }
            if (blankCount < current.length) {
                return current.slice(0, blankCount);
            }
            return current;
        });
    }, [isQuestionText]);
 
    // Initialize isChoices entries for new blanks, and drop entries for
    // blanks that are no longer in the question text (see isBlanks above).
    useEffect(() => {
        const parts = isQuestionText.split(regexMenuHere);
        const blankCount = parts.length - 1;
        setChoices((prev) => {
            const current = prev || [];
            if (blankCount > current.length) {
                const additions = [];
                for (let index = current.length; index < blankCount; index++) {
                    additions.push({ id: index, items: [] });
                }
                return [...current, ...additions];
            }
            if (blankCount < current.length) {
                return current.slice(0, blankCount);
            }
            return current;
        });
    }, [isQuestionText]);
 
    const openIndex = openDropdown?.index ?? null;
    const currentItems = openIndex !== null ? isChoices[openIndex]?.items || [] : [];
    const currentAnswer = openIndex !== null ? isBlanks[openIndex]?.answer || "" : "";
 
    return (
        <>
            <Box
                ref={containerRef}
                className="dropdown-menu-question"
                dangerouslySetInnerHTML={{ __html: sanitizeRichText(buildContent()) }}
                sx={{
                    width: "100%",
                    fontSize: "20px",
                    lineHeight: 2,
                    cursor: "default",
                    userSelect: "none",
                    "& p, & h1, & h2, & h3, & h4, & h5, & h6": {
                        margin: 0,
                        padding: 0,
                        lineHeight: "inherit",
                        fontSize: "inherit",
                        fontWeight: "inherit",
                    },
                    "& s, & del": { textDecoration: "line-through" },
                    "& button[data-menu-index]": {
                        userSelect: "none",
                        "& p": { margin: 0, padding: 0 },
                    },
                }}
            />
            <Popover
                open={openDropdown !== null}
                onClose={() => setOpenDropdown(null)}
                anchorReference="anchorPosition"
                anchorPosition={openDropdown?.anchorPosition}
                transformOrigin={{ vertical: "top", horizontal: "left" }}
                disableAutoFocus
                disableEnforceFocus
                PaperProps={{ sx: { minWidth: 160, py: 0.5 } }}
            >
                {currentItems.map((choice, idx) => {
                    // Store the choice's raw HTML verbatim as the correct answer — the
                    // SAME value the student's <option value> submits for this choice
                    // (DropDownMenu.jsx / GroupDropdownAnswer.jsx) — instead of a
                    // tinyMCEtoString'd plain-text conversion, which is lossy for a math
                    // formula choice (MathLive's rendered markup doesn't collapse back to
                    // its LaTeX source via textContent). The backend normalizes both sides
                    // the same way before comparing (see answer_checking.py), so verbatim
                    // HTML on both sides is what makes that normalization actually work.
                    const isSelected = currentAnswer === choice.text;
                    return (
                        <MenuItem
                            key={idx}
                            selected={isSelected}
                            onClick={() => {
                                setBlanks((prev) =>
                                    prev.map((item, i) => (i === openIndex ? { ...item, answer: choice.text } : item))
                                );
                                setOpenDropdown(null);
                            }}
                            sx={{
                                py: 0.5,
                                "&.Mui-selected": { backgroundColor: "success.light" },
                                "&.Mui-selected:hover": { backgroundColor: "success.light" },
                            }}
                        >
                            <Box
                                dangerouslySetInnerHTML={{ __html: sanitizeRichText(choice.text) }}
                                sx={{
                                    "& p": { margin: 0, padding: 0 },
                                    "& s, & del": { textDecoration: "line-through" },
                                }}
                            />
                        </MenuItem>
                    );
                })}
            </Popover>
        </>
    );
};
 
export default DropdownMenu;