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 | 4x 4x | import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { DrawingGraph, DrawingGraphModes, Graph2D } from "graph2d-react";
import { Box, Chip, Stack, Typography } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import ReadOnlyMathEditor from "@/utils/components/TinyMCETextEditorReadOnly";
import { questionStemTypographySx } from "@/utils/components/question-bank/question-display/utils/questionCardStyles";
import {
GRAPH2D_QUESTION_BANK_CANVAS_SIZE,
drawingGraphFrameSx,
} from "@/utils/components/question-bank/question-display/graph/graphConstants";
import {
normalizeGraphAnswerForImport,
parseGraphAxisBounds,
} from "@/utils/components/question-bank/question-display/graph/graphAnswerUtils";
import {
applyInteractiveDotLimits,
describeInteractiveDotLimitNote,
parseInteractiveDotLimitsFromQuestion,
resolveInteractiveDotsImport,
stampInteractiveDotLimits,
toStudentPromptGraph,
} from "@/utils/components/question-bank/question-display/interactive-dots/interactiveDotsUtils";
import { _addMyAnswer } from "@/store/slices/student/StudentQuestionPage";
import "../StudentQuestion.scss";
const CANVAS = GRAPH2D_QUESTION_BANK_CANVAS_SIZE;
/**
* Student take-assignment / teacher "view as student".
*
* Matches React-Graph-2D-Mongo InteractiveToggleDots: import the authored graph
* first (so interactive dots paint), then switch to toggle mode.
*
* When several Graph Multiple-Select questions share the page (layout-1), pass a
* shared `graphInstance` and sequential `graphId` (0, 1, 2…). Every canvas uses
* DOM ids `canvas${id}` / `embed-${id}` — reusing 0 blanks later graphs.
* graph2d-react also indexes `canvases[graphId]`, so ids must be sequential on
* that shared instance (hashed ids drop imports).
*/
const InteractiveDots = ({ question, graphId: graphIdProp, graphInstance: sharedInstance }) => {
const dispatch = useDispatch();
const containerRef = useRef(null);
const saveTimerRef = useRef(null);
const [ownedInstance] = useState(() => Graph2D());
const graphInstance = sharedInstance ?? ownedInstance;
const graphId = typeof graphIdProp === "number" && Number.isFinite(graphIdProp) ? graphIdProp : 0;
const [isReady, setIsReady] = useState(false);
const [activeCount, setActiveCount] = useState(0);
const currentAnswer = useSelector(
(state) =>
state.StudentQuestionPage.myAnswers?.data?.find((item) => item.questionId === question._id)?.answer || ""
);
const answerKey = useMemo(
() => normalizeGraphAnswerForImport(question?.correctAnswer?.answers),
[question?.correctAnswer?.answers]
);
const promptGraph = useMemo(() => toStudentPromptGraph(answerKey), [answerKey]);
const bounds = useMemo(() => parseGraphAxisBounds(answerKey), [answerKey]);
const limits = useMemo(() => parseInteractiveDotLimitsFromQuestion(question), [question]);
const refreshCount = useCallback(() => {
try {
setActiveCount(graphInstance.countActiveInteractiveDots?.(graphId) ?? 0);
} catch {
/* ignore */
}
}, [graphId, graphInstance]);
const importThenToggle = useCallback(
(saved) => {
let initial = resolveInteractiveDotsImport(saved, promptGraph, answerKey);
if (initial && (limits.min != null || limits.max != null)) {
initial = stampInteractiveDotLimits(initial, limits) || initial;
}
if (initial) {
graphInstance.importAnswer(initial, graphId);
}
graphInstance.setDrawingMode(DrawingGraphModes.TOGGLE_INTERACTIVE_DOT, graphId);
applyInteractiveDotLimits(graphInstance, graphId, limits);
refreshCount();
},
[answerKey, graphId, graphInstance, limits, promptGraph, refreshCount]
);
const autoSave = useCallback(() => {
if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
saveTimerRef.current = setTimeout(() => {
try {
const graphAnswer = graphInstance.getCanvasAnswerObjectToString(graphId);
if (graphAnswer && graphAnswer.trim() !== "") {
dispatch(
_addMyAnswer({
questionId: question._id,
questionType: "graph-multiple-select",
answer: graphAnswer,
})
);
}
refreshCount();
} catch {
/* canvas may not be mounted */
}
}, 300);
}, [dispatch, graphId, graphInstance, question._id, refreshCount]);
const handleGraphReady = useCallback(() => {
setIsReady(true);
try {
importThenToggle(currentAnswer);
} catch (e) {
console.warn("InteractiveDots student import failed:", e);
}
}, [currentAnswer, importThenToggle]);
useEffect(() => {
const container = containerRef.current;
if (!container) return undefined;
const onInteract = () => autoSave();
container.addEventListener("mouseup", onInteract);
container.addEventListener("touchend", onInteract);
return () => {
container.removeEventListener("mouseup", onInteract);
container.removeEventListener("touchend", onInteract);
if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
};
}, [autoSave]);
useEffect(() => {
if (!isReady) return undefined;
try {
importThenToggle(currentAnswer);
} catch {
/* ignore */
}
const retry = setTimeout(() => {
try {
importThenToggle(currentAnswer);
} catch {
/* canvas may still be wiring */
}
}, 100);
return () => clearTimeout(retry);
// Re-import when the question or authored range changes. Do not depend
// on currentAnswer — autosave would wipe the canvas mid-toggle.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isReady, question._id, graphId, bounds.xMin, bounds.xMax, bounds.yMin, bounds.yMax]);
const limitNote = describeInteractiveDotLimitNote(limits);
const limitsUnmet =
(limits.min != null && activeCount < limits.min) || (limits.max != null && activeCount > limits.max);
return (
<Box className="student-graph-multiple-select" ref={containerRef}>
<Box sx={{ ...questionStemTypographySx, mb: 2 }}>
<ReadOnlyMathEditor content={question.question} />
</Box>
<Typography
variant="body2"
color={limitsUnmet ? "warning.main" : "text.secondary"}
sx={{ mb: 1 }}
>
{limitNote}
</Typography>
<Stack direction="row" spacing={1} sx={{ mb: 1.5 }} flexWrap="wrap" useFlexGap>
<Chip
size="small"
label={`${activeCount} active`}
color={limitsUnmet ? "warning" : "primary"}
variant="outlined"
/>
<Typography variant="caption" color="text.secondary" sx={{ alignSelf: "center" }}>
Click a dot to turn it on or off.
</Typography>
</Stack>
<Box sx={drawingGraphFrameSx}>
<DrawingGraph
key={`student-graph-multiple-select-${question._id}-${graphId}-${bounds.xMin}-${bounds.xMax}-${bounds.yMin}-${bounds.yMax}`}
instance={graphInstance}
graphId={graphId}
width={CANVAS}
height={CANVAS}
xMin={bounds.xMin}
xMax={bounds.xMax}
yMin={bounds.yMin}
yMax={bounds.yMax}
steps={1}
borderPixel={5}
responsive={false}
drawingMode={DrawingGraphModes.TOGGLE_INTERACTIVE_DOT}
onGraphReady={handleGraphReady}
/>
</Box>
</Box>
);
};
export default InteractiveDots;
|