All files / src/lib/graph2d/calculus CalculusPanel.jsx

68.88% Statements 31/45
80% Branches 20/25
58.33% Functions 7/12
70.73% Lines 29/41

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                                                9x 9x 9x 9x 9x 9x 9x 9x   9x   9x 7x 1x 1x           9x 7x 7x 7x 1x 1x   6x   6x     7x 7x           9x   9x                                             9x                 1x                                 1x                                                                                                                                                 18x                                    
import { useEffect, useMemo, useRef, useState } from "react";
import functionPlot from "function-plot";
import { Box, TextField, Button, MenuItem, ToggleButton, ToggleButtonGroup, Typography, Alert, Stack } from "@mui/material";
 
import {
    CALCULUS_MODES,
    DEFAULT_VIEWPORT,
    validateCalculusInput,
    buildDerivativeConfig,
    buildIntegralConfig,
    definiteIntegral,
} from "./functionPlotConfig";
import { getAvailableExportFormats, canExport, exportCalculusGraph, buildExportFilename } from "./calculusExport";
 
/**
 * EI-3152 — Calculus Visualization tool.
 *
 * Teacher enters f(x) and either a point x₀ (derivative → curve + tangent line)
 * or bounds [a, b] (integral → curve + shaded area). A live function-plot preview
 * renders on every valid change. Export is disabled until a format (SVG/PNG) is
 * chosen (EI-TC-2654). `onInsert` receives the export payload + the calculus spec
 * so the graph editor can embed it into the question.
 */
export default function CalculusPanel({ onInsert } = {}) {
    const [mode, setMode] = useState(CALCULUS_MODES.DERIVATIVE);
    const [fn, setFn] = useState("x^2");
    const [x0, setX0] = useState("1");
    const [a, setA] = useState("0");
    const [b, setB] = useState("2");
    const [format, setFormat] = useState(""); // empty → Export disabled (EI-TC-2654)
    const [renderError, setRenderError] = useState(null);
    const plotRef = useRef(null);
 
    const validation = useMemo(() => validateCalculusInput({ mode, fn, x0, a, b }), [mode, fn, x0, a, b]);
 
    const integralValue = useMemo(() => {
        if (mode !== CALCULUS_MODES.INTEGRAL || !validation.valid) return null;
        try {
            return definiteIntegral(fn, a, b);
        } catch {
            return null;
        }
    }, [mode, fn, a, b, validation.valid]);
 
    useEffect(() => {
        const target = plotRef.current;
        Iif (!target) return;
        if (!validation.valid) {
            target.innerHTML = "";
            return;
        }
        try {
            const cfg =
                mode === CALCULUS_MODES.DERIVATIVE
                    ? buildDerivativeConfig({ fn, x0 })
                    : buildIntegralConfig({ fn, a, b });
            functionPlot({ ...cfg, target, width: 560, height: 360 });
            setRenderError(null);
        } catch {
            setRenderError("Could not render this function — check the expression.");
        }
    }, [mode, fn, x0, a, b, validation.valid]);
 
    const exportable = canExport(format) && validation.valid;
 
    const handleExport = async () => {
        if (!exportable) return;
        const svg = plotRef.current?.querySelector("svg");
        try {
            const result = await exportCalculusGraph(svg, format, { width: 560, height: 360 });
            onInsert?.({
                ...result,
                filename: buildExportFilename(mode, format),
                spec: {
                    type: "calculus",
                    mode,
                    fn,
                    point: { x0: Number(x0) },
                    bounds: { a: Number(a), b: Number(b) },
                    viewport: DEFAULT_VIEWPORT,
                    version: "1.0",
                },
            });
        } catch {
            setRenderError("Export failed — try again.");
        }
    };
 
    return (
        <Box id="calculus-panel" sx={{ p: 2 }}>
            <Typography variant="h6" sx={{ mb: 1 }}>
                Calculus Visualization
            </Typography>
 
            <ToggleButtonGroup
                exclusive
                value={mode}
                onChange={(_e, v) => v && setMode(v)}
                size="small"
                sx={{ mb: 2 }}
            >
                <ToggleButton id="calculus-mode-derivative" value={CALCULUS_MODES.DERIVATIVE}>
                    Derivative
                </ToggleButton>
                <ToggleButton id="calculus-mode-integral" value={CALCULUS_MODES.INTEGRAL}>
                    Integral
                </ToggleButton>
            </ToggleButtonGroup>
 
            <Stack direction="row" spacing={2} sx={{ mb: 2 }} flexWrap="wrap">
                <TextField
                    id="calculus-fn-input"
                    label="f(x)"
                    value={fn}
                    onChange={(e) => setFn(e.target.value)}
                    inputProps={{ name: "fn" }}
                    size="small"
                />
                {mode === CALCULUS_MODES.DERIVATIVE ? (
                    <TextField
                        id="calculus-x0-input"
                        label="Point x₀"
                        value={x0}
                        onChange={(e) => setX0(e.target.value)}
                        inputProps={{ name: "x0" }}
                        size="small"
                    />
                ) : (
                    <>
                        <TextField
                            id="calculus-a-input"
                            label="Lower bound a"
                            value={a}
                            onChange={(e) => setA(e.target.value)}
                            inputProps={{ name: "a" }}
                            size="small"
                        />
                        <TextField
                            id="calculus-b-input"
                            label="Upper bound b"
                            value={b}
                            onChange={(e) => setB(e.target.value)}
                            inputProps={{ name: "b" }}
                            size="small"
                        />
                    </>
                )}
            </Stack>
 
            {!validation.valid && (
                <Alert id="calculus-validation-error" severity="warning" sx={{ mb: 2 }}>
                    {validation.error}
                </Alert>
            )}
            {renderError && (
                <Alert id="calculus-render-error" severity="error" sx={{ mb: 2 }}>
                    {renderError}
                </Alert>
            )}
 
            {integralValue != null && (
                <Typography id="calculus-integral-value" variant="body2" sx={{ mb: 1 }}>
                    ∫ from {a} to {b} of {fn} dx ≈ {integralValue.toFixed(4)}
                </Typography>
            )}
 
            <Box
                id="calculus-plot"
                ref={plotRef}
                sx={{ border: "1px solid #e0e0e0", borderRadius: 1, minHeight: 360, mb: 2, bgcolor: "#fff" }}
            />
 
            <Stack direction="row" spacing={2} alignItems="center">
                <TextField
                    id="calculus-format-select"
                    select
                    label="Export format"
                    value={format}
                    onChange={(e) => setFormat(e.target.value)}
                    size="small"
                    sx={{ minWidth: 160 }}
                    inputProps={{ name: "format" }}
                >
                    <MenuItem value="">
                        <em>Select a format…</em>
                    </MenuItem>
                    {getAvailableExportFormats().map((f) => (
                        <MenuItem key={f.value} value={f.value} id={`calculus-format-${f.value}`}>
                            {f.label}
                        </MenuItem>
                    ))}
                </TextField>
 
                <Button
                    id="calculus-export-btn"
                    variant="contained"
                    disabled={!exportable}
                    onClick={handleExport}
                >
                    Export
                </Button>
            </Stack>
        </Box>
    );
}