All files / src/utils/components/question-bank/question-display/interactive-dots InteractiveDotsViewOnly.jsx

2.85% Statements 2/70
0% Branches 0/47
0% Functions 0/19
3.57% Lines 2/56

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                                                  6x                   6x                                                                                                                                                                                                                                                                                                                
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 { useTheme } from "@mui/material/styles";
import TinyMCETextEditorReadOnly from "@/utils/components/TinyMCETextEditorReadOnly";
import {
    questionCardSurfaceBg,
    questionItemNumberSx,
    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 {
    countActiveInteractiveDotsInAnswer,
    countInteractiveDots,
    parseInteractiveDotLimitsFromQuestion,
    toStudentPromptGraph,
} from "./interactiveDotsUtils";
 
const CANVAS = GRAPH2D_QUESTION_BANK_CANVAS_SIZE;
 
/**
 * Read-only Graph Multiple-Select display for question-bank cards / assignment lists.
 * - showAnswers=false: student prompt (all dots inactive) + background drawings + saved axes
 * - showAnswers=true: answer key with mark-correct styling (dashed green actives)
 *
 * Lists must pass a shared `graphInstance` and a sequential `graphId` (0, 1, 2…).
 * Each card owning Graph2D() at id 0 fights over `embed-0`; hashed ids drop imports.
 */
const InteractiveDotsViewOnly = ({ question, showAnswers, itemNumber, graphId: graphIdProp, graphInstance: graphInstanceProp }) => {
    const theme = useTheme();
    const cardBg = questionCardSurfaceBg(theme);
    const [ownedInstance] = useState(() => graphInstanceProp ?? Graph2D());
    const graphInstance = graphInstanceProp ?? ownedInstance;
    const graphId = typeof graphIdProp === "number" ? graphIdProp : 0;
    const readyRef = useRef(false);
    const rafRef = useRef([]);
 
    const answerKey = useMemo(
        () =>
            normalizeGraphAnswerForImport(
                question?.correctAnswer?.answers ?? question?.correctAnswer?.content
            ),
        [question?.correctAnswer?.answers, question?.correctAnswer?.content]
    );
    const promptGraph = useMemo(() => toStudentPromptGraph(answerKey), [answerKey]);
    const bounds = useMemo(() => parseGraphAxisBounds(answerKey), [answerKey]);
    const limits = useMemo(() => parseInteractiveDotLimitsFromQuestion(question), [question]);
    const totalDots = useMemo(() => countInteractiveDots(answerKey), [answerKey]);
    const correctDots = useMemo(() => countActiveInteractiveDotsInAnswer(answerKey), [answerKey]);
 
    const cancelRafs = useCallback(() => {
        rafRef.current.forEach((id) => cancelAnimationFrame(id));
        rafRef.current = [];
    }, []);
 
    const applyCanvas = useCallback(() => {
        if (!readyRef.current || !answerKey) return false;
        try {
            graphInstance.clearInteractiveDotReview?.(graphId);
            if (showAnswers) {
                graphInstance.importAnswer(answerKey, graphId);
                graphInstance.setDrawingMode(DrawingGraphModes.MARK_CORRECT_INTERACTIVE_DOT, graphId);
            } else {
                const prompt = promptGraph || answerKey;
                graphInstance.importAnswer(prompt, graphId);
                graphInstance.setDrawingMode(DrawingGraphModes.TOGGLE_INTERACTIVE_DOT, graphId);
            }
            return true;
        } catch (e) {
            console.warn("InteractiveDotsViewOnly import failed:", e);
            return false;
        }
    }, [answerKey, graphId, graphInstance, promptGraph, showAnswers]);
 
    const importWhenReady = useCallback(() => {
        cancelRafs();
        applyCanvas();
        const outer = requestAnimationFrame(() => {
            applyCanvas();
            const inner = requestAnimationFrame(() => {
                applyCanvas();
            });
            rafRef.current.push(inner);
        });
        rafRef.current.push(outer);
    }, [applyCanvas, cancelRafs]);
 
    const handleGraphReady = useCallback(() => {
        readyRef.current = true;
        importWhenReady();
    }, [importWhenReady]);
 
    useEffect(() => {
        if (!readyRef.current) return undefined;
        importWhenReady();
        return cancelRafs;
    }, [answerKey, showAnswers, bounds.xMin, bounds.xMax, bounds.yMin, bounds.yMax, importWhenReady, cancelRafs]);
 
    useEffect(() => () => cancelRafs(), [cancelRafs]);
 
    const limitLabel = (() => {
        if (limits.min == null && limits.max == null) return null;
        if (limits.min != null && limits.max != null) return `Limits ${limits.min}–${limits.max}`;
        if (limits.min != null) return `Min ${limits.min}`;
        return `Max ${limits.max}`;
    })();
 
    const canvasKey = [
        "graph-multiple-select",
        question?._id ?? question?.id ?? "",
        String(graphId),
        showAnswers ? "answers" : "prompt",
        bounds.xMin,
        bounds.xMax,
        bounds.yMin,
        bounds.yMax,
    ].join("-");
 
    return (
        <Box>
            <Box sx={{ display: "flex", alignItems: "flex-start", gap: 1, mb: 1.5 }}>
                {itemNumber != null && itemNumber !== false && (
                    <Typography component="span" sx={{ ...questionItemNumberSx, flexShrink: 0 }}>
                        {itemNumber}.
                    </Typography>
                )}
                <Box sx={{ flex: 1, ...questionStemTypographySx }}>
                    <TinyMCETextEditorReadOnly content={question.question} backgroundColor={cardBg} />
                </Box>
            </Box>
 
            {(showAnswers || limitLabel) && (
                <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap sx={{ mb: 1.5 }}>
                    {showAnswers && (
                        <Chip
                            size="small"
                            color="success"
                            variant="outlined"
                            label={`${correctDots} correct / ${totalDots} dots`}
                        />
                    )}
                    {limitLabel && <Chip size="small" variant="outlined" label={limitLabel} />}
                    {showAnswers && (
                        <Chip
                            size="small"
                            variant="outlined"
                            label={`Axes x[${bounds.xMin}, ${bounds.xMax}] y[${bounds.yMin}, ${bounds.yMax}]`}
                        />
                    )}
                </Stack>
            )}
 
            <Box sx={drawingGraphFrameSx}>
                <DrawingGraph
                    key={canvasKey}
                    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}
                    readOnly
                    drawingMode={
                        showAnswers
                            ? DrawingGraphModes.MARK_CORRECT_INTERACTIVE_DOT
                            : DrawingGraphModes.TOGGLE_INTERACTIVE_DOT
                    }
                    onGraphReady={handleGraphReady}
                />
            </Box>
        </Box>
    );
};
 
export default InteractiveDotsViewOnly;