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 | 3x 31x 31x 31x 31x 3x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 8x 8x 8x 8x 9x 2x 20x 23x 23x 23x 23x 23x 23x 23x 23x 20x 20x 23x 20x 20x 20x 20x 20x 23x 23x 23x 23x 4x 4x 5x 4x 23x 23x 23x 23x 23x 23x 23x 20x 9x 9x 9x 9x 32x 20x 22x | import React, { useEffect, useRef, useState } from "react";
import { Box, Paper } from "@mui/material";
import { useTheme } from "@mui/material/styles";
import tinyMCEUtility from "@/utils/helpers/tinyMCEUtility";
import { useDispatch, useSelector } from "react-redux";
import { _addMyAnswer } from "@/store/slices/student/StudentQuestionPage";
import { sanitizeRichText } from "@/utils/helpers/sanitizeHtml";
import {
STUDENT_QUESTION_FONT_SIZE,
dropZoneColors,
neutralContentBg,
questionContentBg,
} from "../studentQuestionSurfaces";
import "../StudentQuestion.scss";
const unwrapBlock = (html) => {
const el = document.createElement("div");
el.innerHTML = html;
Iif (el.children.length === 1 && el.children[0].tagName === "P") {
return el.children[0].innerHTML;
}
return html;
};
const DragAndDrop = ({ question }) => {
const theme = useTheme();
const dispatch = useDispatch();
const { regexBlank } = tinyMCEUtility();
const { myAnswers } = useSelector((state) => state.StudentQuestionPage);
const existingAnswer = myAnswers?.data?.find((item) => item.questionId === question._id);
const [isBlanks, setBlanks] = useState(existingAnswer?.answer || []);
const [dragOverId, setDragOverId] = useState(null);
const containerRef = useRef(null);
const handleDragStart = (e, value) => {
e.dataTransfer.setData("text/plain", value);
};
const clearBlank = (index) => {
setBlanks((prev) => prev.map((blank) => (blank.id === index ? { ...blank, answer: "" } : blank)));
};
// Sync answer to Redux. Include question._id so switching questions (paginated
// layout) doesn't dispatch the new blanks against the previous question id.
useEffect(() => {
dispatch(
_addMyAnswer({
questionId: question._id,
questionType: "drag-and-drop",
answer: isBlanks,
})
);
}, [isBlanks, question._id]);
// Rebuild blanks FRESH for the current question, restoring THIS question's
// saved answer by position. Keyed on question._id and NOT carrying over the
// previous blanks: the old `[...prev]` append-only init leaked a previous
// question's filled blanks into the next one — which surfaced as "questions
// with identical answer choices inherit the selected answer from another
// question" (the bled choice text is a valid chip only when choices match).
// (EI-2906 / EI-TC-4552)
useEffect(() => {
const parts = question?.question?.split(regexBlank) ?? [];
const blanksLength = Math.max(parts.length - 1, 0);
const saved = myAnswers?.data?.find((item) => item.questionId === question._id)?.answer || [];
setBlanks(
Array.from({ length: blanksLength }, (_, i) => ({
id: i,
answer: saved.find((b) => b.id === i)?.answer ?? "",
}))
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [question._id]);
const buildDropZoneHTML = (index) => {
const blank = isBlanks.find((b) => b.id === index);
const hasAnswer = !!blank?.answer;
const answerContent = hasAnswer ? unwrapBlock(blank.answer) : "Drop here";
const isDragOver = dragOverId === index;
const {
bg: bgColor,
border: borderColor,
text: textColor,
} = dropZoneColors(theme, {
dragOver: isDragOver,
filled: hasAnswer,
});
const borderStyle = hasAnswer ? "solid" : "dashed";
const clearBtn = hasAnswer
? `<span data-clear-index="${index}" style="position:absolute;top:-10px;right:-10px;` +
`display:inline-flex;align-items:center;justify-content:center;` +
`width:20px;height:20px;border-radius:50%;background-color:#d32f2f;` +
`color:white;font-size:12px;cursor:pointer;line-height:1;z-index:1;">✕</span>`
: "";
return (
// No min-width/min-height — the box hugs the dropped word/phrase, same
// as the embedded-multiple-choice mark style (tinyMCEUtility's
// buildEmbeddedChoiceHTML / EmbeddedMultipleChoice.jsx), instead of
// forcing every blank to a fixed 100x36 box regardless of content.
`<span data-drop-index="${index}" style="position:relative;display:inline-block;` +
`vertical-align:middle;padding:1px 3px;margin:4px 8px;` +
`border:2px ${borderStyle} ${borderColor};border-radius:3px;background-color:${bgColor};` +
`white-space:nowrap;line-height:normal;font-size:inherit;` +
`font-weight:${hasAnswer ? 500 : 400};color:${textColor};cursor:pointer;transition:all 0.2s ease;">` +
`${answerContent}${clearBtn}` +
`</span>`
);
};
// Replace __blank__ markers with interactive drop zone spans in the full HTML string.
// This preserves paragraph structure and all inline formatting from TinyMCE.
const buildContent = () => {
let blankIndex = 0;
return question.question.replace(regexBlank, () => buildDropZoneHTML(blankIndex++));
};
// Attach drag/drop DOM listeners after every render so they stay in sync with isBlanks state.
useEffect(() => {
const container = containerRef.current;
Iif (!container) return;
const cleanup = [];
container.querySelectorAll("span[data-drop-index]").forEach((zone) => {
const index = parseInt(zone.getAttribute("data-drop-index"), 10);
const onDragOver = (e) => {
e.preventDefault();
setDragOverId(index);
};
const onDragLeave = () => setDragOverId(null);
const onDrop = (e) => {
e.preventDefault();
const value = e.dataTransfer.getData("text/plain");
setBlanks((prev) => prev.map((blank) => (blank.id === index ? { ...blank, answer: value } : blank)));
setDragOverId(null);
};
zone.addEventListener("dragover", onDragOver);
zone.addEventListener("dragleave", onDragLeave);
zone.addEventListener("drop", onDrop);
cleanup.push(() => {
zone.removeEventListener("dragover", onDragOver);
zone.removeEventListener("dragleave", onDragLeave);
zone.removeEventListener("drop", onDrop);
});
});
container.querySelectorAll("span[data-clear-index]").forEach((btn) => {
const index = parseInt(btn.getAttribute("data-clear-index"), 10);
const onClick = (e) => {
e.stopPropagation();
clearBlank(index);
};
btn.addEventListener("click", onClick);
cleanup.push(() => btn.removeEventListener("click", onClick));
});
return () => cleanup.forEach((fn) => fn());
});
return (
<Box className="student-drag-drop">
{/* dangerouslySetInnerHTML renders the full HTML at once so paragraph structure,
line breaks, and inline formatting are preserved exactly as authored in TinyMCE.
The sx block re-applies browser UA styles killed by the global * CSS reset in index.scss. */}
<Paper
ref={containerRef}
variant="outlined"
className="student-question-content student-drag-drop-question"
dangerouslySetInnerHTML={{ __html: sanitizeRichText(buildContent()) }}
sx={{
display: "block !important",
bgcolor: questionContentBg(theme),
fontSize: STUDENT_QUESTION_FONT_SIZE,
lineHeight: 2,
fontWeight: "normal",
"& p": { margin: 0, padding: 0 },
"& u": { textDecoration: "underline" },
"& s, & del": { textDecoration: "line-through" },
"& strong, & b": { fontWeight: "bold" },
"& em, & i": { fontStyle: "italic" },
"& sub": { verticalAlign: "sub", fontSize: "smaller" },
"& sup": { verticalAlign: "super", fontSize: "smaller" },
"& ul": { listStyle: "disc", paddingLeft: "2em" },
"& ol": { listStyle: "decimal", paddingLeft: "2em" },
"& li": { display: "list-item" },
"& img": { maxWidth: "100%", height: "auto", verticalAlign: "middle" },
}}
/>
<Paper
elevation={0}
className="student-drag-choices"
sx={{ bgcolor: neutralContentBg(theme), fontSize: STUDENT_QUESTION_FONT_SIZE }}
>
{(question.choices ?? []).map((choiceObj, index) => (
<Box
key={index}
className="student-drag-choice"
draggable
onDragStart={(e) => handleDragStart(e, choiceObj.text)}
>
<Box
dangerouslySetInnerHTML={{ __html: sanitizeRichText(unwrapBlock(choiceObj.text)) }}
sx={{
"& p": { margin: 0, padding: 0 },
"& u": { textDecoration: "underline" },
"& s, & del": { textDecoration: "line-through" },
"& strong, & b": { fontWeight: "bold" },
"& em, & i": { fontStyle: "italic" },
}}
/>
</Box>
))}
</Paper>
</Box>
);
};
export default DragAndDrop;
|