All files / src/utils/components TinyMCETextEditor.jsx

57.98% Statements 69/119
62.33% Branches 48/77
55.17% Functions 16/29
60.36% Lines 67/111

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                                                                      6x 44x 44x 44x 44x 44x 44x         44x 44x   44x       44x 44x   44x         9x     44x                             24x                                                                                                                                                                                                                     24x   24x 3x 2x 2x 2x       24x                       24x         1x 1x     1x       24x 4x 2x 2x 1x 1x 1x 1x 1x 1x           24x 4x 2x   2x       24x 6x 5x 5x 5x 5x               24x 2x 2x 2x 1x     24x 3x       3x 3x 1x             3x 2x         1x     3x       24x                                                                                                                                                                                                                 1x 1x 1x               1x 1x                      
import React, { useState, useRef } from "react";
import { Editor } from "@tinymce/tinymce-react";
import { useTheme } from "@mui/material/styles";
import "tinymce/tinymce";
import "tinymce/icons/default";
import "tinymce/themes/silver";
import "tinymce/plugins/link";
import "tinymce/plugins/image";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/advlist";
import "tinymce/plugins/autolink";
import "tinymce/plugins/charmap";
import "tinymce/plugins/preview";
import "tinymce/plugins/anchor";
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/code";
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/insertdatetime";
import "tinymce/plugins/media";
import "tinymce/plugins/wordcount";
import "tinymce/skins/ui/oxide/skin.min.css";
import "tinymce/skins/ui/oxide/content.min.css";
import "tinymce/models/dom/model";
// Import math-formula plugin (registers matheditor globally)
import "@/lib/tinymce/plugins/math-formula";
import { Box, Menu, MenuItem } from "@mui/material";
import tinyMCEUtility from "../helpers/tinyMCEUtility";
import { setupInsertTable } from "@/lib/tinymce/utils/tinyMCETableSetup";
import ImageUploadDialog from "@/lib/tinymce/plugins/image-upload/ImageUploadDialog";
import ImageResizeOverlay from "@/lib/tinymce/plugins/image-upload/ImageResizeOverlay";
import { getGraph2dEditorUrl } from "@/lib/tinymce/plugins/graph2d/plugin";
import "@/lib/tinymce/plugins/graph2d/tinymceGraph2dOpenUrlPlugin.js";
 
const TextEditor = ({ editContent, setEditContent, questionTypes, onImageUpload, disabledToolbarButtons = [] }) => {
    const theme = useTheme();
    const editorRef = useRef(null);
    const [imgDialogOpen, setImgDialogOpen] = useState(false);
    const [replaceImgNode, setReplaceImgNode] = useState(null);
    const [imgContextMenu, setImgContextMenu] = useState(null); // { mouseX, mouseY, node }
    const [selectedImg, setSelectedImg] = useState(null);
 
    // The editable content area (iframe body) otherwise falls back to the browser's
    // default white background regardless of the app theme — pin it to the theme
    // surface instead so it matches dark mode / colored presets.
    const surfaceBg = theme.palette.background.paper;
    const textColor = theme.palette.text.primary;
 
    const { dragDropHTML, dropDownMenuHTML, hasEditorContent, EMBEDDED_CHOICE_ATTR, buildEmbeddedChoiceHTML } =
        tinyMCEUtility();
 
    const showInsertResponse =
        questionTypes && (questionTypes.includes("dragAndDrop") || questionTypes.includes("dropDownMenu"));
    const showMarkEmbeddedChoice = questionTypes && questionTypes.includes("embeddedMultipleChoice");
 
    const handleEditorChange = (content) => {
        // Text-less content (an image, table, math formula, or graph) is still real
        // content — only collapse to "" when there's neither text nor such an element.
        // Modified by Allan Ninal — the predicate now lives in tinyMCEUtility so the
        // editors can apply the same test before saving.
        setEditContent(hasEditorContent(content) ? content : "");
    };
 
    return (
        <>
            <Box
                sx={{
                    "& .tox-edit-area, & .tox-edit-area__iframe, & iframe": {
                        backgroundColor: `${surfaceBg} !important`,
                    },
                }}
            >
                <Editor
                    key={theme.palette.mode}
                    id="tinymce-input-editor"
                    value={editContent}
                    onEditorChange={handleEditorChange}
                    onInit={(_, editor) => {
                        editorRef.current = editor;
                    }}
                    init={{
                        license_key: "gpl",
                        branding: false,
                        skin: false,
                        content_css: false,
                        // Do not rewrite data:/http(s): URLs; rewriting can break inserted images
                        convert_urls: false,
                        relative_urls: false,
                        remove_script_host: false,
                        // height: 200,
                        menubar: false,
                        statusbar: false,
                        forced_root_block: "p",
                        plugins: [
                            "advlist",
                            "autolink",
                            "lists",
                            "link",
                            "image",
                            "charmap",
                            "preview",
                            "anchor",
                            "searchreplace",
                            "visualblocks",
                            "code",
                            "fullscreen",
                            "insertdatetime",
                            "media",
                            "table",
                            "wordcount",
                            "matheditor", // math-formula plugin
                            "graph2d", // cartesian2d-style URL dialog → /graph-editor (tinymceGraph2dOpenUrlPlugin.js)
                        ],
                        toolbar: [
                            "undo redo | blocks | bold italic underline strikethrough |",
                            "matheditor | graph2d | insertimage |",
                            "align lineheight | numlist bullist | inserttable | borderedtext |",
                            showInsertResponse
                                ? "removeformat | insertDropOption"
                                : showMarkEmbeddedChoice
                                  ? "removeformat | markembeddedchoice"
                                  : "removeformat",
                        ].join(" "),
                        // Disable TinyMCE's built-in resize — custom ImageResizeOverlay handles it instead.
                        object_resizing: false,
                        // Table resize configuration
                        table_sizing_mode: "relative",
                        table_column_resizing: "resizetable",
                        table_use_colgroups: true,
                        formats: {
                            alignleft: {
                                selector: "p,h1,h2,h3,h4,h5,h6,td,th,span.graph2d-embed",
                                styles: { "text-align": "left" },
                            },
                            aligncenter: {
                                selector: "p,h1,h2,h3,h4,h5,h6,td,th,span.graph2d-embed",
                                styles: { "text-align": "center" },
                            },
                            alignright: {
                                selector: "p,h1,h2,h3,h4,h5,h6,td,th,span.graph2d-embed",
                                styles: { "text-align": "right" },
                            },
                            alignjustify: {
                                selector: "p,h1,h2,h3,h4,h5,h6,td,th,span.graph2d-embed",
                                styles: { "text-align": "justify" },
                            },
                            // Wraps the selected block(s) in a bordered container — same
                            // wrapper-block shape TinyMCE uses for its built-in blockquote format.
                            borderedtext: [
                                {
                                    block: "div",
                                    classes: "bordered-text-block",
                                    wrapper: true,
                                    remove: "all",
                                },
                            ],
                        },
                        // Math formula styles are loaded from tinymce-erudition-plugins/plugins/math/styles.css
                        content_style: `html, body { background-color: ${surfaceBg} !important; }
                        body { line-height: 1.5; font-weight: normal; font-size: 20px; color: ${textColor}; }
                        p { margin: 0; padding: 0; }
                        /* Inline-block so paragraph text-align (left/center/right) can position the graph. */
                        .graph2d-embed { display: inline-block; vertical-align: middle; }
                        .graph2d-embed img { display: block; height: auto; vertical-align: middle; }
                        /* Selection outline only. */
                        .graph2d-embed[data-mce-selected="1"] { outline: 2px solid #1976d2; outline-offset: 2px; }
                        /* Hide the preview/clone TinyMCE shows when selecting the graph (offscreen selection). */
                        .mce-offscreen-selection:has(.graph2d-embed) { display: none !important; }
                        /* Pointer cursor on inserted images */
                        img:not(.graph2d-embed img) { cursor: pointer; }
                        /* Ensure uploaded/inline images size correctly in the editor */
                        body img { max-width: 100%; height: auto; vertical-align: middle; }
                        /* Bordered-text block — currentColor so it adapts to the surrounding text color. */
                        .bordered-text-block { border: 1px solid currentColor; border-radius: 4px; padding: 8px 12px; margin: 8px 0; }
`,
                        htmlAllowedTags: [".*"],
                        htmlAllowedAttrs: [".*"],
                        extended_valid_elements:
                            "*[.*],span[class|data-latex|contenteditable|style],div[class|contenteditable|style],math-field[read-only|style|class]",
                        custom_elements: "math-field",
                        contextmenu: false,
                        draggable_modal: true,
                        graph2d_url: getGraph2dEditorUrl(),
                        graph2d_size_percent: 90,
                        setup: (editor) => {
                            setupInsertTable(editor, { disabled: disabledToolbarButtons.includes("inserttable") });
 
                            editor.on("keydown", (e) => {
                                if (e.key === " " || e.keyCode === 32) {
                                    const content = editor.getContent();
                                    const plainText = content.replace(/<[^>]+>/g, "").replace(/&nbsp;/gi, " ");
                                    if (!plainText.trim()) e.preventDefault();
                                }
                            });
 
                            editor.ui.registry.addToggleButton("borderedtext", {
                                icon: "border-style",
                                tooltip: "Bordered Text",
                                onSetup: (api) => {
                                    const updateActive = () => api.setActive(editor.formatter.match("borderedtext"));
                                    updateActive();
                                    editor.on("NodeChange", updateActive);
                                    return () => editor.off("NodeChange", updateActive);
                                },
                                onAction: () => editor.formatter.toggle("borderedtext"),
                            });
 
                            editor.ui.registry.addButton("insertimage", {
                                icon: "image",
                                tooltip: "Insert Image",
                                onSetup: disabledToolbarButtons.includes("insertimage")
                                    ? (api) => {
                                          api.setEnabled(false);
                                          return () => {};
                                      }
                                    : undefined,
                                onAction: () => setImgDialogOpen(true),
                            });
 
                            // Disable plugin-registered buttons (e.g. matheditor) after editor init
                            if (disabledToolbarButtons.length > 0) {
                                editor.on("init", () => {
                                    const container = editor.getContainer();
                                    if (!container) return;
                                    disabledToolbarButtons.forEach((name) => {
                                        const btn = container.querySelector(`button[data-mce-name="${name}"]`);
                                        Eif (btn) {
                                            btn.disabled = true;
                                            btn.setAttribute("aria-disabled", "true");
                                            btn.classList.add("tox-tbtn--disabled");
                                        }
                                    });
                                });
                            }
                            // Click on image: show custom resize overlay
                            editor.on("click", (e) => {
                                if (e.target.nodeName === "IMG" && !editor.dom.getParent(e.target, ".graph2d-embed")) {
                                    setSelectedImg(e.target);
                                } else {
                                    setSelectedImg(null);
                                }
                            });
                            // Right-click on image: show "Delete Image" only
                            editor.on("contextmenu", (e) => {
                                if (e.target.nodeName === "IMG") {
                                    e.preventDefault();
                                    const iframe = editor.getContainer()?.querySelector("iframe");
                                    const rect = iframe?.getBoundingClientRect() ?? { left: 0, top: 0 };
                                    setImgContextMenu({
                                        mouseX: rect.left + e.clientX,
                                        mouseY: rect.top + e.clientY,
                                        node: e.target,
                                    });
                                }
                            });
                            // When selection is inside a graph placeholder, hide control selection so the graph doesn't appear twice.
                            editor.on("NodeChange", () => {
                                const node = editor.selection.getNode();
                                const inGraph = node && editor.dom.getParent(node, ".graph2d-embed");
                                if (inGraph && editor.selection.controlSelection?.hideResizeRect) {
                                    editor.selection.controlSelection.hideResizeRect();
                                }
                            });
                            if (showInsertResponse) {
                                editor.ui.registry.addMenuButton("insertDropOption", {
                                    icon: "comment",
                                    tooltip: "Insert Response",
                                    fetch: (callback) => {
                                        const items = [];
                                        if (questionTypes.includes("dragAndDrop"))
                                            items.push({
                                                type: "menuitem",
                                                text: "Insert Drag-and-drop",
                                                onAction: () => {
                                                    editor.insertContent(dragDropHTML);
                                                },
                                            });
                                        if (questionTypes.includes("dropDownMenu"))
                                            items.push({
                                                id: "insert-dropdown-menu",
                                                type: "menuitem",
                                                text: "Insert Dropdown Menu",
                                                onAction: () => {
                                                    editor.insertContent(dropDownMenuHTML);
                                                },
                                            });
                                        callback(items);
                                    },
                                });
                            }
                            Iif (showMarkEmbeddedChoice) {
                                editor.ui.registry.addButton("markembeddedchoice", {
                                    icon: "underline",
                                    tooltip: "Mark selected text as an answer choice",
                                    onAction: () => {
                                        // Read the selection as HTML, not text — a math formula (see
                                        // math-formula/plugin.js) renders as a <span class="mfe-formula">
                                        // with no meaningful plain-text content, so building the choice
                                        // span from getContent({format:"text"}) silently dropped/mangled
                                        // formula choices instead of marking them.
                                        const selectedHtml = editor.selection.getContent({ format: "html" });
                                        if (!selectedHtml || !selectedHtml.trim()) return;
 
                                        const startNode = editor.selection.getStart();
                                        const endNode = editor.selection.getEnd();
                                        const overlapsExistingChoice =
                                            editor.dom.getParent(startNode, `[${EMBEDDED_CHOICE_ATTR}]`) ||
                                            editor.dom.getParent(endNode, `[${EMBEDDED_CHOICE_ATTR}]`) ||
                                            selectedHtml.includes(EMBEDDED_CHOICE_ATTR);
                                        if (overlapsExistingChoice) return;
 
                                        // Punctuation adjacent to the selection stays outside the choice
                                        // span (EI implementation spec 10 — "Punctuation"). Trim only real
                                        // passage text nodes — never descend into a contenteditable="false"
                                        // atomic element (a math formula, an existing marker, ...), so a
                                        // formula's own rendered markup (e.g. a leading "(" in "(x+2)") is
                                        // never mistaken for passage punctuation and stripped out of it.
                                        const container = document.createElement("div");
                                        container.innerHTML = selectedHtml;
 
                                        const isProtectedTextNode = (node) =>
                                            !!node.parentElement?.closest('[contenteditable="false"]');
 
                                        const firstWalker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, {
                                            acceptNode: (node) =>
                                                isProtectedTextNode(node)
                                                    ? NodeFilter.FILTER_REJECT
                                                    : NodeFilter.FILTER_ACCEPT,
                                        });
                                        const firstTextNode = firstWalker.nextNode();
                                        let leadingText = "";
                                        if (firstTextNode) {
                                            const match = firstTextNode.data.match(/^[\s.,!?;:'"()[\]]+/);
                                            if (match) {
                                                leadingText = match[0];
                                                firstTextNode.data = firstTextNode.data.slice(leadingText.length);
                                            }
                                        }
 
                                        const lastWalker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, {
                                            acceptNode: (node) =>
                                                isProtectedTextNode(node)
                                                    ? NodeFilter.FILTER_REJECT
                                                    : NodeFilter.FILTER_ACCEPT,
                                        });
                                        let lastTextNode = null;
                                        while (lastWalker.nextNode()) lastTextNode = lastWalker.currentNode;
                                        let trailingText = "";
                                        if (lastTextNode) {
                                            const match = lastTextNode.data.match(/[\s.,!?;:'"()[\]]+$/);
                                            if (match) {
                                                trailingText = match[0];
                                                lastTextNode.data = lastTextNode.data.slice(
                                                    0,
                                                    lastTextNode.data.length - trailingText.length
                                                );
                                            }
                                        }
 
                                        const coreHtml = container.innerHTML;
                                        if (!coreHtml || !coreHtml.trim()) return;
 
                                        const id = `choice-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
                                        editor.selection.setContent(
                                            `${leadingText}${buildEmbeddedChoiceHTML(id, coreHtml)}${trailingText}`
                                        );
                                    },
                                });
                            }
                        },
                    }}
                />
            </Box>
            <ImageResizeOverlay imgNode={selectedImg} editorRef={editorRef} onClose={() => setSelectedImg(null)} />
            <ImageUploadDialog
                open={imgDialogOpen}
                onClose={() => {
                    setImgDialogOpen(false);
                    setReplaceImgNode(null);
                }}
                editorRef={editorRef}
                replaceNode={replaceImgNode}
                onImageUpload={onImageUpload}
            />
            <Menu
                open={Boolean(imgContextMenu)}
                onClose={() => setImgContextMenu(null)}
                anchorReference="anchorPosition"
                anchorPosition={
                    imgContextMenu ? { top: imgContextMenu.mouseY, left: imgContextMenu.mouseX } : undefined
                }
            >
                <MenuItem
                    size="small"
                    onClick={() => {
                        setReplaceImgNode(imgContextMenu?.node ?? null);
                        setImgContextMenu(null);
                        setImgDialogOpen(true);
                    }}
                >
                    Change Image
                </MenuItem>
                <MenuItem
                    size="small"
                    onClick={() => {
                        editorRef.current?.dom.remove(imgContextMenu.node);
                        setImgContextMenu(null);
                    }}
                >
                    Delete Image
                </MenuItem>
            </Menu>
        </>
    );
};
 
export default TextEditor;