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 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 | 3x 533x 533x 533x 533x 533x 533x 533x 533x 533x 533x 310x 533x 533x 533x 533x 47x 533x 533x 533x 533x 533x 1064x 1064x 1064x 1064x 533x 1x 1x 1x 1x 533x 8x 533x 2128x 8x 8x 533x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 533x 533x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 533x 9x 3x 3x 6x 6x 2x 2x 4x 4x 4x 2x 533x 532x 31x 501x 501x 501x 533x 533x 41x 533x 83x 83x 83x 82x 80x 80x 80x 82x 2x 533x 84x 44x 44x 33x 33x 7x 7x 1x 1x 3x 3x 44x 16x 16x 16x 44x 533x 70x 32x 32x 32x 533x 95x 46x 46x 82x 82x 82x 46x 46x 42x 46x 46x 46x 46x 46x 533x 87x 71x 8x 1x 7x 3x 3x 3x 2x 533x 36x 9x 9x 9x 9x 9x 9x 533x 79x 7x 7x 7x 5x 5x 5x 2x 7x 533x 1472x 22x 2128x 14x 14x 14x 8x 6x 1x 5x 4x 2128x | import React, { useCallback, useEffect, useMemo, useState } from "react";
import "./GraphEditor.scss";
import { DrawingGraph, Graph2D } from "graph2d-react";
import {
Alert,
Box,
Button,
Card,
CardContent,
Chip,
Collapse,
Divider,
FormHelperText,
Grid,
IconButton,
LinearProgress,
Paper,
Stack,
TextField,
Tooltip,
Typography,
useTheme,
} from "@mui/material";
import ReadOnlyMathEditor from "@/utils/components/TinyMCETextEditorReadOnly";
import UnsavedChangesDialog from "@/utils/components/UnsavedChangesDialog";
import {
DEFAULT_GRAPH_AXIS_BOUNDS,
isEmptyGraphAnswer,
normalizeGraphAnswerForImport,
parseGraphAxisBounds,
} from "@/utils/components/question-bank/question-display/graph/graphAnswerUtils";
import { drawingGraphFrameSx } from "@/utils/components/question-bank/question-display/graph/graphConstants";
// Icons
import ShowChartIcon from "@mui/icons-material/ShowChart";
import FunctionsIcon from "@mui/icons-material/Functions";
import TrendingUpIcon from "@mui/icons-material/TrendingUp";
import HorizontalRuleIcon from "@mui/icons-material/HorizontalRule";
import LabelIcon from "@mui/icons-material/Label";
import RadioButtonCheckedIcon from "@mui/icons-material/RadioButtonChecked";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline";
import ScatterPlotIcon from "@mui/icons-material/ScatterPlot";
import TuneIcon from "@mui/icons-material/Tune";
import SaveIcon from "@mui/icons-material/Save";
import CloseIcon from "@mui/icons-material/Close";
import HelpOutlineIcon from "@mui/icons-material/HelpOutline";
import SettingsIcon from "@mui/icons-material/Settings";
import NoteAddIcon from "@mui/icons-material/NoteAdd";
import RestartAltIcon from "@mui/icons-material/RestartAlt";
import EditIcon from "@mui/icons-material/Edit";
import AddIcon from "@mui/icons-material/Add";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";
import {
useQuestionForm,
TextEditorDialog,
QuestionSettings,
QuickTipsCard,
getClassificationProgress,
editorContainerSx,
editorHeaderSx,
cardHeaderHoverSx,
editorCardSx,
contentPreviewSx,
emptyStateSx,
tipsCardSx,
} from "../utils";
const Main = ({ role = "teacher" }) => {
const {
displayError,
setDisplayError,
editQuestion,
isEditMode,
questionText,
setQuestionText,
questionTextEditor,
setQuestionTextEditor,
showQuestionTextEditor,
questionDetailsText,
setQuestionDetailsText,
questionDetailsTextEditor,
setQuestionDetailsTextEditor,
showQuestionDetailsTextEditor,
answerDetailsText,
setAnswerDetailsText,
answerDetailsTextEditor,
setAnswerDetailsTextEditor,
showAnswerDetailsTextEditor,
values,
touched,
errors,
handleChange,
handleBlur,
setFieldValue,
setFieldTouched,
handleCancel,
clickQuestionButton,
saveQuestion,
cancelQuestion,
clickQuestionDetailsButton,
saveQuestionDetails,
cancelQuestionDetails,
clickEditAnswerDetails,
saveAnswerDetails,
cancelEditAnswerDetails,
deleteAnswerDetails,
submitQuestion,
buildBasePayload,
loadEditData,
resetFields,
handleImageUpload,
SaveProgress,
navigationBlocker,
} = useQuestionForm(role, { drawingMode: "Dots" });
// Graph-specific state
const [graphInstance] = useState(() => Graph2D());
const [isGraphAnswer, setGraphAnswer] = useState("");
const [drawingMode, setDrawingMode] = useState("linear");
const [ineqLineModes, setIneqLineModes] = useState("solid");
const [labelMode, setLabelMode] = useState("labelDot");
const [labelText, setLabelText] = useState("L");
const [isSwitchingMode, setIsSwitchingMode] = useState(false);
/** False until graph2d-react DrawingGraph finishes deferred init (addCanvas + instance.init). */
const [isDrawingGraphReady, setIsDrawingGraphReady] = useState(false);
const handleDrawingGraphReady = useCallback(() => {
setIsDrawingGraphReady(true);
}, []);
// Cartesian plane range — replaces the old fixed -10..10 canvas. `axisBounds` is the
// range currently applied to the canvas; `axisBoundsDraft` holds the (string) field
// values being edited, which may be invalid/unapplied.
const [axisBounds, setAxisBounds] = useState(DEFAULT_GRAPH_AXIS_BOUNDS);
const [axisBoundsDraft, setAxisBoundsDraft] = useState({
xMin: String(DEFAULT_GRAPH_AXIS_BOUNDS.xMin),
xMax: String(DEFAULT_GRAPH_AXIS_BOUNDS.xMax),
yMin: String(DEFAULT_GRAPH_AXIS_BOUNDS.yMin),
yMax: String(DEFAULT_GRAPH_AXIS_BOUNDS.yMax),
});
const [axisBoundsError, setAxisBoundsError] = useState("");
/**
* graph2d-react's `applyAxisBounds` (reset + initDrawingCanvases) updates the range
* numerically but does NOT regenerate the `<embed>` SVG background — that background's
* `initPicture(...)` script is only (re)written by DrawingGraph's own mount effect, from
* its xMin/xMax/yMin/yMax props. So a range change is applied by remounting DrawingGraph
* (via `key`) with the new bounds as props, the same mechanism a brand new canvas uses —
* not by calling applyAxisBounds on the live instance, which leaves the visible grid
* showing the old range while only the coordinate math silently uses the new one.
*/
useEffect(() => {
setIsDrawingGraphReady(false);
}, [axisBounds]);
// Expandable sections
const [questionDetailsExpanded, setQuestionDetailsExpanded] = useState(false);
const [answerDetailsExpanded, setAnswerDetailsExpanded] = useState(false);
const [settingsExpanded, setSettingsExpanded] = useState(true);
const theme = useTheme();
// Progress calculation
const getProgress = () => {
let progress = 0;
if (questionText) progress += 50;
progress += (getClassificationProgress(values) / 100) * 50;
return Math.round(progress);
};
const handleClearGraph = () => {
Iif (!isDrawingGraphReady) return;
graphInstance.getInstance().clearcanvas(0);
try {
graphInstance.setPointsVisibility("show", 0);
} catch {
/* ignore */
}
};
const switchGraphDrawingMode = (mode) => {
setDrawingMode(mode);
};
const axisBoundsToDraftStrings = (bounds) => ({
xMin: String(bounds.xMin),
xMax: String(bounds.xMax),
yMin: String(bounds.yMin),
yMax: String(bounds.yMax),
});
const handleAxisBoundsDraftChange = (key) => (event) => {
const { value } = event.target;
setAxisBoundsDraft((prev) => ({ ...prev, [key]: value }));
};
/**
* Applies the drawn cartesian plane range by remounting the canvas at the new bounds
* (see the `isDrawingGraphReady` reset effect above for why a remount, not an in-place
* update, is required) — which clears whatever was drawn, same trade-off as the existing
* "Clear Graph Answer" button, so no separate confirmation here.
*/
const handleApplyAxisRange = () => {
const { xMin, xMax, yMin, yMax } = axisBoundsDraft;
const validation = graphInstance.validateAxisBounds(xMin, xMax, yMin, yMax);
if (!validation.valid) {
setAxisBoundsError(validation.error);
return;
}
const applied = { xMin: Number(xMin), xMax: Number(xMax), yMin: Number(yMin), yMax: Number(yMax) };
setAxisBounds(applied);
setAxisBoundsDraft(axisBoundsToDraftStrings(applied));
setAxisBoundsError("");
setGraphAnswer("");
};
const handleAxisBoundsKeyDown = (event) => {
if (event.key === "Enter") {
event.preventDefault();
handleApplyAxisRange();
}
};
// Reset all values
const handleReset = () => {
setQuestionText("");
setQuestionDetailsText("");
setAnswerDetailsText("");
setGraphAnswer("");
handleClearGraph();
setDrawingMode("linear");
setIneqLineModes("solid");
setLabelMode("labelDot");
setLabelText("L");
setFieldValue("drawingMode", "Dots");
setDisplayError({ status: false, message: "" });
setAxisBounds(DEFAULT_GRAPH_AXIS_BOUNDS);
setAxisBoundsDraft(axisBoundsToDraftStrings(DEFAULT_GRAPH_AXIS_BOUNDS));
setAxisBoundsError("");
resetFields();
};
/**
* Modified by Allan Ninal — the drawn answer was not checked before saving, and a
* save attempted before the canvas was ready did nothing at all.
*
* An untouched canvas serializes to a fully-populated string of EMPTY collections
* (`lines#o#{}&dots#o#{}&…`), never to "", so nothing downstream could tell that a
* graph question had no correct answer. It saved, and the student's graph was then
* marked against nothing.
*
* The readiness check was a bare `return`: clicking Save before graph2d-react
* finished its deferred init silently did nothing, with no message and no reason.
*/
const createNewQuestion = async () => {
if (!isDrawingGraphReady) {
setDisplayError({ status: true, message: "The graph is still loading. Please try again in a moment." });
return;
}
const drawnAnswer = graphInstance.getCanvasAnswerObjectToString(0);
if (isEmptyGraphAnswer(drawnAnswer)) {
setDisplayError({ status: true, message: "Please draw the correct answer on the graph before saving." });
return;
}
setDisplayError({ status: false, message: "" });
const payload = {
...buildBasePayload("Graph", drawnAnswer),
};
await submitQuestion(payload, () => {
setGraphAnswer("");
});
};
// Dialog management
const getActiveDialog = () => {
if (showQuestionTextEditor)
return {
type: "question",
content: questionTextEditor,
setContent: setQuestionTextEditor,
save: saveQuestion,
cancel: cancelQuestion,
};
Iif (showAnswerDetailsTextEditor)
return {
type: "answerDetails",
content: answerDetailsTextEditor,
setContent: setAnswerDetailsTextEditor,
save: saveAnswerDetails,
cancel: cancelEditAnswerDetails,
};
Iif (showQuestionDetailsTextEditor)
return {
type: "questionDetails",
content: questionDetailsTextEditor,
setContent: setQuestionDetailsTextEditor,
save: saveQuestionDetails,
cancel: cancelQuestionDetails,
};
return null;
};
const activeDialog = getActiveDialog();
// ========== GRAPH-SPECIFIC COMPONENTS ==========
const DrawingModeCard = ({ children, selected, onClick, sx = {} }) => (
<Card
sx={{
minWidth: { xs: "100%", sm: 140 },
width: "100%",
cursor: "pointer",
transition: "all 0.3s ease",
border: selected ? `2px solid ${theme.palette.primary.main}` : `2px solid ${theme.palette.divider}`,
backgroundColor: selected ? theme.palette.primary.light + "15" : theme.palette.background.paper,
"&:hover": {
transform: { xs: "none", sm: "translateY(-4px)" },
boxShadow: theme.shadows[8],
borderColor: theme.palette.primary.main,
},
boxShadow: selected ? theme.shadows[4] : theme.shadows[1],
...sx,
}}
onClick={onClick}
>
{children}
</Card>
);
// ========== GRAPH-SPECIFIC EFFECTS ==========
// Disable canvas pointer events when switching modes
useEffect(() => {
Eif (graphInstance !== undefined) {
const instance = graphInstance.getInstance();
if (instance) {
// Modified by Allan Ninal — the engine hands back either an array of
// canvases or a single one, so both shapes are handled. A third block
// in between re-set `canvas[0]`, which the forEach had already covered
// for arrays and which is undefined for the non-array shape: it could
// only ever repeat work or do nothing.
if (instance.canvas && Array.isArray(instance.canvas)) {
instance.canvas.forEach((canvas) => {
Eif (canvas) {
canvas.style.pointerEvents = isSwitchingMode ? "none" : "auto";
}
});
}
if (instance.canvas && !Array.isArray(instance.canvas)) {
instance.canvas.style.pointerEvents = isSwitchingMode ? "none" : "auto";
}
}
}
}, [isSwitchingMode, graphInstance]);
// Drawing mode effects (must run only after DrawingGraph wires the instance — see isDrawingGraphReady)
useEffect(() => {
if (!isDrawingGraphReady || graphInstance === undefined) return;
// Modified by Allan Ninal — pointer-events are NOT touched here. Flipping
// isSwitchingMode is enough: the effect above owns the canvas and sets
// `pointerEvents = isSwitchingMode ? "none" : "auto"`. This was a third copy of
// that same rule, after the one removed from the mode cards.
setIsSwitchingMode(true);
switch (values.drawingMode) {
case "Dots":
graphInstance.setDrawingMode("dot");
break;
case "Basic":
graphInstance.setDrawingMode(drawingMode);
break;
case "Inequalities":
graphInstance.getInstance().settool(0, 10);
break;
case "Label":
graphInstance.setDrawingMode(labelMode);
break;
}
const t = window.setTimeout(() => {
setIsSwitchingMode(false);
try {
graphInstance.setPointsVisibility("show", 0);
} catch {
/* graph2d-react: ignore if API unavailable */
}
}, 300);
return () => window.clearTimeout(t);
}, [drawingMode, graphInstance, values.drawingMode, labelMode, isDrawingGraphReady]);
/** Question bank graph: always show construction handles (not hover-only). */
useEffect(() => {
if (!isDrawingGraphReady) return undefined;
try {
graphInstance.setPointsVisibility("show", 0);
} catch {
/* ignore */
}
return undefined;
}, [isDrawingGraphReady, graphInstance]);
/** Soften default hot-pink axes from graph2d-react (`#FF0066`) to match MUI primary. */
useEffect(() => {
if (!isDrawingGraphReady) return undefined;
const primary = theme.palette.primary.main;
let innerRaf;
const paint = () => {
const embed = document.getElementById("embed-0");
Eif (!embed?.querySelectorAll) return;
const root = embed.tagName === "svg" ? embed : embed.querySelector("svg") || embed;
root.querySelectorAll("path, line, polyline").forEach((el) => {
const s = el.getAttribute("stroke");
if (s && s.toLowerCase() === "#ff0066") {
el.setAttribute("stroke", primary);
}
});
};
paint();
const outerRaf = requestAnimationFrame(() => {
innerRaf = requestAnimationFrame(paint);
});
const t = window.setTimeout(paint, 400);
return () => {
cancelAnimationFrame(outerRaf);
if (innerRaf) cancelAnimationFrame(innerRaf);
window.clearTimeout(t);
};
}, [
isDrawingGraphReady,
theme.palette.primary.main,
values.drawingMode,
drawingMode,
labelMode,
ineqLineModes,
axisBounds,
]);
// ========== DRAWING MODE SUB-OPTIONS ==========
const drawingModeComponent = useMemo(() => {
switch (values.drawingMode) {
case "Dots":
return (
<Box
sx={{
flex: 1,
minHeight: { md: 120 },
display: "flex",
flexDirection: "column",
justifyContent: "flex-start",
}}
>
<Paper
variant="outlined"
sx={{
p: 1.5,
borderRadius: 2,
bgcolor: "action.hover",
borderColor: "divider",
}}
>
<Stack direction="row" spacing={1} alignItems="flex-start">
<ScatterPlotIcon color="primary" sx={{ fontSize: 20, mt: 0.25 }} />
<Box>
<Typography variant="body2" sx={{ fontWeight: 600, fontSize: "0.8rem", mb: 0.5 }}>
Click to place dots
</Typography>
<Typography variant="caption" color="text.secondary" sx={{ fontSize: "0.7rem", lineHeight: 1.45 }}>
Each click on the grid adds a solid dot. Use <strong>Clear Graph Answer</strong> to remove all
dots, or switch mode to draw functions, inequalities, or labels.
</Typography>
</Box>
</Stack>
</Paper>
</Box>
);
case "Basic":
return (
<Stack spacing={0.75} sx={{ minWidth: { xs: "100%", sm: 160 }, width: "100%" }}>
<Typography
variant="subtitle2"
sx={{ fontWeight: 600, mb: 0.5, color: "text.secondary", fontSize: "0.75rem" }}
>
Function Types
</Typography>
<DrawingModeCard
selected={drawingMode === "linear"}
onClick={() => {
switchGraphDrawingMode("linear");
if (isDrawingGraphReady) graphInstance.setDrawingMode("linear");
}}
>
<CardContent sx={{ p: 1, "&:last-child": { pb: 1 } }}>
<Stack direction="row" spacing={1} alignItems="center">
<Box
sx={{
p: 0.5,
borderRadius: 0.5,
bgcolor: drawingMode === "linear" ? "primary.main" : "action.hover",
color: drawingMode === "linear" ? "primary.contrastText" : "text.secondary",
display: "flex",
alignItems: "center",
justifyContent: "center",
"& svg": {
fontSize: "0.875rem",
},
}}
>
<ShowChartIcon />
</Box>
<Box sx={{ flex: 1 }}>
<Typography variant="body2" sx={{ fontWeight: 600, fontSize: "0.75rem" }}>
Linear
</Typography>
<Typography
variant="caption"
color="text.secondary"
sx={{ fontSize: "0.65rem" }}
>
y = mx + b
</Typography>
</Box>
{drawingMode === "linear" && (
<CheckCircleIcon color="primary" sx={{ fontSize: "0.875rem" }} />
)}
</Stack>
</CardContent>
</DrawingModeCard>
<DrawingModeCard
selected={drawingMode === "absolute"}
onClick={() => {
switchGraphDrawingMode("absolute");
if (isDrawingGraphReady) graphInstance.setDrawingMode("absolute");
}}
>
<CardContent sx={{ p: 1, "&:last-child": { pb: 1 } }}>
<Stack direction="row" spacing={1} alignItems="center">
<Box
sx={{
p: 0.5,
borderRadius: 0.5,
bgcolor: drawingMode === "absolute" ? "primary.main" : "action.hover",
color:
drawingMode === "absolute" ? "primary.contrastText" : "text.secondary",
display: "flex",
alignItems: "center",
justifyContent: "center",
"& svg": {
fontSize: "0.875rem",
},
}}
>
<FunctionsIcon />
</Box>
<Box sx={{ flex: 1 }}>
<Typography variant="body2" sx={{ fontWeight: 600, fontSize: "0.75rem" }}>
Absolute Value
</Typography>
<Typography
variant="caption"
color="text.secondary"
sx={{ fontSize: "0.65rem" }}
>
y = |x|
</Typography>
</Box>
{drawingMode === "absolute" && (
<CheckCircleIcon color="primary" sx={{ fontSize: "0.875rem" }} />
)}
</Stack>
</CardContent>
</DrawingModeCard>
<DrawingModeCard
selected={drawingMode === "quadratic"}
onClick={() => {
switchGraphDrawingMode("quadratic");
}}
>
<CardContent sx={{ p: 1, "&:last-child": { pb: 1 } }}>
<Stack direction="row" spacing={1} alignItems="center">
<Box
sx={{
p: 0.5,
borderRadius: 0.5,
bgcolor: drawingMode === "quadratic" ? "primary.main" : "action.hover",
color:
drawingMode === "quadratic" ? "primary.contrastText" : "text.secondary",
display: "flex",
alignItems: "center",
justifyContent: "center",
"& svg": {
fontSize: "0.875rem",
},
}}
>
<TrendingUpIcon sx={{ transform: "rotate(45deg)" }} />
</Box>
<Box sx={{ flex: 1 }}>
<Typography variant="body2" sx={{ fontWeight: 600, fontSize: "0.75rem" }}>
Quadratic
</Typography>
<Typography
variant="caption"
color="text.secondary"
sx={{ fontSize: "0.65rem" }}
>
y = ax² + bx + c
</Typography>
</Box>
{drawingMode === "quadratic" && (
<CheckCircleIcon color="primary" sx={{ fontSize: "0.875rem" }} />
)}
</Stack>
</CardContent>
</DrawingModeCard>
<DrawingModeCard
selected={drawingMode === "exponential"}
onClick={() => {
switchGraphDrawingMode("exponential");
}}
>
<CardContent sx={{ p: 1, "&:last-child": { pb: 1 } }}>
<Stack direction="row" spacing={1} alignItems="center">
<Box
sx={{
p: 0.5,
borderRadius: 0.5,
bgcolor: drawingMode === "exponential" ? "primary.main" : "action.hover",
color:
drawingMode === "exponential"
? "primary.contrastText"
: "text.secondary",
display: "flex",
alignItems: "center",
justifyContent: "center",
"& svg": {
fontSize: "0.875rem",
},
}}
>
<TrendingUpIcon sx={{ transform: "rotate(45deg)" }} />
</Box>
<Box sx={{ flex: 1 }}>
<Typography variant="body2" sx={{ fontWeight: 600, fontSize: "0.75rem" }}>
Exponential
</Typography>
<Typography
variant="caption"
color="text.secondary"
sx={{ fontSize: "0.65rem" }}
>
y = aˣ
</Typography>
</Box>
{drawingMode === "exponential" && (
<CheckCircleIcon color="primary" sx={{ fontSize: "0.875rem" }} />
)}
</Stack>
</CardContent>
</DrawingModeCard>
</Stack>
);
case "Inequalities":
return (
<Stack spacing={0.75} sx={{ minWidth: { xs: "100%", sm: 160 }, width: "100%" }}>
<Typography
variant="subtitle2"
sx={{ fontWeight: 600, mb: 0.5, color: "text.secondary", fontSize: "0.75rem" }}
>
Line Style
</Typography>
<DrawingModeCard
selected={ineqLineModes === "solid"}
onClick={() => {
if (isDrawingGraphReady) graphInstance.getInstance().settool(0, 10);
setIneqLineModes("solid");
}}
>
<CardContent sx={{ p: 1, "&:last-child": { pb: 1 } }}>
<Stack direction="row" spacing={1} alignItems="center">
<Box
sx={{
p: 0.5,
borderRadius: 0.5,
bgcolor: ineqLineModes === "solid" ? "primary.main" : "action.hover",
color:
ineqLineModes === "solid" ? "primary.contrastText" : "text.secondary",
display: "flex",
alignItems: "center",
justifyContent: "center",
"& svg": {
fontSize: "0.875rem",
},
}}
>
<HorizontalRuleIcon />
</Box>
<Box sx={{ flex: 1 }}>
<Typography variant="body2" sx={{ fontWeight: 600, fontSize: "0.75rem" }}>
Solid
</Typography>
<Typography
variant="caption"
color="text.secondary"
sx={{ fontSize: "0.65rem" }}
>
Continuous line
</Typography>
</Box>
{ineqLineModes === "solid" && (
<CheckCircleIcon color="primary" sx={{ fontSize: "0.875rem" }} />
)}
</Stack>
</CardContent>
</DrawingModeCard>
<DrawingModeCard
selected={ineqLineModes === "dashed"}
onClick={() => {
if (isDrawingGraphReady) graphInstance.getInstance().settool(0, 10.2);
setIneqLineModes("dashed");
}}
>
<CardContent sx={{ p: 1, "&:last-child": { pb: 1 } }}>
<Stack direction="row" spacing={1} alignItems="center">
<Box
sx={{
p: 0.5,
borderRadius: 0.5,
bgcolor: ineqLineModes === "dashed" ? "primary.main" : "action.hover",
color:
ineqLineModes === "dashed" ? "primary.contrastText" : "text.secondary",
display: "flex",
alignItems: "center",
justifyContent: "center",
"& svg": {
fontSize: "0.875rem",
},
}}
>
<HorizontalRuleIcon sx={{ opacity: 0.5 }} />
</Box>
<Box sx={{ flex: 1 }}>
<Typography variant="body2" sx={{ fontWeight: 600, fontSize: "0.75rem" }}>
Dashed
</Typography>
<Typography
variant="caption"
color="text.secondary"
sx={{ fontSize: "0.65rem" }}
>
Broken line
</Typography>
</Box>
{ineqLineModes === "dashed" && (
<CheckCircleIcon color="primary" sx={{ fontSize: "0.875rem" }} />
)}
</Stack>
</CardContent>
</DrawingModeCard>
</Stack>
);
case "Label":
return (
<Stack spacing={0.75} sx={{ minWidth: { xs: "100%", sm: 200 }, width: "100%" }}>
<Typography
variant="subtitle2"
sx={{ fontWeight: 600, mb: 0.5, color: "text.secondary", fontSize: "0.75rem" }}
>
Label Tools
</Typography>
<Card
sx={{
border: `2px solid ${theme.palette.divider}`,
transition: "all 0.3s ease",
"&:hover": {
boxShadow: theme.shadows[4],
borderColor: theme.palette.primary.main,
},
}}
>
<CardContent sx={{ p: 1 }}>
<Stack spacing={1}>
<Stack direction="row" spacing={1} alignItems="center">
<Box
sx={{
p: 0.5,
borderRadius: 0.5,
bgcolor: labelMode === "labelDot" ? "primary.main" : "action.hover",
color:
labelMode === "labelDot"
? "primary.contrastText"
: "text.secondary",
display: "flex",
alignItems: "center",
justifyContent: "center",
"& svg": {
fontSize: "0.875rem",
},
}}
>
<LabelIcon />
</Box>
<Typography
variant="body2"
sx={{ fontWeight: 600, flex: 1, fontSize: "0.75rem" }}
>
Label Settings
</Typography>
{labelMode === "labelDot" && (
<CheckCircleIcon color="primary" sx={{ fontSize: "0.875rem" }} />
)}
</Stack>
<TextField
id="graph-label"
label="Label Text"
variant="outlined"
size="small"
value={labelText}
fullWidth
onChange={(event) => {
const newValue = event.target.value;
setLabelText(newValue);
if (isDrawingGraphReady) {
graphInstance.getInstance().setCurrentLabelDot(newValue);
}
}}
InputProps={{
startAdornment: (
<LabelIcon fontSize="small" sx={{ mr: 0.5, color: "text.secondary" }} />
),
}}
sx={{
"& .MuiInputBase-root": {
fontSize: "0.75rem",
height: "32px",
},
"& .MuiInputLabel-root": {
fontSize: "0.75rem",
},
}}
/>
<Button
variant={labelMode === "labelDot" ? "contained" : "outlined"}
fullWidth
startIcon={<LabelIcon sx={{ fontSize: "0.875rem" }} />}
onClick={() => {
if (isDrawingGraphReady) graphInstance.setDrawingMode("labelDot");
setLabelMode("labelDot");
}}
size="small"
sx={{
fontSize: "0.75rem",
py: 0.5,
minHeight: "32px",
}}
>
Use Label
</Button>
</Stack>
</CardContent>
</Card>
<DrawingModeCard
selected={labelMode === "pointDot"}
onClick={() => {
if (isDrawingGraphReady) graphInstance.setDrawingMode("pointDot");
setLabelMode("pointDot");
}}
>
<CardContent sx={{ p: 1, "&:last-child": { pb: 1 } }}>
<Stack direction="row" spacing={1} alignItems="center">
<Box
sx={{
p: 0.5,
borderRadius: 0.5,
bgcolor: labelMode === "pointDot" ? "primary.main" : "action.hover",
color: labelMode === "pointDot" ? "primary.contrastText" : "text.secondary",
display: "flex",
alignItems: "center",
justifyContent: "center",
"& svg": {
fontSize: "0.875rem",
},
}}
>
<RadioButtonCheckedIcon />
</Box>
<Box sx={{ flex: 1 }}>
<Typography variant="body2" sx={{ fontWeight: 600, fontSize: "0.75rem" }}>
Point
</Typography>
<Typography
variant="caption"
color="text.secondary"
sx={{ fontSize: "0.65rem" }}
>
Mark a point
</Typography>
</Box>
{labelMode === "pointDot" && (
<CheckCircleIcon color="primary" sx={{ fontSize: "0.875rem" }} />
)}
</Stack>
</CardContent>
</DrawingModeCard>
</Stack>
);
default:
return null;
}
}, [values.drawingMode, drawingMode, ineqLineModes, theme, labelMode, labelText, graphInstance, isDrawingGraphReady]);
// ========== LOAD EDIT DATA ==========
useEffect(() => {
loadEditData((data) => {
setFieldValue("drawingMode", data.drawingMode);
const encoded = normalizeGraphAnswerForImport(data.correctAnswer?.answers);
setGraphAnswer(encoded ?? "");
// The canvas the answer is imported into (below) must be created at this same
// range — done by feeding it to DrawingGraph as xMin/xMax/yMin/yMax props, which
// remounts the canvas at the right scale before import ever runs.
const bounds = parseGraphAxisBounds(data.correctAnswer?.answers);
setAxisBounds(bounds);
setAxisBoundsDraft(axisBoundsToDraftStrings(bounds));
});
}, [graphInstance]);
// Import saved graph after answer string is set (importAnswer requires JSON string, not a parsed object)
useEffect(() => {
if (!isDrawingGraphReady || !isGraphAnswer) return undefined;
const encoded = normalizeGraphAnswerForImport(isGraphAnswer);
Iif (!encoded) return undefined;
const t = setTimeout(() => {
try {
graphInstance.importAnswer(encoded, 0);
graphInstance.setPointsVisibility("show", 0);
} catch (e) {
console.warn("Graph edit import failed:", e);
}
}, 150);
return () => clearTimeout(t);
}, [graphInstance, isGraphAnswer, isDrawingGraphReady]);
// ========== RENDER ==========
return (
<Box className="graph-v2-container" sx={editorContainerSx()}>
<SaveProgress />
<UnsavedChangesDialog blocker={navigationBlocker} />
{/* Dialog */}
{activeDialog && (
<TextEditorDialog
open={true}
editorType={activeDialog.type}
isEditMode={isEditMode}
editContent={activeDialog.content}
setEditContent={activeDialog.setContent}
onSave={activeDialog.save}
onCancel={activeDialog.cancel}
onImageUpload={handleImageUpload}
/>
)}
{/* Header */}
<Paper className="graph-v2-header" elevation={0} sx={editorHeaderSx()}>
<Box className="graph-v2-header-content">
<Box className="graph-v2-header-left">
<ShowChartIcon sx={{ fontSize: 28, color: "primary.main" }} />
<Box>
<Typography variant="h5" fontWeight={600}>
{editQuestion ? "Edit Question" : "Create Graphing Question"}
</Typography>
<Typography variant="body2" color="text.secondary">
{editQuestion
? "Update your question details"
: "Build an interactive graphing question"}
</Typography>
</Box>
</Box>
<Box className="graph-v2-header-actions">
<Button variant="outlined" color="inherit" onClick={handleCancel} startIcon={<CloseIcon />}>
Cancel
</Button>
<Button variant="outlined" color="warning" onClick={handleReset} startIcon={<RestartAltIcon />}>
Reset
</Button>
<Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
<Button
variant="contained"
color="primary"
onClick={createNewQuestion}
startIcon={<SaveIcon />}
>
{editQuestion ? "Update" : "Save Question"}
</Button>
<Tooltip
title={
<Box sx={{ p: 1 }}>
<Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 1 }}>
Required Fields:
</Typography>
<Stack spacing={0.5}>
<Typography
variant="caption"
sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
>
{questionText ? (
<CheckCircleIcon fontSize="small" color="success" />
) : (
<CheckCircleOutlineIcon fontSize="small" />
)}
Question text
</Typography>
<Typography
variant="caption"
sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
>
{values.assignmentType ? (
<CheckCircleIcon fontSize="small" color="success" />
) : (
<CheckCircleOutlineIcon fontSize="small" />
)}
Assignment type
</Typography>
<Typography
variant="caption"
sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
>
{values.questionPoints ? (
<CheckCircleIcon fontSize="small" color="success" />
) : (
<CheckCircleOutlineIcon fontSize="small" />
)}
Question points
</Typography>
<Typography
variant="caption"
sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
>
{values.keywords?.length > 0 ? (
<CheckCircleIcon fontSize="small" color="success" />
) : (
<CheckCircleOutlineIcon fontSize="small" />
)}
At least 1 keyword
</Typography>
<Typography
variant="caption"
sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
>
{values.assignmentDifficulty ? (
<CheckCircleIcon fontSize="small" color="success" />
) : (
<CheckCircleOutlineIcon fontSize="small" />
)}
Difficulty level
</Typography>
</Stack>
</Box>
}
arrow
placement="bottom-end"
>
<IconButton size="small" sx={{ color: "primary.main" }}>
<HelpOutlineIcon fontSize="small" />
</IconButton>
</Tooltip>
</Box>
</Box>
</Box>
{/* Progress bar */}
<Box className="graph-v2-progress">
<LinearProgress
variant="determinate"
value={getProgress()}
color="success"
sx={{ height: 6, borderRadius: 3 }}
/>
<Typography variant="caption" color="text.secondary" sx={{ mt: 0.5 }}>
{getProgress()}% complete
</Typography>
</Box>
</Paper>
{/* Error Alert */}
{displayError.status && (
<Alert
severity="error"
sx={{ mx: 3, mt: 2 }}
onClose={() => setDisplayError({ status: false, message: "" })}
>
{displayError.message}
</Alert>
)}
{/* Question Settings Validation Errors */}
{Object.keys(errors).some((key) => touched[key]) && (
<Alert severity="error" sx={{ mx: 3, mt: 2 }}>
<Typography variant="body2" fontWeight={600} sx={{ mb: 0.5 }}>
Please complete the required question settings:
</Typography>
<Stack spacing={0.25}>
{Object.entries(errors).map(([key, message]) =>
touched[key] ? (
<Typography key={key} variant="caption">
• {message}
</Typography>
) : null
)}
</Stack>
</Alert>
)}
{/* Main Content */}
<Box className="graph-v2-main">
{/* Left Panel */}
<Box className="graph-v2-left-panel">
{/* Question Card */}
<Card className="graph-v2-card" sx={editorCardSx(theme)}>
<CardContent>
<Box className="graph-v2-card-header">
<Box className="graph-v2-card-title">
<HelpOutlineIcon color="primary" />
<Typography variant="h6">Question</Typography>
{questionText && <CheckCircleIcon color="success" fontSize="small" />}
</Box>
<Button
variant={questionText ? "outlined" : "contained"}
size="small"
startIcon={questionText ? <EditIcon /> : <AddIcon />}
onClick={clickQuestionButton}
>
{questionText ? "Edit" : "Add Question"}
</Button>
</Box>
{questionText ? (
<Paper variant="outlined" className="graph-v2-content-preview" sx={contentPreviewSx()}>
<ReadOnlyMathEditor content={questionText} />
</Paper>
) : (
<Box className="graph-v2-empty-state" sx={emptyStateSx(theme)}>
<NoteAddIcon sx={{ fontSize: 48, color: "action.disabled" }} />
<Typography color="text.secondary">
Click "Add Question" to write your question
</Typography>
</Box>
)}
{/* Question Details - Collapsible */}
<Box sx={{ mt: 2 }}>
<Button
size="small"
onClick={() => setQuestionDetailsExpanded(!questionDetailsExpanded)}
endIcon={questionDetailsExpanded ? <ExpandLessIcon /> : <ExpandMoreIcon />}
sx={{ textTransform: "none" }}
>
Question Details (Optional)
{questionDetailsText && (
<CheckCircleIcon color="success" fontSize="small" sx={{ ml: 1 }} />
)}
</Button>
<Collapse in={questionDetailsExpanded}>
<Box sx={{ mt: 1 }}>
{questionDetailsText ? (
<Paper
variant="outlined"
className="graph-v2-content-preview"
sx={contentPreviewSx()}
>
<ReadOnlyMathEditor content={questionDetailsText} />
<IconButton
size="small"
onClick={clickQuestionDetailsButton}
sx={{ position: "absolute", top: 8, right: 8 }}
>
<EditIcon fontSize="small" />
</IconButton>
</Paper>
) : (
<Button
variant="text"
size="small"
startIcon={<AddIcon />}
onClick={clickQuestionDetailsButton}
>
Add details or hints
</Button>
)}
</Box>
</Collapse>
</Box>
</CardContent>
</Card>
{/* Graph Section Card */}
<Card className="graph-v2-card" sx={editorCardSx(theme)}>
<CardContent>
<Box className="graph-v2-card-header">
<Box className="graph-v2-card-title">
<ShowChartIcon color="primary" />
<Typography variant="h6">Graph Answer</Typography>
</Box>
</Box>
{/* ===== GRAPH SECTION - PRESERVED ===== */}
<Box
sx={{
display: "flex",
flexDirection: { xs: "column", md: "row" },
alignItems: { xs: "stretch", md: "stretch" },
gap: 2.5,
width: "100%",
}}
>
{/* Drawing Modes Panel - Left Side */}
<Card
sx={{
width: { xs: "100%", sm: "100%", md: 320 },
maxWidth: { xs: "100%", md: 320 },
minWidth: { xs: 0, md: 280 },
minHeight: { md: 0 },
boxShadow: theme.shadows[2],
borderRadius: 2,
border: `1px solid ${theme.palette.divider}`,
overflow: "hidden",
display: "flex",
flexDirection: "column",
alignSelf: { md: "stretch" },
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
p: 1.5,
borderBottom: `1px solid ${theme.palette.divider}`,
minHeight: 48,
gap: 1,
}}
>
<Typography
variant="subtitle2"
sx={{ fontWeight: 600, color: "text.secondary" }}
>
Drawing Tools
</Typography>
{values.drawingMode && (
<Chip
icon={
values.drawingMode === "Dots" ? (
<ScatterPlotIcon />
) : values.drawingMode === "Basic" ? (
<ShowChartIcon />
) : values.drawingMode === "Inequalities" ? (
<TuneIcon />
) : (
<LabelIcon />
)
}
label={
values.drawingMode === "Dots"
? "Dots"
: values.drawingMode === "Basic"
? drawingMode === "linear"
? "Linear"
: drawingMode === "absolute"
? "Absolute"
: drawingMode === "quadratic"
? "Quadratic"
: "Exponential"
: values.drawingMode === "Inequalities"
? ineqLineModes === "solid"
? "Solid"
: "Dashed"
: labelMode === "labelDot"
? `Label (${labelText})`
: "Point"
}
color="primary"
size="small"
variant="filled"
/>
)}
</Box>
<Box
sx={{
p: 2,
pt: 1.5,
flex: 1,
minHeight: 0,
overflow: "auto",
display: "flex",
flexDirection: "column",
}}
>
{/* Drawing Mode Selector */}
<Box sx={{ width: "100%", mb: 2 }}>
<Grid container spacing={0.5} sx={{ width: "100%" }}>
{[
{
value: "Dots",
label: "Dots",
icon: <ScatterPlotIcon />,
description: "Place dots",
},
{
value: "Basic",
label: "Basic",
icon: <ShowChartIcon />,
description: "Draw functions",
},
{
value: "Inequalities",
label: "Inequalities",
icon: <TuneIcon />,
description: "Draw inequalities",
},
{
value: "Label",
label: "Label",
icon: <LabelIcon />,
description: "Add labels/points",
},
].map((mode) => (
<Grid
size={{ xs: 12, sm: 3, md: 6 }}
key={mode.value}
sx={{ minWidth: 0 }}
>
<Card
sx={{
width: "100%",
minWidth: 0,
height: 70,
cursor: "pointer",
transition: "all 0.3s ease",
border: `2px solid ${
values.drawingMode === mode.value
? theme.palette.primary.main
: theme.palette.divider
}`,
bgcolor:
values.drawingMode === mode.value
? theme.palette.primary.light + "15"
: theme.palette.background.paper,
boxShadow:
values.drawingMode === mode.value
? theme.shadows[4]
: theme.shadows[1],
"&:hover": {
transform: "translateY(-2px)",
boxShadow: theme.shadows[6],
borderColor: theme.palette.primary.main,
},
display: "flex",
flexDirection: "column",
flex: 1,
}}
// Modified by Allan Ninal — this card now only records the
// CHOICE. Driving the engine is the drawing-mode effect's job,
// and it was already doing every one of these things a moment
// later, keyed on values.drawingMode / drawingMode / labelMode:
// the same setDrawingMode / settool calls, the same
// pointer-events toggle, the same isSwitchingMode flag and 300ms
// settle. `settool(0, 10)` appeared at THREE lines in this file
// because of it.
//
// Two mappings for one action is a drift hazard, and it also
// made the area untestable: a mutant in either copy left the
// other satisfying the assertion, so the tests I wrote for it
// killed 1 of 7 and were thrown away. With one implementation
// they bite. The effect's timer is also cleaned up on unmount,
// which the copy removed here never was.
//
// The sub-mode state below stays: the effect READS drawingMode
// and labelMode to decide which tool Basic and Label mean.
onClick={() => {
setFieldValue("drawingMode", mode.value);
setFieldTouched("drawingMode", true);
if (mode.value === "Basic") {
switchGraphDrawingMode("linear");
} else if (mode.value === "Inequalities") {
setIneqLineModes("solid");
} else if (mode.value === "Label") {
setLabelMode("labelDot");
}
}}
>
<CardContent
sx={{
p: 0.25,
"&:last-child": { pb: 0.25 },
flex: 1,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
minHeight: 0,
height: "100%",
}}
>
<Stack
spacing={0.15}
alignItems="center"
sx={{
width: "100%",
height: "100%",
justifyContent: "center",
}}
>
<Box
sx={{
p: 0.2,
borderRadius: 0.5,
bgcolor:
values.drawingMode === mode.value
? "primary.main"
: "action.hover",
color:
values.drawingMode === mode.value
? "primary.contrastText"
: "text.secondary",
display: "flex",
alignItems: "center",
justifyContent: "center",
"& svg": {
fontSize: "0.875rem",
},
}}
>
{mode.icon}
</Box>
<Typography
variant="body2"
sx={{
fontWeight: 600,
fontSize: "0.65rem",
textAlign: "center",
lineHeight: 1,
m: 0,
}}
>
{mode.label}
</Typography>
{values.drawingMode === mode.value && (
<CheckCircleIcon
color="primary"
sx={{ fontSize: "0.65rem", m: 0 }}
/>
)}
</Stack>
</CardContent>
</Card>
</Grid>
))}
</Grid>
{touched.drawingMode && errors.drawingMode && (
<FormHelperText error sx={{ mt: 1 }}>
{errors.drawingMode}
</FormHelperText>
)}
</Box>
<Divider sx={{ my: 1.5 }} />
{/* Drawing Mode Sub-Options */}
<Box
sx={{
width: "100%",
flex: 1,
minHeight: 0,
display: "flex",
flexDirection: "column",
}}
>
<Typography
variant="overline"
sx={{
fontWeight: 700,
letterSpacing: "0.08em",
mb: 1,
color: "text.secondary",
display: "block",
}}
>
Options
</Typography>
<Box sx={{ flex: 1, minHeight: 0 }}>{drawingModeComponent}</Box>
</Box>
<Divider sx={{ my: 1.5 }} />
{/* Cartesian plane range — replaces the old fixed -10..10 canvas */}
<Box sx={{ width: "100%" }}>
<Typography
variant="overline"
sx={{
fontWeight: 700,
letterSpacing: "0.08em",
mb: 1,
color: "text.secondary",
display: "block",
}}
>
Axis Range
</Typography>
<Grid container spacing={1}>
{[
{ key: "xMin", label: "X Min" },
{ key: "xMax", label: "X Max" },
{ key: "yMin", label: "Y Min" },
{ key: "yMax", label: "Y Max" },
].map((field) => (
<Grid size={6} key={field.key}>
<TextField
id={`${role}-question-bank-graph-axis-${field.key}`}
label={field.label}
size="small"
fullWidth
value={axisBoundsDraft[field.key]}
onChange={handleAxisBoundsDraftChange(field.key)}
onKeyDown={handleAxisBoundsKeyDown}
sx={{
"& .MuiInputBase-root": { fontSize: "0.75rem" },
"& .MuiInputLabel-root": { fontSize: "0.75rem" },
}}
/>
</Grid>
))}
</Grid>
{axisBoundsError ? (
<FormHelperText error sx={{ mt: 0.5 }}>
{axisBoundsError}
</FormHelperText>
) : (
<Typography
variant="caption"
color="text.secondary"
sx={{ mt: 0.5, display: "block" }}
>
Applying a new range clears the current drawing.
</Typography>
)}
<Button
id={`${role}-question-bank-graph-btn-apply-axis-range`}
variant="outlined"
size="small"
fullWidth
startIcon={<TuneIcon sx={{ fontSize: "0.875rem" }} />}
onClick={handleApplyAxisRange}
disabled={!isDrawingGraphReady}
sx={{ mt: 1, fontSize: "0.75rem" }}
>
Apply Range
</Button>
</Box>
</Box>
</Card>
{/* Graph Canvas - Right Side */}
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: { xs: 1.5, md: 2 },
flex: 1,
width: { xs: "100%", md: "auto" },
minWidth: 0,
minHeight: { md: 0 },
alignSelf: { md: "stretch" },
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: 1,
width: "100%",
justifyContent: "center",
flex: { md: 1 },
minHeight: 0,
}}
>
<Box
className="graph-v2-graph-surface"
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
width: "100%",
maxWidth: { xs: "100%", sm: "450px", md: "450px" },
overflow: "visible",
}}
>
<Box
sx={{
...drawingGraphFrameSx,
position: "relative",
opacity: isSwitchingMode ? 0.5 : 1,
transition: "opacity 0.2s ease",
width: "100%",
maxWidth: { xs: "100%", sm: "450px", md: "450px" },
}}
>
<Box
sx={{
width: "100%",
height: "100%",
position: "relative",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Box
sx={{
width: { xs: "100%", sm: "410px" },
maxWidth: "100%",
position: "relative",
overflow: "visible",
}}
>
<DrawingGraph
key={`graph-editor-${axisBounds.xMin}-${axisBounds.xMax}-${axisBounds.yMin}-${axisBounds.yMax}`}
drawingMode="linear"
width={410}
height={410}
instance={graphInstance}
steps={1}
onGraphReady={handleDrawingGraphReady}
xLabel="x"
yLabel="y"
xMin={axisBounds.xMin}
xMax={axisBounds.xMax}
yMin={axisBounds.yMin}
yMax={axisBounds.yMax}
/>
</Box>
</Box>
{isSwitchingMode && (
<Box
sx={{
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
bgcolor: "rgba(0, 0, 0, 0.05)",
display: "flex",
alignItems: "center",
justifyContent: "center",
zIndex: 1000,
pointerEvents: "auto",
cursor: "not-allowed",
}}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
}}
onMouseDown={(e) => {
e.stopPropagation();
e.preventDefault();
}}
onMouseUp={(e) => {
e.stopPropagation();
e.preventDefault();
}}
onMouseMove={(e) => {
e.stopPropagation();
e.preventDefault();
}}
>
<Typography variant="caption" color="text.secondary">
Switching mode...
</Typography>
</Box>
)}
</Box>
</Box>
</Box>
<Stack
direction={{ xs: "column", sm: "row" }}
gap={1.5}
sx={{
width: "100%",
maxWidth: { xs: "100%", sm: "410px" },
justifyContent: { sm: "flex-end" },
flexShrink: 0,
mt: { xs: 0.5, md: 0 },
}}
>
<Button
id={`${role}-question-bank-graph-btn-clear-graph`}
variant="outlined"
color="primary"
size="small"
onClick={handleClearGraph}
sx={{ width: { xs: "100%", sm: "auto" } }}
>
Clear Graph Answer
</Button>
<Button
variant="outlined"
color="error"
size="small"
disabled={isGraphAnswer === ""}
onClick={() => {
if (isGraphAnswer !== "" && isDrawingGraphReady) {
graphInstance.importAnswer(isGraphAnswer);
}
}}
sx={{ width: { xs: "100%", sm: "auto" } }}
>
Reset
</Button>
</Stack>
</Box>
</Box>
{/* ===== END GRAPH SECTION ===== */}
</CardContent>
</Card>
{/* Answer Details Card - Collapsible */}
<Card className="graph-v2-card" sx={editorCardSx(theme)}>
<CardContent>
<Box
className="graph-v2-card-header clickable"
onClick={() => setAnswerDetailsExpanded(!answerDetailsExpanded)}
sx={cardHeaderHoverSx(theme)}
>
<Box className="graph-v2-card-title">
<NoteAddIcon color="primary" />
<Typography variant="h6">Answer Explanation (Optional)</Typography>
{answerDetailsText && <CheckCircleIcon color="success" fontSize="small" />}
</Box>
{answerDetailsExpanded ? <ExpandLessIcon /> : <ExpandMoreIcon />}
</Box>
<Collapse in={answerDetailsExpanded}>
<Box sx={{ mt: 2 }}>
{answerDetailsText ? (
<Paper
variant="outlined"
className="graph-v2-content-preview"
sx={{ position: "relative", ...contentPreviewSx() }}
>
<ReadOnlyMathEditor content={answerDetailsText} />
<Box
sx={{
position: "absolute",
top: 8,
right: 8,
display: "flex",
gap: 0.5,
}}
>
<IconButton
size="small"
onClick={() => clickEditAnswerDetails(answerDetailsText)}
>
<EditIcon fontSize="small" />
</IconButton>
<IconButton size="small" onClick={deleteAnswerDetails} color="error">
<DeleteOutlineIcon fontSize="small" />
</IconButton>
</Box>
</Paper>
) : (
<Button
variant="outlined"
startIcon={<AddIcon />}
onClick={() => clickEditAnswerDetails("")}
fullWidth
>
Add Answer Explanation
</Button>
)}
</Box>
</Collapse>
</CardContent>
</Card>
</Box>
{/* Right Panel - Tips + Settings */}
<Box className="graph-v2-right-panel">
<QuickTipsCard
className="graph-v2-card graph-v2-tips-card"
sx={{ ...editorCardSx(theme), ...tipsCardSx(theme) }}
tips={[
"Select a drawing mode from the tools panel",
"Use Basic mode for functions like linear, quadratic, etc.",
"Use Inequalities to draw shaded regions",
"Use Labels to mark specific points on the graph",
]}
/>
<Card className="graph-v2-card graph-v2-settings-card" sx={editorCardSx(theme)}>
<CardContent>
<Box
className="graph-v2-card-header clickable"
onClick={() => setSettingsExpanded(!settingsExpanded)}
sx={cardHeaderHoverSx(theme)}
>
<Box className="graph-v2-card-title">
<SettingsIcon color="primary" />
<Typography variant="h6">Question Settings</Typography>
</Box>
{settingsExpanded ? <ExpandLessIcon /> : <ExpandMoreIcon />}
</Box>
<Collapse in={settingsExpanded}>
<Box sx={{ mt: 2 }}>
<QuestionSettings
values={values}
touched={touched}
errors={errors}
handleChange={handleChange}
handleBlur={handleBlur}
setFieldValue={setFieldValue}
setFieldTouched={setFieldTouched}
/>
</Box>
</Collapse>
</CardContent>
</Card>
</Box>
</Box>
</Box>
);
};
export default Main;
|