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 | 15x 14x 11x 15x 7x 1x 1x 2x 4x 3x 1x 2x 1x 1x 5x 223x 223x 223x 223x 223x 223x 223x 223x 255x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 28x 28x 223x 223x 223x 235x 50x 223x 223x 223x 223x 223x 1x 1x 1x 1x 1x 1x 1x 223x 1x 1x 223x 1x 1x 223x 9x 9x 223x 4x 4x 223x 1x 1x 223x 3x 3x 223x 223x 28x 28x 223x 223x 92x 92x 223x 140x 83x 223x 149x 1341x 149x 326x 23x 149x 223x 27x 27x 3x 3x 3x 3x 24x 24x 27x 27x 27x 27x 9x 9x 9x 15x 24x 24x 223x 79x 79x 223x 61x 223x 223x 54x 223x 54x 54x 54x 54x 223x 223x 225x 225x 223x 223x 223x 168x 225x 173x 173x 173x 173x 173x 28x | import React, { useState, useEffect, useRef } from "react";
import "./QuestionBank.scss";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import {
AppBar,
Button,
Chip,
Divider,
Drawer,
IconButton,
List,
ListItemButton,
ListItemText,
Menu,
Paper,
Skeleton,
Toolbar,
Tooltip,
useMediaQuery,
} from "@mui/material";
import { alpha, useTheme } from "@mui/material/styles";
import VolumeUpIcon from "@mui/icons-material/VolumeUp";
import LibraryBooksIcon from "@mui/icons-material/LibraryBooks";
import FilterListIcon from "@mui/icons-material/FilterList";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import HelpIcon from "@mui/icons-material/Help";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { Graph2D } from "graph2d-react";
import { useSnackbar } from "notistack";
import ReadAloud from "@/utils/components/ReadAloud";
import SearchField from "@/utils/components/SearchField";
import { CreateNewQuestionButton } from "@/utils/components/question-bank/question-content/utils";
import YesNoOption from "@/utils/components/dialogs/YesNoOption";
import CombinedPagination from "@/utils/components/pagination/CombinedPagination";
import useDebounce from "@/utils/hooks/useDebounce";
import tinyMCEUtility from "@/utils/helpers/tinyMCEUtility";
import { utcToLocalTimeZone } from "@/utils/helpers/utcToLocalTime";
import { HtmlTooltip, getNoResultsMessage } from "@/utils/components/question-bank/utils";
import { QuestionDisplayRenderer, CardSettings } from "@/utils/components/question-bank/question-display/utils";
import {
isInteractiveDotsQuestion,
needsSharedGraphCanvas,
} from "@/utils/components/question-bank/question-display/interactive-dots/interactiveDotsUtils";
import QuestionBankFilterPanel from "@/utils/components/question-bank/QuestionBankFilterPanel";
import {
_teacherDeletePersonalQuestion,
_teacherFetchPersonalQuestions,
} from "@/store/slices/teacher/TeacherQuestionBank";
// ─── Helpers ──────────────────────────────────────────────────────────────────
function snackbarTextFromDeleteRejection(rejected) {
if (typeof rejected === "string" && rejected.trim() !== "") return rejected;
if (!rejected || typeof rejected !== "object") return "Failed to delete question";
const detail = rejected.detail ?? rejected.data?.detail;
if (detail != null) {
if (typeof detail === "string" || typeof detail === "number") return String(detail);
Eif (Array.isArray(detail))
return detail
.map((x) => (x && typeof x === "object" && x.msg != null ? String(x.msg) : String(x)))
.join(" ");
}
if (typeof rejected.data === "string" && rejected.data.trim() !== "") return rejected.data;
if (rejected.data && typeof rejected.data === "object" && typeof rejected.data.message === "string")
return rejected.data.message;
if (rejected.message && !String(rejected.message).includes("Request failed with status code"))
return String(rejected.message);
return "Failed to delete question";
}
// ─── Skeleton ─────────────────────────────────────────────────────────────────
// Placeholder card mirroring a question card's header (points/index/icons) +
// body + footer-chips shape so the skeleton doesn't jump/reflow once the
// real cards render.
function QuestionCardSkeleton() {
return (
<Paper
elevation={2}
sx={{ border: (t) => `1px solid ${t.palette.divider}`, borderRadius: 3, overflow: "hidden" }}
>
<Box
sx={{
px: 2,
py: 1.25,
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: 1,
bgcolor: (t) => alpha(t.palette.primary.main, 0.04),
borderBottom: (t) => `1px solid ${t.palette.divider}`,
}}
>
<Skeleton variant="text" width={60} animation="wave" />
<Skeleton variant="text" width={40} animation="wave" />
<Skeleton variant="circular" width={24} height={24} animation="wave" />
</Box>
<Box sx={{ p: "1rem 1.5rem" }}>
<Skeleton variant="text" width="90%" animation="wave" />
<Skeleton variant="text" width="75%" animation="wave" />
<Skeleton variant="text" width="60%" animation="wave" />
</Box>
<Divider />
<Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.75, px: 2, py: 1.25 }}>
<Skeleton variant="rounded" width={72} height={22} animation="wave" />
<Skeleton variant="rounded" width={88} height={22} animation="wave" />
<Skeleton variant="rounded" width={64} height={22} animation="wave" />
</Box>
</Paper>
);
}
function QuestionBankSkeleton({ gridCols }) {
return (
<Box sx={{ display: "grid", gap: 2.5, gridTemplateColumns: gridCols, width: "100%" }}>
{Array.from({ length: 6 }).map((_, i) => (
<QuestionCardSkeleton key={i} />
))}
</Box>
);
}
// ─── Main ─────────────────────────────────────────────────────────────────────
const QuestionBank = ({ role = "teacher" }) => {
const theme = useTheme();
const isMobile = useMediaQuery("(max-width:900px)");
const [graphInstance] = useState(() => Graph2D());
const { speak, speaking } = ReadAloud();
const { tinyMCEtoString, regexBlank } = tinyMCEUtility();
const dispatch = useDispatch();
const navigate = useNavigate();
const { enqueueSnackbar } = useSnackbar();
const reduxState = useSelector((state) => state.TeacherQuestionBank);
const {
questionData,
_assignmentTypes,
_questionTypes,
_categories,
_difficulties,
_gradeLevels,
_subjects,
isLoading,
_pagination,
} = reduxState;
const deleteAction = _teacherDeletePersonalQuestion;
const fetchAction = _teacherFetchPersonalQuestions;
const [anchorEl, setAnchorEl] = useState(null);
const openMenu = Boolean(anchorEl);
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const [isShowAnswers, setShowAnswers] = useState(false);
const [columnLayout, setColumnLayout] = useState("1");
const [itemClick, setItemClick] = useState();
const [showDeleteDialog, setShowDeletDialog] = useState(false);
const [getQuestion, setGetQuestion] = useState(null);
const [filterDrawerOpen, setFilterDrawerOpen] = useState(false);
const [selectedAssignmentTypes, setSelectedAssignmentTypes] = useState([]);
const [selectedQuestionTypes, setSelectedQuestionTypes] = useState([]);
const [selectedCategories, setSelectedCategories] = useState([]);
const [selectedDifficulties, setSelectedDifficulties] = useState([]);
const [selectedGradeLevels, setSelectedGradeLevels] = useState([]);
const [selectedSubjects, setSelectedSubjects] = useState([]);
const [isPage, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(_pagination?.pageSize || 10);
const tablePageChange = (_, newPage) => setPage(newPage);
const pageChange = (_, newPage) => setPage(newPage - 1);
const tableRowsPageChange = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
const clickOpenMenu = (event, questionClicked) => {
setAnchorEl(event.currentTarget);
setGetQuestion(questionClicked);
};
const handleClose = () => {
setAnchorEl(null);
setGetQuestion(null);
};
const handleSpeakClick = (question, questionId) => {
const modifiedString = tinyMCEtoString(question.question);
const modifiedText = regexBlank ? modifiedString.replace(regexBlank, "blank") : modifiedString;
setItemClick(questionId);
speak(modifiedText);
};
const filteredQuestions = (questionData || []).filter(
(entry) =>
!search ||
["question", "correctAnswer", "assignmentType", "questionType", "teksCode"].some(
(key) => entry[key] && entry[key].toString().toLowerCase().includes(search.toLowerCase())
)
);
const hasActiveFilters =
search.trim() !== "" ||
selectedAssignmentTypes.length +
selectedQuestionTypes.length +
selectedCategories.length +
selectedDifficulties.length +
selectedGradeLevels.length +
selectedSubjects.length >
0;
const totalActiveFilters =
selectedAssignmentTypes.length +
selectedQuestionTypes.length +
selectedCategories.length +
selectedDifficulties.length +
selectedGradeLevels.length +
selectedSubjects.length;
const isEmptyBank = !hasActiveFilters && _pagination?.overAllEntries === 0;
const isPageEmpty = filteredQuestions.length === 0 && !hasActiveFilters && _pagination?.overAllEntries > 0;
const clickClearAllGlobalFilters = () => {
setSearch("");
setSelectedAssignmentTypes([]);
setSelectedQuestionTypes([]);
setSelectedCategories([]);
setSelectedDifficulties([]);
setSelectedGradeLevels([]);
setSelectedSubjects([]);
};
const handleAssignmentTypeChange = (e) => {
const { value, checked } = e.target;
setSelectedAssignmentTypes((p) => (checked ? [...p, value] : p.filter((i) => i !== value)));
};
const handleQuestionTypeChange = (e) => {
const { value, checked } = e.target;
setSelectedQuestionTypes((p) => (checked ? [...p, value] : p.filter((i) => i !== value)));
};
const handleCategoryChange = (e) => {
const { value, checked } = e.target;
setSelectedCategories((p) => (checked ? [...p, value] : p.filter((i) => i !== value)));
};
const handleDifficultyChange = (e) => {
const { value, checked } = e.target;
setSelectedDifficulties((p) => (checked ? [...p, value] : p.filter((i) => i !== value)));
};
const handleGradeLevelChange = (e) => {
const { value, checked } = e.target;
setSelectedGradeLevels((p) => (checked ? [...p, value] : p.filter((i) => i !== value)));
};
const handleSubjectChange = (e) => {
const { value, checked } = e.target;
setSelectedSubjects((p) => (checked ? [...p, value] : p.filter((i) => i !== value)));
};
const setEditQuestion = () => {
const editorType = isInteractiveDotsQuestion(getQuestion)
? "graph-multiple-select"
: getQuestion.questionType.toLowerCase();
navigate(`/${role}/question-bank/${editorType}`, {
state: { selectedQuestion: getQuestion },
});
setAnchorEl(null);
};
const clickDeleteOption = () => {
setShowDeletDialog(true);
setAnchorEl(null);
};
// Every query this component has actually asked the server for, most recent last
// — see the effects below for why one request can be requested twice.
const lastFetchedQueryRef = useRef(null);
const forceFetch = (queryString) => {
lastFetchedQueryRef.current = queryString;
dispatch(fetchAction(queryString));
};
const fetchIfNew = (queryString) => {
if (lastFetchedQueryRef.current === queryString) return;
forceFetch(queryString);
};
const buildQueryString = (pageIndexZero) => {
const queryParams = {
questionType: selectedQuestionTypes.length > 0 ? selectedQuestionTypes : undefined,
assignmentType: selectedAssignmentTypes.length > 0 ? selectedAssignmentTypes : undefined,
category: selectedCategories.length > 0 ? selectedCategories : undefined,
difficulty: selectedDifficulties.length > 0 ? selectedDifficulties : undefined,
gradeLevel: selectedGradeLevels.length > 0 ? selectedGradeLevels : undefined,
subject: selectedSubjects.length > 0 ? selectedSubjects : undefined,
searchText: debouncedSearch || undefined,
page: pageIndexZero + 1,
pageSize: rowsPerPage,
};
const filtered = Object.fromEntries(Object.entries(queryParams).filter(([, v]) => v !== undefined));
const qs = Object.entries(filtered)
.map(([k, v]) =>
Array.isArray(v)
? v.map((x) => `${k}=${encodeURIComponent(x)}`).join("&")
: `${k}=${encodeURIComponent(v)}`
)
.join("&");
return qs ? `?${qs}` : "";
};
const confirmDelete = async () => {
const rawId = getQuestion?._id ?? getQuestion?.id;
if (rawId == null || rawId === "") {
enqueueSnackbar("Could not delete: missing question id", { variant: "error" });
setShowDeletDialog(false);
setGetQuestion(null);
return;
}
const questionId = String(rawId);
const wasOnlyItemOnPage = (questionData || []).length === 1;
const shouldGoToPrev = wasOnlyItemOnPage && isPage > 0;
const pageToFetch = shouldGoToPrev ? isPage - 1 : isPage;
try {
await dispatch(deleteAction(questionId)).unwrap();
enqueueSnackbar("Question successfully deleted", { variant: "success" });
if (shouldGoToPrev) setPage(pageToFetch);
forceFetch(buildQueryString(pageToFetch));
} catch (rejected) {
enqueueSnackbar(snackbarTextFromDeleteRejection(rejected), { variant: "error" });
} finally {
setShowDeletDialog(false);
setGetQuestion(null);
}
};
// Modified by Allan Ninal — one request per distinct query.
//
// These two effects both dispatch a fetch, and on mount they both arrive at the
// SAME query string in the same commit, so the bank opened with two identical
// `?page=1&pageSize=10` requests every single time (measured, not inferred).
// `debouncedSearch` sat in both dependency lists, so every search did it again.
// This is the teacher's busiest screen, and the pair also race: two identical
// requests in flight means the response that wins is arbitrary.
//
// `fetchIfNew` skips a query already in flight/just issued; `forceFetch` is for
// the deliberate refetch after a delete, where the query is unchanged but the
// DATA is not. Keeping the ref current there stops the next effect run from
// re-issuing what the delete already asked for.
useEffect(() => {
setPage(0);
fetchIfNew(buildQueryString(0));
}, [
selectedAssignmentTypes,
selectedQuestionTypes,
selectedCategories,
selectedDifficulties,
selectedGradeLevels,
selectedSubjects,
rowsPerPage,
debouncedSearch,
dispatch,
]);
// `debouncedSearch` deliberately NOT a dependency here: the effect above already
// handles a search, and it resets to the first page — which is the correct
// behaviour for one. Leaving it here meant a search from page 3 also fired a
// request for page 3 of the NEW results before the reset landed.
useEffect(() => {
fetchIfNew(buildQueryString(isPage));
}, [isPage, dispatch]);
const [staticCounts, setStaticCounts] = useState({
assignmentTypes: {},
questionTypes: {},
categories: {},
difficulties: {},
gradeLevels: {},
subjects: {},
});
useEffect(() => {
Eif (Object.keys(_questionTypes).length === 0 && Object.keys(_assignmentTypes).length === 0) return;
setStaticCounts((prev) => ({
assignmentTypes: { ...prev.assignmentTypes, ..._assignmentTypes },
questionTypes: { ...prev.questionTypes, ..._questionTypes },
categories: { ...prev.categories, ..._categories },
difficulties: { ...prev.difficulties, ..._difficulties },
gradeLevels: { ...prev.gradeLevels, ..._gradeLevels },
subjects: { ...prev.subjects, ..._subjects },
}));
}, [_assignmentTypes, _questionTypes, _categories, _difficulties, _gradeLevels, _subjects]);
useEffect(() => {
const sa = localStorage.getItem("isShowAnswers");
const cl = localStorage.getItem("columnLayout");
Iif (sa !== null) setShowAnswers(sa === "true");
Iif (cl !== null) setColumnLayout(cl);
}, []);
let graphId = 0;
const displayQuestionType = (question) => {
const currentGraphId = needsSharedGraphCanvas(question) ? graphId++ : undefined;
return (
<QuestionDisplayRenderer
question={question}
showAnswers={isShowAnswers}
graphId={currentGraphId}
graphInstance={graphInstance}
/>
);
};
const filterPanelProps = {
role,
staticCounts,
selectedAssignmentTypes,
selectedQuestionTypes,
selectedCategories,
selectedDifficulties,
selectedGradeLevels,
selectedSubjects,
onAssignmentTypeChange: handleAssignmentTypeChange,
onQuestionTypeChange: handleQuestionTypeChange,
onCategoryChange: handleCategoryChange,
onDifficultyChange: handleDifficultyChange,
onGradeLevelChange: handleGradeLevelChange,
onSubjectChange: handleSubjectChange,
onClearAll: clickClearAllGlobalFilters,
};
const gridCols = isMobile
? "repeat(1, minmax(0, 1fr))"
: columnLayout === "2"
? "repeat(2, minmax(0, 1fr))"
: columnLayout === "3"
? "repeat(3, minmax(0, 1fr))"
: "repeat(1, minmax(0, 1fr))";
return (
<>
<YesNoOption
title="Confirm Delete"
message={`Do you want to Delete this question? (Question ${questionData?.indexOf(getQuestion) + 1})`}
showDialog={showDeleteDialog}
clickNo={() => setShowDeletDialog(false)}
clickYes={confirmDelete}
/>
<Box
sx={{
minHeight: "100vh",
bgcolor: (t) => (t.palette.mode === "dark" ? "background.default" : "#f8f9fc"),
}}
>
<AppBar position="relative" color="primary" elevation={0}>
<Toolbar>
<Typography variant="h6" fontWeight={700}>
My Questions
</Typography>
<Box sx={{ flexGrow: 1 }} />
{isMobile && (
<Tooltip title="Filters">
<IconButton color="inherit" onClick={() => setFilterDrawerOpen(true)}>
<FilterListIcon />
{totalActiveFilters > 0 && (
<Box
component="span"
sx={{
position: "absolute",
top: 6,
right: 6,
width: 8,
height: 8,
borderRadius: "50%",
bgcolor: "warning.main",
}}
/>
)}
</IconButton>
</Tooltip>
)}
</Toolbar>
</AppBar>
{/* Mobile filter drawer */}
<Drawer
anchor="left"
open={filterDrawerOpen}
onClose={() => setFilterDrawerOpen(false)}
PaperProps={{ sx: { width: 300 } }}
>
<QuestionBankFilterPanel {...filterPanelProps} onClose={() => setFilterDrawerOpen(false)} />
</Drawer>
<Box sx={{ display: "flex", gap: 0, alignItems: "flex-start" }}>
{/* Desktop filter sidebar */}
{!isMobile && (
<Box
sx={{
width: 260,
flexShrink: 0,
minHeight: "calc(100vh - 64px)",
overflowY: "auto",
}}
>
<QuestionBankFilterPanel {...filterPanelProps} />
</Box>
)}
{/* Main content */}
<Box sx={{ flex: 1, minWidth: 0, px: { xs: 2, sm: 3, md: 4 }, pb: 6 }}>
{/* Toolbar row */}
<Box
sx={{
display: "flex",
alignItems: { xs: "stretch", sm: "center" },
flexDirection: { xs: "column", sm: "row" },
gap: 1.5,
mt: 3,
mb: 2,
}}
>
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flex: 1, flexWrap: "wrap" }}>
<CreateNewQuestionButton role={role} />
<Box sx={{ width: { xs: "100%", sm: "50%" }, minWidth: 160 }}>
<SearchField search={search} setSearch={setSearch} placeHolder="Search Question" />
</Box>
</Box>
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexShrink: 0 }}>
{isMobile && totalActiveFilters > 0 && (
<Chip
label={`${totalActiveFilters} filter${totalActiveFilters !== 1 ? "s" : ""}`}
size="small"
color="primary"
onDelete={clickClearAllGlobalFilters}
sx={{ fontWeight: 700 }}
/>
)}
{!isMobile && (
<CardSettings
isShowAnswers={isShowAnswers}
setShowAnswers={setShowAnswers}
columnLayout={columnLayout}
setColumnLayout={setColumnLayout}
/>
)}
</Box>
</Box>
{isLoading ? (
<QuestionBankSkeleton gridCols={gridCols} />
) : (
<>
{filteredQuestions.length > 0 && (
<Box sx={{ display: "flex", justifyContent: "flex-end", mb: 1.5 }}>
<Typography variant="caption" color="text.secondary">
Page {_pagination?.currentPage || 1} of {_pagination?.totalPages || 1}
</Typography>
</Box>
)}
{filteredQuestions.length > 0 ? (
<Box
className="question-bank-items"
sx={{ display: "grid", gap: 2.5, gridTemplateColumns: gridCols, width: "100%" }}
>
{filteredQuestions.map((question, index) => (
<Paper
key={question._id + ""}
elevation={2}
sx={{
border: (t) => `1px solid ${t.palette.divider}`,
borderRadius: 3,
overflow: "hidden",
width: "100%",
minWidth: 0,
wordBreak: "break-word",
transition: (t) =>
t.transitions.create(
["box-shadow", "transform", "border-color"],
{ duration: t.transitions.duration.short }
),
"&:hover": {
boxShadow: (t) => t.shadows[8],
borderColor: "primary.main",
transform: "translateY(-3px)",
},
}}
>
{/* Card header */}
<Box
sx={{
px: 2,
py: 1.25,
display: "flex",
alignItems: "center",
justifyContent: "space-between",
flexWrap: "wrap",
gap: 1,
bgcolor: (t) => alpha(t.palette.primary.main, 0.04),
borderBottom: (t) => `1px solid ${t.palette.divider}`,
}}
>
<Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
<HtmlTooltip
title={
<Box
sx={{
display: "flex",
flexDirection: "column",
gap: 0.25,
}}
>
<span>Category: {question.assignmentType}</span>
<span>Type: {question.questionType}</span>
<span>Points: {question.points}</span>
<span>Difficulty: {question.difficulty}</span>
<span>TEKS Code: {question.teksCode}</span>
<span>
Date Created:{" "}
{utcToLocalTimeZone(question.createdDate)}
</span>
</Box>
}
>
<IconButton size="small">
<HelpIcon fontSize="small" />
</IconButton>
</HtmlTooltip>
<Typography variant="body2" fontWeight={600}>
{question.points} pts
</Typography>
</Box>
<Typography variant="caption" color="text.secondary">
{index + 1} of {filteredQuestions.length}
</Typography>
<Box sx={{ display: "flex", gap: 0.5 }}>
<IconButton
size="small"
color={
speaking && itemClick === question._id
? "primary"
: "default"
}
onClick={() => handleSpeakClick(question, question._id)}
>
<VolumeUpIcon fontSize="small" />
</IconButton>
<IconButton
id={`${role}-question-bank-iconbutton-option-${index + 1}`}
size="small"
aria-controls={
openMenu
? `${role}-question-bank-card-options`
: undefined
}
aria-haspopup="true"
aria-expanded={openMenu ? "true" : undefined}
onClick={(e) => clickOpenMenu(e, question)}
>
<MoreVertIcon fontSize="small" />
</IconButton>
<Menu
id={`${role}-question-bank-card-options`}
anchorEl={anchorEl}
open={openMenu && getQuestion?._id === question._id}
onClose={handleClose}
aria-hidden="false"
>
<List
sx={{ width: "100%", maxWidth: 200 }}
component="nav"
dense
>
<ListItemButton
id={`${role}-question-bank-card-option-edit`}
onClick={setEditQuestion}
>
<ListItemText primary="Edit" />
</ListItemButton>
<ListItemButton
id={`${role}-question-bank-card-option-delete`}
onClick={clickDeleteOption}
>
<ListItemText
primary="Delete"
sx={{ color: "error.main" }}
/>
</ListItemButton>
</List>
</Menu>
</Box>
</Box>
{/* Question body */}
<Box
sx={{
p: "1rem 1.5rem",
wordBreak: "break-word",
overflowWrap: "anywhere",
}}
>
{displayQuestionType(question, index + 1)}
</Box>
{/* Tags footer */}
<Divider />
<Box
sx={{
display: "flex",
flexWrap: "wrap",
gap: 0.75,
px: 2,
py: 1.25,
}}
>
{question.createdDate && (
<Chip
size="small"
color="primary"
label={utcToLocalTimeZone(question.createdDate)}
/>
)}
{question.assignmentType && (
<Chip
size="small"
color="primary"
label={question.assignmentType}
/>
)}
{question.questionType && (
<Chip
size="small"
color="primary"
label={question.questionType}
/>
)}
{question.category && (
<Chip size="small" color="primary" label={question.category} />
)}
{question.difficulty && (
<Chip
size="small"
color="primary"
label={question.difficulty}
/>
)}
{question.teksCode && (
<Chip size="small" color="primary" label={question.teksCode} />
)}
</Box>
</Paper>
))}
</Box>
) : isEmptyBank ? (
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 2,
py: 12,
}}
>
<LibraryBooksIcon sx={{ fontSize: 80, color: "action.disabled" }} />
<Typography variant="h6" color="text.secondary">
Your question bank is empty
</Typography>
<Typography
variant="body2"
color="text.secondary"
textAlign="center"
maxWidth={380}
>
Get started by clicking <strong>Create New Question</strong> above to add
your first question.
</Typography>
</Box>
) : isPageEmpty ? (
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 2,
py: 12,
}}
>
<LibraryBooksIcon sx={{ fontSize: 80, color: "action.disabled" }} />
<Typography variant="h6" color="text.secondary">
This page is empty
</Typography>
<Button variant="outlined" size="small" onClick={() => setPage(0)}>
Go to first page
</Button>
</Box>
) : (
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 2,
py: 12,
}}
>
<LibraryBooksIcon sx={{ fontSize: 80, color: "action.disabled" }} />
<Typography variant="h6" color="text.secondary">
No results found
</Typography>
<Typography
variant="body2"
color="text.secondary"
textAlign="center"
maxWidth={380}
>
{search.trim()
? `No questions match "${search}".`
: "No questions match the active filters."}
</Typography>
<Button variant="outlined" size="small" onClick={clickClearAllGlobalFilters}>
Clear all filters
</Button>
</Box>
)}
{filteredQuestions.length > 0 && (
<CombinedPagination
pagination={_pagination}
basicPage={{ isPage, rowsPerPage, pageChange }}
tablePage={{ isPage, rowsPerPage, tablePageChange, tableRowsPageChange }}
/>
)}
</>
)}
</Box>
</Box>
</Box>
</>
);
};
export default QuestionBank;
|