All files / src/lib/graph2d/calculus calculusExport.js

95.91% Statements 47/49
86.2% Branches 25/29
100% Functions 10/10
95.74% Lines 45/47

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                3x             11x                 68x         7x 7x 7x     3x                               17x 16x 16x   15x 1x 1x   16x                 8x 8x 1x 1x   7x 7x 7x 7x 7x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x           7x 2x 2x   7x                 8x 3x           5x 2x   3x 2x   1x 1x    
/**
 * EI-3152 — Calculus Visualization: export helpers (SVG / PNG) + format gating.
 *
 * function-plot renders a d3 <svg>. Export = serialize the SVG (lossless) or
 * rasterize it to a PNG data URL via a canvas. `canExport(format)` gates the
 * Export button: it is false until a KNOWN format is selected (EI-TC-2654).
 */
 
export const EXPORT_FORMATS = Object.freeze([
    { value: "svg", label: "SVG" },
    { value: "png", label: "PNG" },
]);
 
/** The selectable export formats (for the format <Select>). */
export function getAvailableExportFormats() {
    return EXPORT_FORMATS;
}
 
/**
 * Whether an export is allowed for the currently-selected format.
 * Returns false for empty / null / unknown formats → the Export button stays
 * disabled until the user picks SVG or PNG. (Drives EI-TC-2654.)
 */
export function canExport(format) {
    return EXPORT_FORMATS.some((f) => f.value === format);
}
 
/** A stable download filename, e.g. "calculus-derivative.svg". */
export function buildExportFilename(mode, format) {
    const safeMode = mode === "integral" || mode === "derivative" ? mode : "graph";
    const safeExt = canExport(format) ? format : "svg";
    return `calculus-${safeMode}.${safeExt}`;
}
 
const SVG_NS = "http://www.w3.org/2000/svg";
 
/**
 * Serialize an <svg> element to a standalone SVG string.
 *
 * Modified by Allan Ninal — every exported SVG was malformed. `getAttribute("xmlns")`
 * is null for a NAMESPACED element (a namespace is not an attribute), and d3 /
 * function-plot produce exactly that, so the old guard always added a literal xmlns
 * on top of the one XMLSerializer emits itself:
 *
 *     <svg xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"/>
 *
 * A duplicate attribute is invalid XML, so the downloaded file is rejected outright
 * by strict parsers — which is most things that open an .svg other than a browser.
 */
export function serializeSvg(svgEl) {
    if (!svgEl) return "";
    const clone = svgEl.cloneNode(true);
    if (clone.namespaceURI === SVG_NS) {
        // The serializer writes xmlns for us; anything literal here is a duplicate.
        clone.removeAttribute("xmlns");
    } else Eif (!clone.getAttribute("xmlns")) {
        clone.setAttribute("xmlns", SVG_NS);
    }
    return new XMLSerializer().serializeToString(clone);
}
 
/**
 * Rasterize an <svg> element to a PNG data URL via a canvas.
 * Returns a Promise<string> (the data: URL). Rejects if the format is not PNG
 * or the SVG can't be loaded.
 */
export function svgToPngDataUrl(svgEl, width, height) {
    return new Promise((resolve, reject) => {
        if (!svgEl) {
            reject(new Error("No SVG to export"));
            return;
        }
        const svgString = serializeSvg(svgEl);
        const blob = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" });
        const url = URL.createObjectURL(blob);
        const img = new Image();
        img.onload = () => {
            try {
                const canvas = document.createElement("canvas");
                canvas.width = width || svgEl.clientWidth || 600;
                canvas.height = height || svgEl.clientHeight || 400;
                const ctx = canvas.getContext("2d");
                ctx.fillStyle = "#ffffff";
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                URL.revokeObjectURL(url);
                resolve(canvas.toDataURL("image/png"));
            } catch (e) {
                URL.revokeObjectURL(url);
                reject(e);
            }
        };
        img.onerror = (e) => {
            URL.revokeObjectURL(url);
            reject(e instanceof Error ? e : new Error("Failed to rasterize SVG"));
        };
        img.src = url;
    });
}
 
/**
 * Produce the export payload for the chosen format. Throws if no valid format is
 * selected (mirrors the disabled Export button — EI-TC-2654 defense in depth).
 */
export async function exportCalculusGraph(svgEl, format, { width, height } = {}) {
    if (!canExport(format)) {
        throw new Error("Select an export format first.");
    }
    // Modified by Allan Ninal — the two formats disagreed about a missing graph. The
    // PNG path rejected with this same message, while the SVG path serialised nothing
    // into "" and SUCCEEDED, handing the teacher a zero-byte .svg download. An empty
    // file looks like something they did wrong; a refusal does not.
    if (!svgEl) {
        throw new Error("No SVG to export");
    }
    if (format === "svg") {
        return { format, data: serializeSvg(svgEl), mime: "image/svg+xml" };
    }
    const dataUrl = await svgToPngDataUrl(svgEl, width, height);
    return { format, data: dataUrl, mime: "image/png" };
}