All files / src/utils/components/question-bank/question-content/free-response FreeResponseEditor.jsx

91.07% Statements 51/56
90.14% Branches 64/71
76.47% Functions 13/17
90.56% Lines 48/53

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                                                                                                        3x                                                                                           335x   335x 335x     335x     335x 335x 335x     335x 670x 670x 670x 670x 670x       335x 1x 1x 1x 1x 1x 1x                         335x 13x 6x 6x   7x 7x       335x 13x   7x       7x 6x         335x 335x 25x             310x 2x             308x               308x     335x   335x 17x 3x       335x                                                                                                                                                                                                                                                                                                                                     939x             29x                                                                                                                                                                                                                                             1x                                                                                       1x                                                                                                                          
import React, { useEffect, useState } from "react";
import "./FreeResponseEditor.scss";
import {
    Alert,
    Box,
    Button,
    Card,
    CardContent,
    Collapse,
    IconButton,
    LinearProgress,
    Paper,
    Stack,
    Tooltip,
    Typography,
} from "@mui/material";
import { useTheme } from "@mui/material/styles";
import {
    useQuestionForm,
    TextEditorDialog,
    QuestionSettings,
    QuickTipsCard,
    getClassificationProgress,
    editorContainerSx,
    editorHeaderSx,
    cardHeaderHoverSx,
    editorCardSx,
    contentPreviewSx,
    emptyStateSx,
    tipsCardSx,
} from "../utils";
import TinyMCETextEditor from "@/utils/components/TinyMCETextEditor";
import ReadOnlyMathEditor from "@/utils/components/TinyMCETextEditorReadOnly";
import UnsavedChangesDialog from "@/utils/components/UnsavedChangesDialog";
import tinyMCEUtility from "@/utils/helpers/tinyMCEUtility";
 
// 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 NoteAddIcon from "@mui/icons-material/NoteAdd";
import RestartAltIcon from "@mui/icons-material/RestartAlt";
import SettingsIcon from "@mui/icons-material/Settings";
import RateReviewIcon from "@mui/icons-material/RateReview";
 
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,
        handleImageUpload,
        resetFields,
        SaveProgress,
        navigationBlocker,
    } = useQuestionForm(role);
 
    const { hasEditorContent } = tinyMCEUtility();
    const theme = useTheme();
 
    // Free-response specific state
    const [isLatex, setLatex] = useState("");
 
    // Expandable sections
    const [questionDetailsExpanded, setQuestionDetailsExpanded] = useState(false);
    const [answerDetailsExpanded, setAnswerDetailsExpanded] = useState(false);
    const [settingsExpanded, setSettingsExpanded] = useState(true);
 
    // Progress calculation
    const getProgress = () => {
        let progress = 0;
        if (questionText) progress += 25;
        if (isLatex) progress += 25;
        progress += (getClassificationProgress(values) / 100) * 50;
        return Math.round(progress);
    };
 
    // Reset all values
    const handleReset = () => {
        setQuestionText("");
        setQuestionDetailsText("");
        setAnswerDetailsText("");
        setLatex("");
        setDisplayError({ status: false, message: "" });
        resetFields();
    };
 
    /**
     * Modified by Allan Ninal — the model answer was not checked before saving.
     *
     * Every other question editor refuses to save without its answer content
     * (multiple-choice and checkbox want two choices and a correct one, drag-and-drop
     * a choice and a blank, drop-down a menu with responses). Free-response has a
     * single piece of answer content and had no check at all, so a question could be
     * saved with nothing for a marker to grade against — while its own tooltip lists
     * the model answer under "Required Fields".
     */
    const hasModelAnswer = () => {
        if (!hasEditorContent(isLatex)) {
            setDisplayError({ status: true, message: "Please write a model answer before saving." });
            return false;
        }
        setDisplayError({ status: false, message: "" });
        return true;
    };
 
    // Submit handler
    const createNewQuestion = async () => {
        if (!hasModelAnswer()) return;
 
        const questionPayload = {
            ...buildBasePayload("Free-response", isLatex),
        };
 
        await submitQuestion(questionPayload, () => {
            setLatex("");
        });
    };
 
    // Dialog management
    const getActiveDialog = () => {
        if (showQuestionTextEditor)
            return {
                type: "question",
                content: questionTextEditor,
                setContent: setQuestionTextEditor,
                save: saveQuestion,
                cancel: cancelQuestion,
            };
        if (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();
 
    useEffect(() => {
        loadEditData((data) => {
            setLatex(data.correctAnswer?.answers || "");
        });
    }, []);
 
    return (
        <Box className="freeresponse-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="checkbox-header" elevation={0} sx={editorHeaderSx()}>
                <Box className="checkbox-header-content">
                    <Box className="checkbox-header-left">
                        <RateReviewIcon sx={{ fontSize: 28, color: "primary.main" }} />
                        <Box>
                            <Typography variant="h5" fontWeight={600}>
                                {editQuestion ? "Edit Question" : "Create Free-response Question"}
                            </Typography>
                            <Typography variant="body2" color="text.secondary">
                                {editQuestion
                                    ? "Update your question details"
                                    : "Build an open-ended question with a model answer"}
                            </Typography>
                        </Box>
                    </Box>
                    <Box className="checkbox-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 }}
                                            >
                                                {isLatex ? (
                                                    <CheckCircleIcon fontSize="small" color="success" />
                                                ) : (
                                                    <CheckCircleOutlineIcon fontSize="small" />
                                                )}
                                                Model answer
                                            </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="checkbox-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="checkbox-main">
                {/* Left Panel */}
                <Box className="checkbox-left-panel">
                    {/* Question Card */}
                    <Card className="checkbox-card" sx={editorCardSx(theme)}>
                        <CardContent>
                            <Box className="checkbox-card-header">
                                <Box className="checkbox-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="checkbox-content-preview" sx={contentPreviewSx()}>
                                    <ReadOnlyMathEditor content={questionText} />
                                </Paper>
                            ) : (
                                <Box className="checkbox-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="checkbox-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>
 
                    {/* Model Answer Card */}
                    <Card className="checkbox-card" sx={editorCardSx(theme)}>
                        <CardContent>
                            <Box className="checkbox-card-header">
                                <Box className="checkbox-card-title">
                                    <RateReviewIcon color="primary" />
                                    <Typography variant="h6">Model Answer</Typography>
                                    {isLatex && <CheckCircleIcon color="success" fontSize="small" />}
                                </Box>
                            </Box>
 
                            {/* Only render when no dialog is open to avoid TinyMCE ID conflict */}
                            {!activeDialog && (
                                <TinyMCETextEditor
                                    editContent={isLatex}
                                    setEditContent={setLatex}
                                    onImageUpload={handleImageUpload}
                                />
                            )}
                        </CardContent>
                    </Card>
 
                    {/* Answer Explanation Card - Collapsible */}
                    <Card className="checkbox-card" sx={editorCardSx(theme)}>
                        <CardContent>
                            <Box
                                className="checkbox-card-header clickable"
                                onClick={() => setAnswerDetailsExpanded(!answerDetailsExpanded)}
                                sx={cardHeaderHoverSx(theme)}
                            >
                                <Box className="checkbox-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="checkbox-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="checkbox-right-panel">
                    <QuickTipsCard
                        className="checkbox-card checkbox-tips-card"
                        sx={{ ...editorCardSx(theme), ...tipsCardSx(theme) }}
                        tips={[
                            "Write a clear, open-ended question",
                            "Provide a model answer for reference",
                            "Use question details to add hints or context",
                            "Add an explanation to guide grading",
                        ]}
                    />
 
                    <Card className="checkbox-card checkbox-settings-card" sx={editorCardSx(theme)}>
                        <CardContent>
                            <Box
                                className="checkbox-card-header clickable"
                                onClick={() => setSettingsExpanded(!settingsExpanded)}
                                sx={cardHeaderHoverSx(theme)}
                            >
                                <Box className="checkbox-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;