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 | 1x 1005x 1005x 1005x 1005x 362x 1468x 734x 734x 1x 1x 1x 1x 4504x 1x 1x 322x 322x 1x 362x 362x 362x 362x 362x 362x 362x 362x 362x 3356x 362x 362x 362x 362x 362x 362x 362x 362x 362x 362x 621x 591x 531x 362x 724x 724x 724x 724x 724x 724x 724x 362x 2x 2x 2x 2x 362x 14x 14x 14x 14x 362x 362x 16x 28x 2x 16x 16x 16x 16x 362x 362x 2x 2x 2x 2x 362x 17x 17x 17x 17x 362x 362x 19x 17x 37x 2x 19x 19x 19x 19x 362x 3x 3x 3x 362x 362x 3x 3x 3x 3x 362x 3x 1x 3x 362x 13x 27x 362x 362x 8x 8x 8x 1x 1x 7x 14x 7x 1x 1x 6x 1x 1x 5x 5x 362x 8x 10x 10x 10x 5x 5x 10x 8x 4x 4x 4x 362x 362x 16x 346x 32x 314x 37x 277x 6x 271x 271x 271x 362x 362x 11x 362x 362x 362x 2172x 720x 8x 56x 3x 3x 1x 1x 735x 735x 17x 17x 1x 1x 742x 14x 14x 1517x 13x 13x | import React, { useEffect, useState } from "react";
import "./GridQuestionEditor.scss";
import {
Alert,
Box,
Button,
Card,
CardContent,
ClickAwayListener,
Collapse,
IconButton,
LinearProgress,
Paper,
Radio,
Stack,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Tooltip,
Typography,
} from "@mui/material";
import { alpha, useTheme } from "@mui/material/styles";
import ReadOnlyMathEditor from "@/utils/components/TinyMCETextEditorReadOnly";
import UnsavedChangesDialog from "@/utils/components/UnsavedChangesDialog";
// Icons
import AddIcon from "@mui/icons-material/Add";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import EditIcon from "@mui/icons-material/Edit";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";
import SaveIcon from "@mui/icons-material/Save";
import CloseIcon from "@mui/icons-material/Close";
import HelpOutlineIcon from "@mui/icons-material/HelpOutline";
import GridOnIcon from "@mui/icons-material/GridOn";
import SettingsIcon from "@mui/icons-material/Settings";
import NoteAddIcon from "@mui/icons-material/NoteAdd";
import RestartAltIcon from "@mui/icons-material/RestartAlt";
import {
useQuestionForm,
TextEditorDialog,
QuestionSettings,
QuickTipsCard,
getClassificationProgress,
editorContainerSx,
editorHeaderSx,
cardHeaderHoverSx,
editorCardSx,
contentPreviewSx,
emptyStateSx,
neutralSurfaceSx,
tipsCardSx,
} from "../utils";
import { sanitizeRichText } from "@/utils/helpers/sanitizeHtml";
const unwrapBlock = (html) => {
const el = document.createElement("div");
el.innerHTML = html;
Iif (el.children.length === 1 && el.children[0].tagName === "P") {
return el.children[0].innerHTML;
}
return html;
};
// The app's global theme overrides (src/theme/ui/overrides/components/table.jsx) fight a fully
// outlined grid on two fronts: MuiTableCell gives every header cell a dashed bottom border and a
// `background.neutral` fill, and MuiTableRow clears the LAST row's cell borders entirely
// (`borderColor: transparent`, at higher specificity than a plain cell-level override) — both
// reasonable for an ordinary data table, but this is an answer grid, where every cell in every
// row, including the last, needs a visible boundary and the header shouldn't read as a tinted band.
const gridTableSx = (theme) => ({
"& .MuiTableCell-root": { border: `1px solid ${theme.palette.divider}` },
"& .MuiTableCell-head": { backgroundColor: "transparent" },
"& .MuiTableRow-root:last-of-type .MuiTableCell-root": { borderColor: theme.palette.divider },
});
const makeId = (prefix) => `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const emptyRow = () => ({ localId: makeId("row"), text: "", correctColumnLocalId: "" });
const emptyColumn = () => ({ localId: makeId("col"), text: "" });
const MIN_ROWS = 2;
const MIN_COLUMNS = 2;
const DEFAULT_ROW_HEADER_LABEL = "Statement";
// The first (statement) column always gets exactly half the table, capped at
// that share even for long text — it never yields width to the option
// columns. The option columns split the OTHER half evenly between however
// many of them there are, so the two always sum to 100% regardless of column
// count.
const ROW_HEADER_COLUMN_WIDTH = "50%";
const optionColumnWidth = (columnCount) => `${50 / Math.max(columnCount, 1)}%`;
// Sentinel key for the row-header (first/"Statement") column in the shared
// hover/pin state — option columns are keyed by their numeric index, and this
// column isn't one of them, so it needs a key that can never collide with 0.
const ROW_HEADER_COLUMN_KEY = "rowHeader";
// Border/tint applied to every cell of the hovered option column, forming one
// continuous outline around the whole column (the header cell's top edge
// through the last row's bottom edge) rather than each cell drawing its own
// separate boxed outline. `!important` is needed to beat gridTableSx's
// `& .MuiTableCell-root` border shorthand — that's a descendant selector
// (two classes), which otherwise outranks a plain class selector on the cell
// itself even though both come from the same `sx` mechanism.
const columnHighlightSx = (theme, { isHeader = false, isLastRow = false } = {}) => {
const color = theme.palette.primary.main;
return {
backgroundColor: `${alpha(color, 0.06)} !important`,
borderLeft: `2px solid ${color} !important`,
borderRight: `2px solid ${color} !important`,
...(isHeader && { borderTop: `2px solid ${color} !important` }),
...(isLastRow && { borderBottom: `2px solid ${color} !important` }),
};
};
const GridQuestionEditor = ({ role = "teacher" }) => {
const {
displayError,
setDisplayError,
editQuestion,
isEditMode,
setEditMode,
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);
const theme = useTheme();
// Expandable sections
const [questionDetailsExpanded, setQuestionDetailsExpanded] = useState(false);
const [answerDetailsExpanded, setAnswerDetailsExpanded] = useState(false);
const [settingsExpanded, setSettingsExpanded] = useState(true);
// Grid-specific state: rows are the statements, columns are the shared
// answer options every row picks exactly one of. `localId` is a stable
// React key independent of the sequential integer `id` assigned at save
// time (see createNewQuestion) — mirrors MultiPartQuestionEditor's
// group/localId split.
const [rows, setRows] = useState([emptyRow(), emptyRow()]);
const [columns, setColumns] = useState([emptyColumn(), emptyColumn()]);
// First column's header text — editable via the same TinyMCE dialog as
// row/column text. Empty means "use the default": the header shows the
// "Statement" placeholder rather than committing that text, and
// DEFAULT_ROW_HEADER_LABEL is only substituted at submit time
// (createNewQuestion) — so the delete button can clear it back to this
// placeholder state instead of re-filling literal "Statement" text.
const [rowHeaderLabel, setRowHeaderLabel] = useState("");
// Which option column the pointer is over — header and body cells for a
// column aren't DOM siblings (each row owns its own cell), so "hover the
// whole column" needs one shared index instead of a per-cell CSS :hover.
const [hoveredColumnIndex, setHoveredColumnIndex] = useState(null);
const columnHoverHandlers = (colIndex) => ({
onMouseEnter: () => setHoveredColumnIndex(colIndex),
onMouseLeave: () => setHoveredColumnIndex((prev) => (prev === colIndex ? null : prev)),
});
// Clicking a column header PINS its highlight/actions so they stay put
// once the pointer moves away — lets a teacher actually reach the
// floating buttons without the hover state racing them there. Clicking
// the same header again unpins it; clicking anywhere outside the table
// (ClickAwayListener below) unpins it too.
const [pinnedColumnIndex, setPinnedColumnIndex] = useState(null);
const toggleColumnPin = (colIndex) => setPinnedColumnIndex((prev) => (prev === colIndex ? null : colIndex));
// Row statement dialog
const [rowTextEditor, setRowTextEditor] = useState("");
const [showRowTextEditor, setShowRowTextEditor] = useState(false);
const [editingRowLocalId, setEditingRowLocalId] = useState(null);
// Column option dialog
const [columnTextEditor, setColumnTextEditor] = useState("");
const [showColumnTextEditor, setShowColumnTextEditor] = useState(false);
const [editingColumnLocalId, setEditingColumnLocalId] = useState(null);
// First column header dialog
const [rowHeaderTextEditor, setRowHeaderTextEditor] = useState("");
const [showRowHeaderTextEditor, setShowRowHeaderTextEditor] = useState(false);
const hasAllRowText = rows.length > 0 && rows.every((r) => r.text?.trim());
const hasAllColumnText = columns.length > 0 && columns.every((c) => c.text?.trim());
const hasAllCorrectAnswers = rows.length > 0 && rows.every((r) => r.correctColumnLocalId);
// Progress calculation
const getProgress = () => {
let progress = 0;
if (questionText) progress += 20;
if (hasAllRowText) progress += 20;
if (hasAllColumnText) progress += 20;
if (hasAllCorrectAnswers) progress += 20;
progress += (getClassificationProgress(values) / 100) * 20;
return Math.round(progress);
};
// Row handlers
const clickAddRow = () => {
setShowRowTextEditor(true);
setRowTextEditor("");
setEditingRowLocalId(null);
setEditMode(false);
};
const clickEditRow = (row) => {
setShowRowTextEditor(true);
setRowTextEditor(row.text);
setEditingRowLocalId(row.localId);
setEditMode(true);
};
const cancelRow = () => {
setRowTextEditor("");
setShowRowTextEditor(false);
setEditingRowLocalId(null);
setEditMode(false);
};
const saveRow = () => {
if (isEditMode && editingRowLocalId !== null) {
setRows((prev) => prev.map((r) => (r.localId === editingRowLocalId ? { ...r, text: rowTextEditor } : r)));
} else {
setRows((prev) => [...prev, { ...emptyRow(), text: rowTextEditor }]);
}
setRowTextEditor("");
setShowRowTextEditor(false);
setEditingRowLocalId(null);
setEditMode(false);
};
const deleteRow = (localId) => {
setRows((prev) => prev.filter((r) => r.localId !== localId));
};
// Column handlers
const clickAddColumn = () => {
setShowColumnTextEditor(true);
setColumnTextEditor("");
setEditingColumnLocalId(null);
setEditMode(false);
};
const clickEditColumn = (column) => {
setShowColumnTextEditor(true);
setColumnTextEditor(column.text);
setEditingColumnLocalId(column.localId);
setEditMode(true);
};
const cancelColumn = () => {
setColumnTextEditor("");
setShowColumnTextEditor(false);
setEditingColumnLocalId(null);
setEditMode(false);
};
const saveColumn = () => {
if (isEditMode && editingColumnLocalId !== null) {
setColumns((prev) =>
prev.map((c) => (c.localId === editingColumnLocalId ? { ...c, text: columnTextEditor } : c))
);
} else {
setColumns((prev) => [...prev, { ...emptyColumn(), text: columnTextEditor }]);
}
setColumnTextEditor("");
setShowColumnTextEditor(false);
setEditingColumnLocalId(null);
setEditMode(false);
};
// First column header handlers — same TinyMCE dialog pattern as row/column
// text, but there's exactly one of these (no add/delete-from-list), so
// "delete" (its own popup button below) just clears it back to "".
const clickEditRowHeader = () => {
setShowRowHeaderTextEditor(true);
setRowHeaderTextEditor(rowHeaderLabel);
setEditMode(Boolean(rowHeaderLabel));
};
const cancelRowHeader = () => {
setRowHeaderTextEditor("");
setShowRowHeaderTextEditor(false);
setEditMode(false);
};
const saveRowHeader = () => {
setRowHeaderLabel(rowHeaderTextEditor);
setRowHeaderTextEditor("");
setShowRowHeaderTextEditor(false);
setEditMode(false);
};
// Deleting a column clears it as the correct answer for any row that
// pointed at it — mirrors DragAndDropEditor.deleteChoice's blank-clearing
// behavior so a deleted option can never linger as an unreachable answer.
const deleteColumn = (localId) => {
setColumns((prev) => prev.filter((c) => c.localId !== localId));
setRows((prev) =>
prev.map((r) => (r.correctColumnLocalId === localId ? { ...r, correctColumnLocalId: "" } : r))
);
};
const selectCorrectColumn = (rowLocalId, columnLocalId) => {
setRows((prev) =>
prev.map((r) => (r.localId === rowLocalId ? { ...r, correctColumnLocalId: columnLocalId } : r))
);
};
// Reset all values
const handleReset = () => {
setQuestionText("");
setQuestionDetailsText("");
setAnswerDetailsText("");
setRows([emptyRow(), emptyRow()]);
setColumns([emptyColumn(), emptyColumn()]);
setRowHeaderLabel("");
setDisplayError({ status: false, message: "" });
resetFields();
};
// Validation
const hasValidGrid = () => {
Iif (rows.length < MIN_ROWS) {
setDisplayError({ status: true, message: `Please add at least ${MIN_ROWS} rows.` });
return false;
}
Iif (columns.length < MIN_COLUMNS) {
setDisplayError({ status: true, message: `Please add at least ${MIN_COLUMNS} columns.` });
return false;
}
if (!hasAllRowText) {
setDisplayError({ status: true, message: "Every row needs statement text." });
return false;
}
Iif (!hasAllColumnText) {
setDisplayError({ status: true, message: "Every column needs option text." });
return false;
}
const columnTexts = columns.map((c) => c.text.trim());
if (new Set(columnTexts).size !== columnTexts.length) {
setDisplayError({ status: true, message: "Column options must be unique." });
return false;
}
if (!hasAllCorrectAnswers) {
setDisplayError({ status: true, message: "Please mark the correct answer for every row." });
return false;
}
setDisplayError({ status: false, message: "" });
return true;
};
// Submit handler — reassign sequential integer ids at save time regardless
// of internal bookkeeping (localId), matching MultiPartQuestionEditor's
// page-index reassignment. correctAnswer.answers is {id: row id, answer:
// the correct column's TEXT} — the same {id, answer} shape Drag-and-Drop
// uses, so grading needs no new logic (see answer_checking.py).
const createNewQuestion = async () => {
if (!hasValidGrid()) return;
const rowsPayload = rows.map((r, idx) => ({ id: idx, text: r.text }));
const columnById = new Map(columns.map((c, idx) => [c.localId, { id: idx, text: c.text }]));
const correctAnswers = rows.map((r, idx) => ({
id: idx,
answer: columnById.get(r.correctColumnLocalId).text,
}));
const basePayload = buildBasePayload("Grid-Question", correctAnswers);
const payload = {
...basePayload,
rows: rowsPayload,
choices: columns.map((c, idx) => ({ id: idx, text: c.text })),
rowHeaderLabel: rowHeaderLabel.trim() || DEFAULT_ROW_HEADER_LABEL,
};
await submitQuestion(payload, () => {
setRows([emptyRow(), emptyRow()]);
setColumns([emptyColumn(), emptyColumn()]);
setRowHeaderLabel("");
});
};
// Dialog management — single active dialog, same pattern every editor uses.
const getActiveDialog = () => {
if (showQuestionTextEditor)
return {
type: "question",
content: questionTextEditor,
setContent: setQuestionTextEditor,
save: saveQuestion,
cancel: cancelQuestion,
questionTypes: [],
};
if (showRowTextEditor)
return {
type: "gridRow",
content: rowTextEditor,
setContent: setRowTextEditor,
save: saveRow,
cancel: cancelRow,
questionTypes: [],
disabledToolbarButtons: ["matheditor", "graph2d", "insertimage", "inserttable"],
};
if (showColumnTextEditor)
return {
type: "gridColumn",
content: columnTextEditor,
setContent: setColumnTextEditor,
save: saveColumn,
cancel: cancelColumn,
questionTypes: [],
disabledToolbarButtons: ["matheditor", "graph2d", "insertimage", "inserttable"],
};
if (showRowHeaderTextEditor)
return {
type: "gridRowHeader",
content: rowHeaderTextEditor,
setContent: setRowHeaderTextEditor,
save: saveRowHeader,
cancel: cancelRowHeader,
questionTypes: [],
disabledToolbarButtons: ["matheditor", "graph2d", "insertimage", "inserttable"],
};
Iif (showAnswerDetailsTextEditor)
return {
type: "answerDetails",
content: answerDetailsTextEditor,
setContent: setAnswerDetailsTextEditor,
save: saveAnswerDetails,
cancel: cancelEditAnswerDetails,
questionTypes: [],
};
Iif (showQuestionDetailsTextEditor)
return {
type: "questionDetails",
content: questionDetailsTextEditor,
setContent: setQuestionDetailsTextEditor,
save: saveQuestionDetails,
cancel: cancelQuestionDetails,
questionTypes: [],
};
return null;
};
const activeDialog = getActiveDialog();
// Load edit data — rebuild columns from `choices`, then resolve each
// row's correctColumnLocalId by matching the loaded column whose text
// equals the row's correct answer text.
useEffect(() => {
loadEditData((data) => {
const loadedColumns = (data.choices || []).map((c) => ({ localId: makeId("col"), text: c.text }));
const answersByRowId = new Map((data.correctAnswer?.answers || []).map((a) => [a.id, a.answer]));
const loadedRows = (data.rows || []).map((r) => {
const correctText = answersByRowId.get(r.id);
const matchColumn = loadedColumns.find((c) => c.text === correctText);
return {
localId: makeId("row"),
text: r.text,
correctColumnLocalId: matchColumn?.localId || "",
};
});
setColumns(loadedColumns.length ? loadedColumns : [emptyColumn(), emptyColumn()]);
setRows(loadedRows.length ? loadedRows : [emptyRow(), emptyRow()]);
// A saved label equal to the default is indistinguishable from
// "never customized" — show it as the placeholder either way
// rather than committing literal "Statement" text to the field.
setRowHeaderLabel(
data.rowHeaderLabel && data.rowHeaderLabel !== DEFAULT_ROW_HEADER_LABEL ? data.rowHeaderLabel : ""
);
});
}, []);
const isRowHeaderColumnActive =
hoveredColumnIndex === ROW_HEADER_COLUMN_KEY || pinnedColumnIndex === ROW_HEADER_COLUMN_KEY;
const requirements = [
["Question text", Boolean(questionText)],
[`At least ${MIN_ROWS} rows`, rows.length >= MIN_ROWS],
[`At least ${MIN_COLUMNS} columns`, columns.length >= MIN_COLUMNS],
["A correct answer for every row", hasAllCorrectAnswers],
["Assignment type", Boolean(values.assignmentType)],
["Question points", Boolean(values.questionPoints)],
];
return (
<Box className="grid-question-editor-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}
questionTypes={activeDialog.questionTypes}
onImageUpload={handleImageUpload}
disabledToolbarButtons={activeDialog.disabledToolbarButtons ?? []}
/>
)}
{/* Header */}
<Paper className="grid-question-editor-header" elevation={0} sx={editorHeaderSx()}>
<Box className="grid-question-editor-header-content">
<Box className="grid-question-editor-header-left">
<GridOnIcon sx={{ fontSize: 28, color: "primary.main" }} />
<Box>
<Typography variant="h5" fontWeight={600}>
{editQuestion ? "Edit Question" : "Create Grid Question"}
</Typography>
<Typography variant="body2" color="text.secondary">
{editQuestion
? "Update your question details"
: "Build a grid of statements and shared answer options"}
</Typography>
</Box>
</Box>
<Box className="grid-question-editor-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}>
{requirements.map(([label, met]) => (
<Typography
key={label}
variant="caption"
sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
>
{met ? (
<CheckCircleIcon fontSize="small" color="success" />
) : (
<CheckCircleOutlineIcon fontSize="small" />
)}
{label}
</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="grid-question-editor-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="grid-question-editor-main">
{/* Left Panel - Question & Grid */}
<Box className="grid-question-editor-left-panel">
{/* Question Card */}
<Card className="grid-question-editor-card" sx={editorCardSx(theme)}>
<CardContent>
<Box className="grid-question-editor-card-header">
<Box className="grid-question-editor-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="grid-question-editor-content-preview"
sx={contentPreviewSx()}
>
<ReadOnlyMathEditor content={questionText} />
</Paper>
) : (
<Box className="grid-question-editor-empty-state" sx={emptyStateSx(theme)}>
<NoteAddIcon sx={{ fontSize: 48, color: "action.disabled" }} />
<Typography color="text.secondary">
Click "Add Question" to write the shared question or instructions
</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="grid-question-editor-content-preview"
sx={{ position: "relative", ...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>
{/* Grid Card */}
<Card className="grid-question-editor-card" sx={editorCardSx(theme)}>
<CardContent>
<Box className="grid-question-editor-card-header">
<Box className="grid-question-editor-card-title">
<GridOnIcon color="primary" />
<Typography variant="h6">Grid</Typography>
</Box>
</Box>
<Typography variant="caption" color="text.secondary" sx={{ display: "block", mb: 2 }}>
Select a radio button in each row to mark that row's correct column.
</Typography>
<ClickAwayListener onClickAway={() => setPinnedColumnIndex(null)}>
<TableContainer
component={Paper}
variant="outlined"
className="grid-question-editor-table"
sx={{
...neutralSurfaceSx(theme),
// MUI's default `overflow-x: auto` implicitly forces
// `overflow-y` to `auto` too (CSS can't mix a
// scrolling axis with a `visible` one), which clips
// the column-actions popup positioned ABOVE the
// header row. Safe to drop entirely since the option
// columns are percentage-widths that always sum to
// 100% — this table never needs to scroll.
overflow: "visible",
}}
>
<Table size="small" sx={{ ...gridTableSx(theme), tableLayout: "fixed" }}>
<TableHead>
<TableRow>
<TableCell
className="grid-question-row-header-cell"
{...columnHoverHandlers(ROW_HEADER_COLUMN_KEY)}
onClick={() => toggleColumnPin(ROW_HEADER_COLUMN_KEY)}
sx={{
width: ROW_HEADER_COLUMN_WIDTH,
maxWidth: ROW_HEADER_COLUMN_WIDTH,
position: "relative",
cursor: "pointer",
"&:focus-within .grid-question-column-actions": {
opacity: 1,
visibility: "visible",
},
...(isRowHeaderColumnActive &&
columnHighlightSx(theme, { isHeader: true })),
}}
>
<Stack
direction="row"
spacing={0.25}
alignItems="center"
justifyContent="center"
className="grid-question-column-actions"
sx={{
position: "absolute",
bottom: "100%",
left: "50%",
transform: "translateX(-50%)",
mb: 0.5,
px: 0.5,
py: 0.25,
bgcolor: "background.paper",
border: "1px solid",
borderColor: "divider",
borderRadius: 1,
boxShadow: 2,
whiteSpace: "nowrap",
zIndex: 2,
opacity: isRowHeaderColumnActive ? 1 : 0,
visibility: isRowHeaderColumnActive ? "visible" : "hidden",
transition: "opacity 0.15s ease",
}}
>
<IconButton
size="small"
data-testid="grid-question-edit-row-header"
onClick={(e) => {
e.stopPropagation();
clickEditRowHeader();
}}
sx={{ p: 0.25 }}
>
<EditIcon sx={{ fontSize: 16 }} />
</IconButton>
<IconButton
size="small"
color="error"
data-testid="grid-question-delete-row-header"
onClick={(e) => {
e.stopPropagation();
setRowHeaderLabel("");
}}
disabled={!rowHeaderLabel}
sx={{ p: 0.25 }}
>
<DeleteOutlineIcon sx={{ fontSize: 16 }} />
</IconButton>
</Stack>
{rowHeaderLabel ? (
<Box
dangerouslySetInnerHTML={{
__html: sanitizeRichText(unwrapBlock(rowHeaderLabel)),
}}
sx={{ ml: 1, fontWeight: 600, "& p": { margin: 0 } }}
/>
) : (
<Typography
variant="body2"
color="text.secondary"
fontStyle="italic"
sx={{ ml: 1 }}
>
{DEFAULT_ROW_HEADER_LABEL}
</Typography>
)}
</TableCell>
{columns.map((column, colIndex) => {
const isColumnActive =
hoveredColumnIndex === colIndex ||
pinnedColumnIndex === colIndex;
return (
<TableCell
key={column.localId}
align="center"
className="grid-question-column-header-cell"
{...columnHoverHandlers(colIndex)}
onClick={() => toggleColumnPin(colIndex)}
sx={{
width: optionColumnWidth(columns.length),
maxWidth: optionColumnWidth(columns.length),
position: "relative",
cursor: "pointer",
"&:focus-within .grid-question-column-actions": {
opacity: 1,
visibility: "visible",
},
...(isColumnActive &&
columnHighlightSx(theme, { isHeader: true })),
}}
>
<Stack
direction="row"
spacing={0.25}
alignItems="center"
justifyContent="center"
className="grid-question-column-actions"
sx={{
position: "absolute",
bottom: "100%",
left: "50%",
transform: "translateX(-50%)",
mb: 0.5,
px: 0.5,
py: 0.25,
bgcolor: "background.paper",
border: "1px solid",
borderColor: "divider",
borderRadius: 1,
boxShadow: 2,
whiteSpace: "nowrap",
zIndex: 2,
opacity: isColumnActive ? 1 : 0,
visibility: isColumnActive ? "visible" : "hidden",
transition: "opacity 0.15s ease",
}}
>
<IconButton
size="small"
data-testid={`grid-question-edit-column-${colIndex}`}
onClick={(e) => {
e.stopPropagation();
clickEditColumn(column);
}}
sx={{ p: 0.25 }}
>
<EditIcon sx={{ fontSize: 16 }} />
</IconButton>
<IconButton
size="small"
color="error"
data-testid={`grid-question-delete-column-${colIndex}`}
onClick={(e) => {
e.stopPropagation();
deleteColumn(column.localId);
}}
disabled={columns.length <= MIN_COLUMNS}
sx={{ p: 0.25 }}
>
<DeleteOutlineIcon sx={{ fontSize: 16 }} />
</IconButton>
</Stack>
<Box>
{column.text ? (
<Box
dangerouslySetInnerHTML={{
__html: sanitizeRichText(
unwrapBlock(column.text)
),
}}
sx={{ fontWeight: 600, "& p": { margin: 0 } }}
/>
) : (
<Typography
variant="body2"
color="text.secondary"
fontStyle="italic"
>
(empty option)
</Typography>
)}
</Box>
</TableCell>
);
})}
</TableRow>
</TableHead>
<TableBody>
{rows.map((row, rowIndex) => (
<TableRow key={row.localId}>
<TableCell
{...columnHoverHandlers(ROW_HEADER_COLUMN_KEY)}
onClick={() => toggleColumnPin(ROW_HEADER_COLUMN_KEY)}
sx={{
width: ROW_HEADER_COLUMN_WIDTH,
maxWidth: ROW_HEADER_COLUMN_WIDTH,
cursor: "pointer",
...(isRowHeaderColumnActive &&
columnHighlightSx(theme, {
isLastRow: rowIndex === rows.length - 1,
})),
}}
>
<Stack direction="row" spacing={0.25} alignItems="center">
{row.text ? (
<Box
dangerouslySetInnerHTML={{
__html: sanitizeRichText(unwrapBlock(row.text)),
}}
sx={{
ml: 1,
flex: 1,
minWidth: 0,
overflowWrap: "break-word",
wordBreak: "break-word",
"& p": { margin: 0 },
}}
/>
) : (
<Typography
variant="body2"
color="text.secondary"
fontStyle="italic"
sx={{ ml: 1, flex: 1, minWidth: 0 }}
>
(empty statement)
</Typography>
)}
<IconButton
size="small"
data-testid={`grid-question-edit-row-${rowIndex}`}
onClick={() => clickEditRow(row)}
sx={{ flexShrink: 0 }}
>
<EditIcon fontSize="small" />
</IconButton>
<IconButton
size="small"
color="error"
data-testid={`grid-question-delete-row-${rowIndex}`}
onClick={() => deleteRow(row.localId)}
disabled={rows.length <= MIN_ROWS}
sx={{ flexShrink: 0 }}
>
<DeleteOutlineIcon fontSize="small" />
</IconButton>
</Stack>
</TableCell>
{columns.map((column, colIndex) => (
<TableCell
key={column.localId}
align="center"
{...columnHoverHandlers(colIndex)}
onClick={() => toggleColumnPin(colIndex)}
sx={{
width: optionColumnWidth(columns.length),
maxWidth: optionColumnWidth(columns.length),
cursor: "pointer",
...((hoveredColumnIndex === colIndex ||
pinnedColumnIndex === colIndex) &&
columnHighlightSx(theme, {
isLastRow: rowIndex === rows.length - 1,
})),
}}
>
<Radio
checked={row.correctColumnLocalId === column.localId}
onChange={() =>
selectCorrectColumn(row.localId, column.localId)
}
name={`grid-question-row-${row.localId}`}
value={column.localId}
color="success"
inputProps={{
"data-testid": `grid-question-radio-${rowIndex}-${colIndex}`,
}}
/>
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</ClickAwayListener>
<Stack direction="row" spacing={2} sx={{ mt: 2 }}>
<Button variant="outlined" startIcon={<AddIcon />} onClick={clickAddRow} fullWidth>
Add Row
</Button>
<Button variant="outlined" startIcon={<AddIcon />} onClick={clickAddColumn} fullWidth>
Add Column
</Button>
</Stack>
</CardContent>
</Card>
{/* Answer Details Card - Collapsible */}
<Card className="grid-question-editor-card" sx={editorCardSx(theme)}>
<CardContent>
<Box
className="grid-question-editor-card-header clickable"
onClick={() => setAnswerDetailsExpanded(!answerDetailsExpanded)}
sx={cardHeaderHoverSx(theme)}
>
<Box className="grid-question-editor-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="grid-question-editor-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="grid-question-editor-right-panel">
<QuickTipsCard
className="grid-question-editor-card grid-question-editor-tips-card"
sx={{ ...editorCardSx(theme), ...tipsCardSx(theme) }}
tips={[
"Add a row for every statement students will classify",
"Add a column for every shared answer option",
"Hover a column header to edit or remove that column",
"Select a radio button in each row to mark its correct column",
"Column options must be unique so a student's selection is unambiguous",
]}
/>
<Card
className="grid-question-editor-card grid-question-editor-settings-card"
sx={editorCardSx(theme)}
>
<CardContent>
<Box
className="grid-question-editor-card-header clickable"
onClick={() => setSettingsExpanded(!settingsExpanded)}
sx={cardHeaderHoverSx(theme)}
>
<Box className="grid-question-editor-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 GridQuestionEditor;
|