All files / src/utils/components TinyMCETextEditorReadOnly.jsx

73.75% Statements 59/80
42.62% Branches 26/61
87.5% Functions 14/16
77.77% Lines 56/72

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                                    17x     270x                                                           54x 54x 54x 54x 54x 54x         54x 54x                                   18x 18x                     72x 72x   72x 144x 144x 144x     72x 72x   72x 414x   270x 414x       270x                       17x               46x 46x 46x 46x 46x 46x 46x 46x 46x                         46x 46x   46x   18x 18x 18x         46x 32x         46x 32x                                                                                                                                     18x 18x         18x 18x 18x       18x 36x         36x             46x   46x   46x                                                                                      
import React, { useCallback, useEffect, useMemo, 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/autoresize";
import "tinymce/models/dom/model";
import "@/lib/tinymce/plugins/math-formula";
import "@/lib/tinymce/plugins/graph2d/tinymceGraph2dOpenUrlPlugin.js";
import { getGraph2dEditorUrl } from "@/lib/tinymce/plugins/graph2d/plugin";
import { Box } from "@mui/material";
import {
    questionCardSurfaceBg,
    READ_ONLY_MATH_CHOICE_CONTENT_PADDING,
    READ_ONLY_MATH_CONTENT_PADDING,
} from "@/utils/components/question-bank/question-display/utils/questionCardStyles";
 
const GRAPH_SELECTION_OUTLINE = "#1976d2";
 
function isLightBackground(color) {
    Eif (!color) return false;
    const normalized = color.replace(/\s/g, "").toLowerCase();
    if (
        normalized === "white" ||
        normalized === "#fff" ||
        normalized === "#ffffff" ||
        normalized === "rgb(255,255,255)" ||
        normalized === "rgba(255,255,255,1)"
    ) {
        return true;
    }
    const rgb = normalized.match(/^rgba?\((\d+),(\d+),(\d+)/);
    if (rgb) {
        const [r, g, b] = rgb.slice(1, 4).map(Number);
        return r >= 240 && g >= 240 && b >= 240;
    }
    return false;
}
 
/**
 * TinyMCE's silver theme renders the UI hidden (inline `visibility:hidden`
 * on `.tox-tinymce`) while it measures layout, then reveals it once its own
 * post-init promise chain resolves. With `skin: false` (self-hosted, no skin
 * stylesheet) that promise never resolves for a subset of instances when many
 * editors mount at once — the container is left permanently hidden and frozen
 * at `autoresize_min_height`, even though the iframe body has the real content.
 * Revealing and re-measuring by hand here sidesteps that stuck promise instead
 * of depending on it.
 */
function revealAndResizeEditor(editor) {
    const container = editor?.getContainer?.();
    const body = editor?.getBody?.();
    Iif (!container || !body) return;
    const height = `${body.scrollHeight}px`;
    container.style.visibility = "visible";
    container.style.height = height;
    // getContainer() is only the outer `.tox-tinymce` shell — its `.tox-edit-area`/iframe
    // children keep their own stale height (overflow: visible by default), so without this
    // the taller-than-needed iframe visually bleeds past the shrunk container and paints
    // over whatever content follows it on the page.
    Eif (editor.iframeElement) {
        editor.iframeElement.style.height = height;
    }
}
 
/**
 * Keeps `iframeElement.style.height` mirrored to the container's height on an
 * ongoing basis. TinyMCE's own `autoresize` plugin keeps `.tox-tinymce` (the
 * container) correctly sized to the iframe body's content at all times, but
 * `revealAndResizeEditor` above is the ONLY code that sizes the iframe
 * element itself, and it only runs from the `init`/`SetContent` handlers.
 * Content that grows the body height AFTER those fire — e.g. a graph2d
 * embed's `blob:` URL image, which decodes and loads asynchronously — never
 * gets a matching iframe resize, so the stale (shorter) iframe height clips
 * the now-taller body via its `overflow: hidden`. A ResizeObserver on the
 * container catches that late growth (autoresize already reacts to it) and
 * reapplies it to the iframe.
 */
function observeContainerResize(editor) {
    const container = editor?.getContainer?.();
    Eif (!container || typeof ResizeObserver === "undefined") return undefined;
    const ro = new ResizeObserver(() => {
        if (editor.iframeElement) {
            editor.iframeElement.style.height = container.style.height || `${container.clientHeight}px`;
        }
    });
    ro.observe(container);
    return () => ro.disconnect();
}
 
function applyReadOnlyEditorColors(editor, textColor, backgroundColor) {
    const doc = editor?.getDoc?.();
    Iif (!doc) return;
 
    const applyTo = (el) => {
        Iif (!el) return;
        el.style.setProperty("background-color", backgroundColor, "important");
        el.style.setProperty("color", textColor, "important");
    };
 
    applyTo(doc.documentElement);
    applyTo(doc.body);
 
    doc.querySelectorAll("*").forEach((node) => {
        if (node === doc.documentElement || node === doc.body) return;
 
        const inlineBg = node.style?.backgroundColor;
        Iif (isLightBackground(inlineBg)) {
            node.style.setProperty("background-color", "transparent", "important");
        }
 
        node.style.setProperty("color", textColor, "important");
    });
}
 
/**
 * @param {{ content?: string, backgroundColor?: string, sx?: object, onEditorInit?: Function, fontSize?: string }} props
 * backgroundColor must be a solid color — TinyMCE iframes cannot inherit parent backgrounds.
 * fontSize overrides the compact/non-compact default (e.g. so a caller can render question
 * text, choices, and math formulas/symbols — the `.mfe-formula` rule is `font-size: 1em`,
 * so it tracks whatever this ends up being — all at one uniform size; see
 * studentQuestionSurfaces.js's STUDENT_QUESTION_FONT_SIZE for the take-assignment page's use).
 */
const TinyMCETextEditorReadOnly = ({
    content,
    backgroundColor,
    compact = false,
    sx: sxProp,
    onEditorInit,
    fontSize: fontSizeProp,
}) => {
    const theme = useTheme();
    const editorRef = useRef(null);
    const textColor = theme.palette.text.primary;
    const surfaceBg = backgroundColor ?? questionCardSurfaceBg(theme);
    const contentPadding = compact ? READ_ONLY_MATH_CHOICE_CONTENT_PADDING : READ_ONLY_MATH_CONTENT_PADDING;
    const lineHeight = compact ? 1.3 : 1.5;
    const fontSize = fontSizeProp ?? (compact ? "17px" : "20px");
    const minHeight = compact ? 22 : 24;
    const bottomMargin = compact ? 2 : 4;
 
    // A caller that derives `backgroundColor` from state set in a post-mount effect
    // (e.g. a selected multiple-choice/checkbox option restoring its answer on
    // question revisit — see MultipleChoiceOption.jsx/CheckboxOption.jsx) can change
    // colors before TinyMCE's own async init has finished, i.e. before `handleInit`
    // ever runs. `@tinymce/tinymce-react` only registers `onInit` once at mount, so
    // by the time it actually fires it can call a stale closure still holding the
    // FIRST render's (wrong) colors — the live-update effect below can't correct
    // this either, since it only re-runs on a LATER color change, not this first
    // one. Reading colors from a ref that's kept current every render, instead of
    // closing over them, means `handleInit` always applies whatever's freshest at
    // the moment TinyMCE actually calls it, regardless of when that is.
    const latestColorsRef = useRef({ textColor, surfaceBg });
    latestColorsRef.current = { textColor, surfaceBg };
 
    const handleInit = useCallback(
        (_, editor) => {
            editorRef.current = editor;
            applyReadOnlyEditorColors(editor, latestColorsRef.current.textColor, latestColorsRef.current.surfaceBg);
            onEditorInit?.(editor);
        },
        [onEditorInit]
    );
 
    useEffect(() => {
        Iif (editorRef.current) {
            applyReadOnlyEditorColors(editorRef.current, textColor, surfaceBg);
        }
    }, [textColor, surfaceBg]);
 
    const editorInit = useMemo(
        () => ({
            license_key: "gpl",
            branding: false,
            skin: false,
            content_css: false,
            readonly: true,
            toolbar: false,
            menubar: false,
            statusbar: false,
            plugins: ["autoresize", "matheditor", "graph2d"],
            autoresize_bottom_margin: bottomMargin,
            autoresize_min_height: minHeight,
            min_height: minHeight,
            graph2d_url: getGraph2dEditorUrl(),
            graph2d_size_percent: 90,
            object_resizing: false,
            content_style: `html, body {
                    background-color: ${surfaceBg} !important;
                    color: ${textColor} !important;
                    line-height: ${lineHeight};
                    cursor: default;
                    caret-color: transparent;
                    margin: 0;
                    padding: ${contentPadding};
                    overflow: hidden;
                    font-size: ${fontSize};
                }
                body p, body div, body li, body td, body th, body a {
                    background-color: transparent !important;
                    color: ${textColor} !important;
                }
                body span:not([style*="background-color"]) {
                    background-color: transparent !important;
                    color: ${textColor} !important;
                }
                .mfe-formula, .mfe-formula * {
                    background: transparent !important;
                    background-color: transparent !important;
                }
                p { margin: 0; padding: 0; }
                .bordered-text-block { border: 1px solid currentColor; border-radius: 4px; padding: 8px 12px; margin: 8px 0; }
                .graph2d-embed { display: inline-block; vertical-align: middle; }
                .graph2d-embed img { display: block; height: auto; vertical-align: middle; }
                .graph2d-embed[data-mce-selected="1"] { outline: 2px solid ${GRAPH_SELECTION_OUTLINE}; outline-offset: 2px; }
                .mce-offscreen-selection:has(.graph2d-embed) { display: none !important; }`,
            // Explicit allow-list instead of the wildcard "*[.*]" — prevents
            // arbitrary attributes/event-handlers (on*, javascript: etc.) from
            // surviving in read-only rendered content.
            // math-field: custom element for mathlive (read-only attribute required)
            // span.mfe-formula: math-formula plugin wrapper (data-latex carries LaTeX source)
            // div.graph2d-embed: graph2d plugin placeholder (data-graph2d carries encoded graph)
            extended_valid_elements: [
                "span[class|style|data-latex|contenteditable|data-mce-selected]",
                "div[class|style|data-graph2d|contenteditable|data-mce-selected]",
                "math-field[read-only|style|class|data-mce-selected]",
            ].join(","),
            custom_elements: "math-field",
            // `editorInit` (this whole object) is only ever actually handed to
            // tinymce.init() once — @tinymce/tinymce-react doesn't reinitialize the
            // editor when a recomputed `init` prop comes in on a later render — so
            // these handlers close over whichever textColor/surfaceBg were current
            // at THAT first render. Reading latestColorsRef.current instead (kept
            // fresh every render, see above) means "init"/"SetContent" firing late
            // — e.g. after a post-mount effect corrects a restored selection's color
            // — still paints the color that's actually current instead of replaying
            // the stale one baked in at mount.
            setup: (editor) => {
                editor.on("init", () => {
                    applyReadOnlyEditorColors(
                        editor,
                        latestColorsRef.current.textColor,
                        latestColorsRef.current.surfaceBg
                    );
                    revealAndResizeEditor(editor);
                    const stopObserving = observeContainerResize(editor);
                    Iif (stopObserving) {
                        editor.on("remove", stopObserving);
                    }
                });
                editor.on("SetContent", () => {
                    applyReadOnlyEditorColors(
                        editor,
                        latestColorsRef.current.textColor,
                        latestColorsRef.current.surfaceBg
                    );
                    revealAndResizeEditor(editor);
                });
            },
        }),
        [textColor, surfaceBg, contentPadding, lineHeight, fontSize, minHeight, bottomMargin]
    );
 
    Iif (!content) return null;
 
    const normalizedContent = typeof content === "string" ? content : String(content);
 
    return (
        <Box
            className="read-only-tinymce"
            sx={{
                pointerEvents: "none",
                width: "100%",
                color: "text.primary",
                bgcolor: surfaceBg,
                "& .tox-tinymce": {
                    border: "none !important",
                    backgroundColor: `${surfaceBg} !important`,
                    boxShadow: "none !important",
                    // Belt-and-suspenders for revealAndResizeEditor above — TinyMCE's own
                    // reveal-after-init can get stuck leaving this hidden (see setup()).
                    visibility: "visible !important",
                },
                "& .tox-editor-container": {
                    backgroundColor: `${surfaceBg} !important`,
                },
                "& .tox-edit-area": {
                    backgroundColor: `${surfaceBg} !important`,
                },
                "& .tox-edit-area__iframe": {
                    backgroundColor: `${surfaceBg} !important`,
                },
                "& iframe": {
                    backgroundColor: `${surfaceBg} !important`,
                },
                ...sxProp,
            }}
        >
            <Editor
                key={theme.palette.mode}
                value={normalizedContent}
                onEditorChange={() => {}}
                onInit={handleInit}
                init={editorInit}
            />
        </Box>
    );
};
 
export default TinyMCETextEditorReadOnly;