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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 | 2x 122x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 6x 6x 24x 24x 24x 11x 11x 11x 11x 199x 21x 199x 11x 11x 11x 11x 1x 6x 9x 7x 6x 6x 1x 1x 6x 18x 18x 6x 13x 13x 8x 2x 182x 182x 182x 182x 285x 285x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 28x 182x 18x 20x 18x 18x 18x 18x 13x 13x 3x 3x 10x 10x 5x 18x 182x 104x 2x 182x 105x 182x 181x 182x 104x 104x 16x 26x 26x 26x 26x 16x 16x 16x 182x 13x 13x 13x 9x 9x 1x 1x 1x 8x 4x 4x 12x 12x 182x 122x 8x 8x 182x 104x 5x 5x 182x 182x 170x 170x 68x 65x 65x 65x 65x 65x 170x 170x 186x 170x 170x 10x 10x 170x 10x 10x 10x 10x 6x 4x 10x 4x 4x 2x 2x 2x 4x 3x 4x 3x 4x 1x 1x 1x 4x 1x 1x 1x 1x 1x 4x 2x 142x 14x 7x 4x 4x 20x 9x 9x 6x 10x 8x 4x 4x 8x 6x 5x 2x 182x 412x 412x 412x 354x 324x 324x 324x 34x 34x 26x 290x 182x 182x 181x 206x 182x 182x 182x 182x 182x 182x 1x 181x 206x 206x 206x 206x 206x 206x 206x 206x 206x 9x 9x 15x 15x | import {
Box,
Button,
Card,
CardContent,
Chip,
CircularProgress,
Collapse,
IconButton,
LinearProgress,
Stack,
Tooltip,
Typography,
} from "@mui/material";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import YesNoOption from "@/utils/components/dialogs/YesNoOption";
import OKOption from "@/utils/components/dialogs/OKOption";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { _generateAnswersModel } from "@/store/slices/student/StudentQuestionPage";
import { scroller } from "react-scroll";
import { API_ENDPOINTS } from "@/api/endpoints";
import axios from "axios";
import { enqueueSnackbar } from "notistack";
// Icons
import FlagIcon from "@mui/icons-material/Flag";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";
import SendIcon from "@mui/icons-material/Send";
import AssignmentIcon from "@mui/icons-material/Assignment";
import AccessTimeIcon from "@mui/icons-material/AccessTime";
import { alpha } from "@mui/material/styles";
import { isEmptyGraphAnswer } from "@/utils/components/question-bank/question-display/graph/graphAnswerUtils";
import {
countActiveInteractiveDotsInAnswer,
isInteractiveDotsAnswerComplete,
parseInteractiveDotLimitsFromQuestion,
} from "@/utils/components/question-bank/question-display/interactive-dots/interactiveDotsUtils";
import { sanitizeRichText } from "@/utils/helpers/sanitizeHtml";
const formatDuration = (totalSeconds) => {
if (totalSeconds <= 0) return null;
const days = Math.floor(totalSeconds / 86400);
const hours = Math.floor((totalSeconds % 86400) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const parts = [];
if (days > 0) parts.push(`${days}d`);
if (hours > 0) parts.push(`${hours}h`);
if (minutes > 0) parts.push(`${minutes}m`);
parts.push(`${seconds}s`);
return parts.join(" ");
};
/**
* Read a graph answer stored in the OLD encoding: `key#o#{json}` segments run
* together (`tplines#o#{...}&dots#o#{...}`). They are not separated by anything a
* split could use, so each segment's end is found by counting braces.
*
* Lifted out of displayAnswer by Allan Ninal so this path can be taken BEFORE
* JSON.parse is attempted. The extraction logic is unchanged.
*/
function readLegacyGraphAnswer(answer) {
const points = [];
const extractJson = (str, key) => {
const prefix = `${key}#o#`;
const startIndex = str.indexOf(prefix);
if (startIndex === -1) return null;
const jsonStart = startIndex + prefix.length;
let braceCount = 0;
let jsonEnd = jsonStart;
for (let i = jsonStart; i < str.length; i++) {
if (str[i] === "{") braceCount++;
else if (str[i] === "}") braceCount--;
if (braceCount === 0) {
jsonEnd = i + 1;
break;
}
}
try {
return JSON.parse(str.slice(jsonStart, jsonEnd));
} catch {
return null;
}
};
const pushPoint = (point) => {
if (typeof point?.x === "number" && typeof point?.y === "number") {
points.push(`(x: ${point.x}, y: ${point.y})`);
}
};
const tplines = extractJson(answer, "tplines");
if (tplines) {
for (const line of Object.values(tplines)) {
Eif (Array.isArray(line.dotData)) line.dotData.forEach(pushPoint);
}
}
for (const key of ["dots", "pointValueDots", "labeldots"]) {
const group = extractJson(answer, key);
if (group) Object.values(group).forEach(pushPoint);
}
return points.length ? points.join(", ") : "";
}
/**
* What to tell a student whose submission did not go through.
*
* Added by Allan Ninal. Keep the server's reason when it gives one — "the assignment
* is closed" is actionable in a way a generic apology is not — but never surface
* axios' own wording or a raw error object to a student.
*/
export function submitFailureMessage(error) {
const detail = error?.response?.data?.detail;
if (typeof detail === "string" && detail.trim()) return detail;
return "Your answers could not be submitted. Please check your connection and try again.";
}
const AnswerTracker = ({ page, setPage }) => {
const navigate = useNavigate();
const location = useLocation();
const dispatch = useDispatch();
const { assignmentQuestions, myAnswers, settings, violationLockout } = useSelector(
(state) => state.StudentQuestionPage
);
const { specificAssignmentData } = useSelector((state) => state.StudentSpecificAssignment);
const { classCode, assignmentTitle } = useParams();
const [showYesNoOption, setShowYesNoOption] = useState(false);
const [isLoading, setLoading] = useState(false);
const [showAnswers, setShowAnswers] = useState(true);
const [secondsUntilClose, setSecondsUntilClose] = useState(null);
const [closedDialog, setClosedDialog] = useState(false);
// Modified by Allan Ninal — the closed dialog used to claim the work was submitted
// whether or not it actually was.
const [autoSubmitFailed, setAutoSubmitFailed] = useState(false);
// Which of the two triggers fired the closed dialog — same dialog, different copy.
const [autoSubmitReason, setAutoSubmitReason] = useState("timeout");
const hasAutoSubmittedRef = useRef(false);
const answersRef = useRef(myAnswers);
const answerListRef = useRef(null);
const submitAnswers = () => {
setShowYesNoOption(true);
};
const clickYes = async () => {
let answers = [
...myAnswers.data.map(({ questionType, answer, ...rest }) => ({
...rest,
studentAnswer: answer ?? "",
})),
];
setLoading(true);
setShowYesNoOption(false);
try {
const response = await axios.post(
API_ENDPOINTS.student.assignment.submitAnswers(specificAssignmentData.details._id),
{ answers }
);
Eif (response.status == 200) {
// EI-1210: when the backend marks the submission as pending teacher
// approval (late submission), navigate directly to the submission
// details page so the student sees the pending-review state rather
// than a score screen.
if (response.data?.reviewStatus === "pending") {
enqueueSnackbar(response.data.message || "Submission received — awaiting teacher approval", {
variant: "info",
});
navigate(`/student/classes/${classCode}/assignment/${assignmentTitle}/submission`, {
state: { assignmentId: specificAssignmentData.details._id },
});
} else {
enqueueSnackbar(response.data.message, { variant: "success" });
navigate(-1);
}
}
} catch (error) {
// Modified by Allan Ninal — a failed submission said nothing at all.
// The confirmation dialog has already closed by this point, so the student
// was left back on their answers with no message, no navigation, and every
// reason to believe the work had gone in. It had not.
enqueueSnackbar(submitFailureMessage(error), { variant: "error" });
} finally {
setLoading(false);
}
};
useEffect(() => {
if (myAnswers.data.length == 0) {
dispatch(_generateAnswersModel());
}
}, []);
useEffect(() => {
answersRef.current = myAnswers;
}, [myAnswers]);
// A rendered answer can carry plain MathJax-delimited text (\(...\)) from a
// teacher-authored choice, not just a pre-rendered .mfe-formula span — only a
// typeset call turns that into real math. Reruns on every render (no dep array,
// same pattern as EmbeddedChoicePassage.jsx) so it catches answers changing.
useEffect(() => {
Iif (window.MathJax?.typesetPromise && answerListRef.current) {
window.MathJax.typesetPromise([answerListRef.current]).catch(() => {});
}
});
useEffect(() => {
const dateClose = specificAssignmentData?.details?.date_close;
if (!dateClose) return;
const updateCountdown = () => {
const now = Date.now();
const closeTime = new Date(dateClose).getTime();
const diff = Math.floor((closeTime - now) / 1000);
setSecondsUntilClose(diff);
};
updateCountdown();
const intervalId = setInterval(updateCountdown, 1000);
return () => clearInterval(intervalId);
}, [specificAssignmentData?.details?.date_close]);
/**
* Shared by both auto-submit triggers below (close-time and, now, the browser-
* lockdown violation threshold — see
* docs/implementation/browser_lockdown_violation_tracking.md) so the submit POST,
* the EI-1210 pending-review branch, and the failed-submission handling exist in
* exactly one place. `hasAutoSubmittedRef` is shared too: only ONE of the two
* triggers may ever actually submit, whichever fires first.
*/
const autoSubmit = useCallback(async (reason) => {
const answers = answersRef.current.data.map(({ questionType, answer, category, ...rest }) => ({
...rest,
studentAnswer: answer ?? "",
}));
try {
const { data, status } = await axios.post(
API_ENDPOINTS.student.assignment.submitAnswers(specificAssignmentData.details._id),
{ answers }
);
Eif (status === 200) {
// EI-1210: when the auto-submitted late work goes into the
// pending-approval queue, navigate directly to the submission
// details page (same route as the manual clickYes path) so the
// student sees the pending state instead of the closed-dialog.
if (data?.reviewStatus === "pending") {
enqueueSnackbar(data.message || "Submission received — awaiting teacher approval", {
variant: "info",
});
navigate(`/student/classes/${classCode}/assignment/${assignmentTitle}/submission`, {
state: { assignmentId: specificAssignmentData.details._id },
});
return; // skip the assignment-closed dialog
}
enqueueSnackbar(data.message, { variant: "success" });
}
} catch (error) {
// Modified by Allan Ninal — the worst of the three.
//
// The closed dialog below is shown either way, so a student whose
// auto-submission FAILED saw exactly what a student whose submission
// succeeded saw. They had every reason to believe their work was in,
// and no way to find out otherwise until a grade never appeared.
setAutoSubmitFailed(true);
enqueueSnackbar(submitFailureMessage(error), { variant: "error" });
}
setAutoSubmitReason(reason);
setClosedDialog(true);
}, [specificAssignmentData?.details?._id, navigate, classCode, assignmentTitle]);
// Auto-submit when assignment closes
useEffect(() => {
if (secondsUntilClose === null || secondsUntilClose > 0 || hasAutoSubmittedRef.current) return;
hasAutoSubmittedRef.current = true;
autoSubmit("timeout");
}, [secondsUntilClose, autoSubmit]);
// Auto-submit when browser-lockdown violations exceed the allowed threshold (3) —
// LockdownGuard reports each violation to the backend and, once it responds with
// the threshold exceeded, dispatches `_triggerViolationLockout` (see
// TakeAssignmentPage.jsx). `hasAutoSubmittedRef` is the SAME ref the close-time
// trigger above uses, so whichever fires first is the only one that submits.
useEffect(() => {
if (!violationLockout?.triggered || hasAutoSubmittedRef.current) return;
hasAutoSubmittedRef.current = true;
autoSubmit("violations");
}, [violationLockout?.triggered, autoSubmit]);
const closingLabel = useMemo(() => formatDuration(secondsUntilClose), [secondsUntilClose]);
const displayAnswer = (entry) => {
Iif (!entry || !entry.questionType) return "";
// Guarded like the teacher preview tracker's copy: an answer item without a
// string `answer` (a drop-down blank stored as a plain string, say) otherwise
// throws here and takes the WHOLE tracker down mid-assessment, rather than
// just leaving one summary line blank. Modified by Allan Ninal.
//
// DOM-based, not a tag-stripping regex: a regex only removes tags, so
// entities TinyMCE writes for things like spaces and comparison signs
// (` `, `<`, `&`) survived into the tracker verbatim — a free-
// response answer of "hello world < 5" rendered as literal
// "hello world < 5". innerHTML/textContent decodes every entity the
// same way the browser would, matching the stripHtml already used for
// drag-and-drop/drop-down blanks (DragAndDrop.jsx, DropDownMenu.jsx) and
// tinyMCEUtility's tinyMCEtoString.
//
// A math-formula span's rendered markup (MathLive's convertLatexToMarkup
// output, see math-formula/plugin.js) is deeply nested spans laid out purely
// visually — a fraction's numerator/denominator have no textual "/" between
// them, so plain textContent extraction read them in DOM order with nothing
// to separate them: a `\frac{a}{b}` answer showed as "ba" instead of "a/b".
// Swap each formula for its `data-latex` source (the actual semantic answer)
// before extracting text — same technique as tinyMCEUtility's
// getChoiceComparisonKey, which hits the identical problem comparing choices.
//
// Image-only choices have no text either — every bare <img> would strip to ""
// and every image choice would resolve to the same (wrong) letter. Keep the
// src in the comparison key the same way formulas keep their LaTeX.
const stripHtml = (text) => {
if (!text || typeof text !== "string") return "";
const el = document.createElement("div");
el.innerHTML = text;
el.querySelectorAll(".mfe-formula[data-latex]").forEach((node) => {
node.textContent = node.getAttribute("data-latex") || "";
});
el.querySelectorAll("img[src]").forEach((node) => {
node.textContent = `[[img:${node.getAttribute("src")}]]`;
});
return (el.textContent || el.innerText || "").trim();
};
// Sanitized HTML, not flattened text — used for anything that can carry a
// math formula (free-response, drag-and-drop/drop-down blanks, an embedded-
// choice phrase). `.mfe-formula` is MathLive's own pre-rendered markup
// (MathLive's static CSS/fonts are already loaded globally in index.html —
// see RichTextContent.jsx, which renders the same spans the same way), so
// this actually SHOWS the formula instead of stripHtml's plain-text
// `data-latex` fallback ("\frac{a}{b}"), which is only meant for the
// multiple-choice/checkbox comparisons below, not for what a student reads.
const richPreview = (html) => sanitizeRichText(html || "");
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const questionMeta = assignmentQuestions.find((q) => q._id === entry.questionId);
const questionType = entry.questionType.toLowerCase();
// Debug logging for graph answers
if (questionType === "graph") {
console.log("Graph entry in displayAnswer:", entry);
console.log("Graph answer value:", entry.answer);
}
switch (questionType) {
case "graph-multiple-select":
case "graph-multiple-choice": {
if (!entry.answer) return "";
const active = countActiveInteractiveDotsInAnswer(entry.answer);
return active > 0 ? `${active} selected` : "";
}
case "graph": {
Iif (!entry.answer) return "";
const points = [];
try {
// The legacy encoding is NOT JSON, so it has to be recognised
// BEFORE the parse below. It used to be handled after it, where
// JSON.parse had already thrown and jumped to the catch — which
// made the fallback unreachable and left every older graph
// submission showing a blank answer. Modified by Allan Ninal.
if (typeof entry.answer === "string" && entry.answer.includes("#o#")) {
return readLegacyGraphAnswer(entry.answer);
}
// Parse the answer - could be JSON string or object
const graphData = typeof entry.answer === "string" ? JSON.parse(entry.answer) : entry.answer;
// New format: { format: "Graph2D", version: "2.0", data: { ... } }
if (graphData.format === "Graph2D" && graphData.data) {
const data = graphData.data;
// Extract from pointValueDots
if (Array.isArray(data.pointValueDots)) {
for (const point of data.pointValueDots) {
Eif (typeof point.x === "number" && typeof point.y === "number") {
points.push(`(x: ${point.x}, y: ${point.y})`);
}
}
}
// Extract from dots
if (Array.isArray(data.dots)) {
for (const point of data.dots) {
if (typeof point.x === "number" && typeof point.y === "number") {
points.push(`(x: ${point.x}, y: ${point.y})`);
}
}
}
// Extract from labeldots
if (Array.isArray(data.labeldots)) {
for (const point of data.labeldots) {
Eif (typeof point.x === "number" && typeof point.y === "number") {
points.push(`(x: ${point.x}, y: ${point.y})`);
}
}
}
// Extract from tplines (lines with dotData)
if (Array.isArray(data.tplines)) {
for (const line of data.tplines) {
Eif (Array.isArray(line.dotData)) {
for (const point of line.dotData) {
Eif (typeof point.x === "number" && typeof point.y === "number") {
points.push(`(x: ${point.x}, y: ${point.y})`);
}
}
}
}
}
return points.length ? points.join(", ") : "";
}
} catch (e) {
console.error("Error parsing graph answer:", e);
return "";
}
return "";
}
case "free-response":
// entry.answer is TinyMCE HTML (see FreeResponse.jsx) — rendered as
// sanitized HTML (truncated to a single line via CSS) so a math
// formula in the answer shows rendered, not as raw LaTeX text.
return richPreview(entry.answer || "");
case "multiple-choice": {
if (!questionMeta?.choices || typeof entry.answer !== "string") return "";
const index = questionMeta.choices.findIndex((c) => stripHtml(c.text) === stripHtml(entry.answer));
return index >= 0 && index < alphabet.length ? alphabet[index] : "";
}
case "checkbox": {
Iif (!Array.isArray(entry.answer) || !questionMeta?.choices) return "";
return entry.answer
.map((ans) => {
const index = questionMeta.choices.findIndex((c) => stripHtml(c.text) === stripHtml(ans));
return index >= 0 && index < alphabet.length ? alphabet[index] : null;
})
.filter((letter) => letter !== null)
.join(", ");
}
case "drag-and-drop":
return Array.isArray(entry.answer)
? entry.answer
.filter((item) => item?.answer?.trim?.() !== "")
.map((item) => richPreview(item.answer))
.join(", ")
: "";
case "embedded-multiple-choice": {
// entry.answer is the selected choice's id (not its text — the same
// phrase can be marked more than once in the passage), so resolve it
// against the question's choices to show the picked word/phrase.
if (!questionMeta?.choices || typeof entry.answer !== "string" || !entry.answer) return "";
const selected = questionMeta.choices.find((c) => c.id === entry.answer);
return selected ? richPreview(selected.text) : "";
}
case "grid-question": {
// entry.answer is [{id: row id, answer: chosen column TEXT}] — the
// same id-keyed shape drag-and-drop uses. Unlike drag-and-drop's
// inline blanks, a grid's rows aren't visually ordered in the stem,
// so each entry is prefixed with its row's own statement text.
if (!Array.isArray(entry.answer)) return "";
return entry.answer
.filter((item) => item?.answer?.trim?.())
.map((item) => {
const row = questionMeta?.rows?.find((r) => r.id === item.id);
const rowLabel = row ? richPreview(row.text) : "";
return rowLabel ? `${rowLabel}: ${item.answer}` : item.answer;
})
.join("; ");
}
case "single-stimulus":
case "multi-part-question": {
// entry.answer is { [group_id]: <that group's own answer> } — one
// string/array-of-strings per group, never mixed across groups (see
// SingleStimulus.jsx / MultiPartQuestion.jsx). Summarize each answered
// group as its own "Group N: <letters>" chunk, same letter-resolution
// as multiple-choice/checkbox above, just scoped to that group's choices.
if (!questionMeta?.groups || typeof entry.answer !== "object" || entry.answer === null) return "";
return questionMeta.groups
.map((group, groupIdx) => {
const groupAnswer = entry.answer[group.group_id];
if (group.type === "drop-down" || group.type === "drag-and-drop") {
if (!Array.isArray(groupAnswer)) return null;
const filled = groupAnswer
.filter((item) => {
if (typeof item === "string") return item.trim() !== "";
return item?.answer?.trim?.() !== "";
})
.map((item) => richPreview(typeof item === "string" ? item : item.answer));
return filled.length ? `Group ${groupIdx + 1}: ${filled.join(", ")}` : null;
}
const values = Array.isArray(groupAnswer) ? groupAnswer : groupAnswer ? [groupAnswer] : [];
if (values.length === 0) return null;
const groupLetters = values
.map((value) => {
const index = (group.choices || []).findIndex(
(c) => stripHtml(c.text) === stripHtml(value)
);
return index >= 0 && index < alphabet.length ? alphabet[index] : null;
})
.filter((letter) => letter !== null);
return groupLetters.length ? `Group ${groupIdx + 1}: ${groupLetters.join(", ")}` : null;
})
.filter(Boolean)
.join(" · ");
}
case "drop-down-menu":
// Blanks arrive as {id, answer} objects OR as plain strings. Reading
// only the object shape left a plain-string blank contributing an
// empty entry, so a student saw a stray "," instead of their answer.
// This now matches the teacher preview tracker, whose entire purpose
// is to show a teacher what the student sees. Modified by Allan Ninal.
Iif (!Array.isArray(entry.answer)) return "";
return entry.answer
.filter((item) => {
if (typeof item === "string") return item.trim() !== "";
return item?.answer?.trim?.() !== "";
})
.map((item) => richPreview(typeof item === "string" ? item : item.answer))
.join(", ");
default:
return "";
}
};
// Modified by Allan Ninal — graph answers cannot be judged by emptiness of the
// string. An UNTOUCHED canvas does not serialize to ""; it comes back fully
// populated with empty collections (`lines#o#{}&dots#o#{}&…`), so the `return
// true` below counted it as answered. A single click on the graph is enough for
// the autosave to store that, and the student is then told everything is done and
// submits a blank graph. `isEmptyGraphAnswer` is the helper written for this — its
// docstring says a `trim() !== ""` test can never detect an empty canvas — and
// nothing was calling it here.
const isAnswered = (entry) => {
Iif (!entry) return false;
const { answer } = entry;
if (answer === "" || answer === null || answer === undefined) return false;
if (entry.questionType === "graph") return !isEmptyGraphAnswer(answer);
Iif (
entry.questionType === "graph-multiple-select" ||
entry.questionType === "graph-multiple-choice"
) {
const questionMeta = assignmentQuestions.find((q) => q._id === entry.questionId);
const limits = parseInteractiveDotLimitsFromQuestion(questionMeta);
return isInteractiveDotsAnswerComplete(answer, limits);
}
Iif (entry.questionType === "single-stimulus" || entry.questionType === "multi-part-question") {
// A plain-object answer ({} to start) is truthy, so the generic
// `return true` below would count an untouched question as
// answered the instant its entry exists. Answered here means
// EVERY group has its own non-empty value.
const questionMeta = assignmentQuestions.find((q) => q._id === entry.questionId);
const groups = questionMeta?.groups || [];
if (groups.length === 0 || typeof answer !== "object") return false;
return groups.every((g) => {
const value = answer[g.group_id];
return Array.isArray(value) ? value.length > 0 : Boolean(value);
});
}
if (Array.isArray(answer)) {
return !answer.every((item) => {
if (typeof item !== "object" || item === null) return false;
return "answer" in item && item.answer === "";
});
}
return true;
};
const totalAnswers = (entries = []) => entries.filter(isAnswered).length;
const totalFlaggedQuestions = (questionsList) => {
Iif (!Array.isArray(questionsList)) return 0;
return questionsList.reduce((count, q) => (q?.isFlagged ? count + 1 : count), 0);
};
const handleViewQuestion = (questionIndex) => {
setPage(questionIndex + 1);
if (settings.layout === "1") {
scroller.scrollTo(`question-${questionIndex}`, {
duration: 800,
delay: 0,
smooth: "easeInOutQuart",
offset: -150,
});
}
};
const answeredCount = totalAnswers(Object.values(myAnswers.data));
const totalQuestions = assignmentQuestions?.length || 0;
const flaggedCount = totalFlaggedQuestions(myAnswers.data);
const progressPercent = totalQuestions > 0 ? (answeredCount / totalQuestions) * 100 : 0;
return (
<Box>
{assignmentQuestions && (
<>
<YesNoOption
title="Confirm Submission"
message={
answeredCount === totalQuestions
? "Do you want to submit all your answers?"
: `You have ${totalQuestions - answeredCount} unanswered question${totalQuestions - answeredCount !== 1 ? "s" : ""} and ${flaggedCount} flagged question${flaggedCount !== 1 ? "s" : ""}. Do you want to submit all your answers? Warning: unanswered questions will be marked as wrong.`
}
showDialog={showYesNoOption}
clickNo={() => setShowYesNoOption(false)}
clickYes={clickYes}
/>
<OKOption
isDialog={closedDialog}
setDialog={() => {
setClosedDialog(false);
navigate(-1);
}}
title={
autoSubmitFailed
? "Not Submitted"
: autoSubmitReason === "violations"
? "Assignment Submitted"
: "Assignment Closed"
}
message={
autoSubmitReason === "violations"
? autoSubmitFailed
? "Too many browser lockdown violations were detected, but your answers could NOT be submitted. Please tell your teacher before leaving this page."
: "Too many browser lockdown violations were detected. Your work has been submitted automatically."
: autoSubmitFailed
? "This assignment has closed, but your answers could NOT be submitted. Please tell your teacher before leaving this page."
: "This assignment has closed. Your work has been submitted automatically."
}
/>
<Card
sx={{
borderRadius: 3,
boxShadow: "0 4px 20px rgba(0, 0, 0, 0.08)",
overflow: "hidden",
}}
>
{/* Header */}
<Box
sx={{
p: 2,
background: "linear-gradient(135deg, #1976d2 0%, #1565c0 100%)",
color: "white",
}}
>
<Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 1 }}>
<AssignmentIcon fontSize="small" />
<Typography variant="subtitle1" fontWeight={600}>
Answer Tracker
</Typography>
</Box>
{/* Progress Section */}
<Box sx={{ mt: 1.5 }}>
<Box sx={{ display: "flex", justifyContent: "space-between", mb: 0.5 }}>
<Typography variant="caption" sx={{ opacity: 0.9 }}>
Progress
</Typography>
<Typography variant="caption" fontWeight={600}>
{answeredCount} / {totalQuestions}
</Typography>
</Box>
<LinearProgress
variant="determinate"
value={progressPercent}
sx={{
height: 8,
borderRadius: 4,
backgroundColor: "action.disabledBackground",
"& .MuiLinearProgress-bar": {
backgroundColor: "success.main",
borderRadius: 4,
},
}}
/>
</Box>
{/* Stats Chips */}
<Stack direction="row" spacing={1} sx={{ mt: 1.5 }}>
<Chip
size="small"
icon={<CheckCircleIcon sx={{ fontSize: 16, color: "#4caf50 !important" }} />}
label={`${answeredCount} Answered`}
sx={{
bgcolor: "rgba(255,255,255,0.15)",
color: "white",
fontSize: 11,
height: 24,
}}
/>
{flaggedCount > 0 && (
<Chip
size="small"
icon={<FlagIcon sx={{ fontSize: 14, color: "#ffb74d !important" }} />}
label={`${flaggedCount} Flagged`}
sx={{
bgcolor: "rgba(255,255,255,0.15)",
color: "white",
fontSize: 11,
height: 24,
}}
/>
)}
</Stack>
</Box>
{/* Toggle Button */}
<Box
onClick={() => setShowAnswers(!showAnswers)}
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
px: 2,
py: 1,
cursor: "pointer",
bgcolor: "action.hover",
borderBottom: (t) => `1px solid ${t.palette.divider}`,
"&:hover": { bgcolor: "action.selected" },
}}
>
<Typography variant="body2" color="text.secondary" fontWeight={500}>
{showAnswers ? "Hide Answers" : "Show Answers"}
</Typography>
<IconButton size="small">
{showAnswers ? <ExpandLessIcon /> : <ExpandMoreIcon />}
</IconButton>
</Box>
{/* Answer List */}
<Collapse in={showAnswers}>
<Box
ref={answerListRef}
sx={{
maxHeight: "45vh",
overflowY: "auto",
p: 1,
}}
>
{myAnswers.data?.map((entry, answerIndex) => {
const answered = isAnswered(entry);
const isCurrent = page - 1 === answerIndex;
const isFlagged = entry?.isFlagged;
return (
<Box
key={answerIndex}
onClick={() => handleViewQuestion(answerIndex)}
sx={{
display: "flex",
alignItems: "center",
gap: 1.5,
p: 1.5,
mb: 0.5,
borderRadius: 2,
cursor: "pointer",
transition: "all 0.2s ease",
bgcolor: (t) =>
isCurrent ? alpha(t.palette.primary.main, 0.1) : "transparent",
border: (t) =>
isCurrent
? `1px solid ${alpha(t.palette.primary.main, 0.4)}`
: "1px solid transparent",
"&:hover": {
bgcolor: (t) =>
isCurrent
? alpha(t.palette.primary.main, 0.1)
: t.palette.action.selected,
},
}}
>
{/* Question Number Badge */}
<Box
sx={{
width: 28,
height: 28,
borderRadius: "50%",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: 12,
fontWeight: 600,
flexShrink: 0,
bgcolor: (t) =>
answered
? alpha(t.palette.success.main, 0.12)
: t.palette.action.hover,
color: answered ? "success.main" : "text.disabled",
border: (t) =>
answered
? `2px solid ${t.palette.success.main}`
: `2px solid ${t.palette.divider}`,
}}
>
{answerIndex + 1}
</Box>
{/* Answer Content */}
<Box sx={{ flex: 1, minWidth: 0 }}>
<Typography
variant="body2"
component="div"
// component="div", not the default <p>: displayAnswer can return
// sanitized HTML (free-response/drag-and-drop/dropdown/embedded-choice
// answers), and that HTML is itself wrapped in a <p> — nesting a <p>
// inside Typography's own <p> is invalid and gets silently split by
// the browser, breaking the single-line truncation below.
sx={{
color: answered ? "text.primary" : "text.disabled",
fontWeight: answered ? 500 : 400,
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
// Tall enough to hold a rendered formula (~36px at the 20px size
// below) without vertically clipping it — the body2 default
// line-height (~20px) cut a fraction's denominator clean off.
lineHeight: "36px",
// Flatten block-level wrappers from the answer's own HTML (TinyMCE
// always wraps free-response content in <p>) into the single line.
"& p": { display: "inline", margin: 0 },
"& .mfe-formula": {
// Bigger than the surrounding 14px text — at body2 size a
// fraction/root reads as illegible clutter, not math.
fontSize: "20px",
// Puts the fraction bar (not the whole box) ~6px — about
// 0.3em at this font-size — above the text baseline, which
// is where a minus sign or the bar of a fraction sits in
// real typeset math ("axis height"). A larger pull-down
// (e.g. -0.35em) put the bar almost ON the baseline instead
// of above it, so the denominator hung ~22px below the line
// — noticeably lower than the plain text ("start"/"end")
// flanking it, reading as sitting on a different line rather
// than the same one. Measured against getBoundingClientRect
// of the surrounding text and the formula's own
// .ML__frac-line, not eyeballed.
verticalAlign: "-0.15em",
},
}}
dangerouslySetInnerHTML={{
__html: answered ? displayAnswer(entry) : "Not answered",
}}
/>
</Box>
{/* Status Icons */}
{isFlagged && (
<Tooltip title="Flagged for review">
<FlagIcon
sx={{
fontSize: 18,
color: "warning.main",
}}
/>
</Tooltip>
)}
</Box>
);
})}
</Box>
</Collapse>
{/* Assignment close countdown */}
{closingLabel && (
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: 1,
px: 2,
py: 1.25,
bgcolor: (t) =>
secondsUntilClose < 300
? alpha(t.palette.warning.main, 0.1)
: alpha(t.palette.info.main, 0.1),
borderBottom: "1px solid",
borderColor: (t) =>
secondsUntilClose < 300
? alpha(t.palette.warning.main, 0.3)
: alpha(t.palette.info.main, 0.3),
}}
>
<AccessTimeIcon
sx={{
fontSize: 18,
color: secondsUntilClose < 300 ? "warning.dark" : "info.dark",
}}
/>
<Typography
variant="body2"
fontWeight={600}
sx={{
color: secondsUntilClose < 300 ? "warning.dark" : "info.dark",
}}
>
Assignment closes in {closingLabel}
</Typography>
</Box>
)}
{secondsUntilClose !== null && secondsUntilClose <= 0 && (
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: 1,
px: 2,
py: 1.25,
bgcolor: (t) => alpha(t.palette.error.main, 0.1),
borderBottom: (t) => `1px solid ${alpha(t.palette.error.main, 0.3)}`,
}}
>
<AccessTimeIcon sx={{ fontSize: 18, color: "error.dark" }} />
<Typography variant="body2" fontWeight={600} sx={{ color: "error.dark" }}>
Assignment is closed
</Typography>
</Box>
)}
{/* Submit Button */}
<CardContent sx={{ p: 2, pt: 1.5, pb: "16px !important" }}>
<Button
variant="contained"
color="primary"
disabled={isLoading}
fullWidth
onClick={submitAnswers}
startIcon={!isLoading && <SendIcon />}
sx={{
py: 1.25,
borderRadius: 2,
textTransform: "none",
fontWeight: 600,
fontSize: 15,
boxShadow: "0 4px 12px rgba(25, 118, 210, 0.3)",
"&:hover": {
boxShadow: "0 6px 16px rgba(25, 118, 210, 0.4)",
},
}}
>
{isLoading ? <CircularProgress size={24} color="inherit" /> : "Submit Answers"}
</Button>
</CardContent>
</Card>
</>
)}
</Box>
);
};
export default AnswerTracker;
|