Files
Hulumath-Web/backend/static/js/toolbox.js
T
Jacky 6cd155ef05
CI / test (pull_request) Canceled after 13s
feat: expand toolbox and add math games
2026-08-09 01:52:35 +08:00

711 lines
24 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(function () {
const $tool = (selector, root = document) => root.querySelector(selector);
const $$tool = (selector, root = document) => [...root.querySelectorAll(selector)];
const CALC_FIELDS = {
derivative: ["order"],
integral: ["bounds"],
limit: ["point"],
base: ["base"],
unit: ["unit"],
};
function formatCalculatorResult(result) {
if (Array.isArray(result)) {
return {
exact: result.map((item) => item.exact).join(", "),
decimal: result.map((item) => item.decimal).join(", "),
latex: result.map((item) => item.latex).join(", "),
};
}
if (result && typeof result === "object" && "exact" in result) return result;
const entries = Object.entries(result || {});
return {
exact: entries.map(([key, value]) => `${key}: ${value}`).join(" · "),
decimal: entries.map(([key, value]) => `${key}: ${value}`).join(" · "),
latex: entries.map(([key, value]) => `${key}=${value}`).join(", "),
};
}
function updateCalculatorFields() {
const operation = $tool("#calc-operation").value;
const visible = new Set(CALC_FIELDS[operation] || []);
$$tool("[data-calc-field]").forEach((field) => {
field.hidden = !visible.has(field.dataset.calcField);
});
const input = $tool("#calc-input");
const placeholders = {
statistics: "12, 15, 18, 21, 24",
base: "FF",
matrix_det: "1,2;3,4",
matrix_inverse: "1,2;3,4",
matrix_rref: "1,2,3;2,4,6",
matrix_transpose: "1,2,3;4,5,6",
solve: "x^2 - 5*x + 6 = 0",
};
input.placeholder = placeholders[operation] || "例如:sqrt(2) + 1/3";
}
async function runCalculator() {
const button = $tool("#calc-run");
const operation = $tool("#calc-operation").value;
const expression = $tool("#calc-input").value.trim();
button.disabled = true;
$tool("#calc-history").textContent = "数学内核正在计算…";
try {
const payload = await api("toolbox/calculate/", {
method: "POST",
body: {
operation,
expression,
variable: $tool("#calc-variable").value,
order: $tool("#calc-order").value,
lower: $tool("#calc-lower").value,
upper: $tool("#calc-upper").value,
point: $tool("#calc-point").value,
from_base: $tool("#calc-from-base").value,
to_base: $tool("#calc-to-base").value,
from_unit: $tool("#calc-from-unit").value,
to_unit: $tool("#calc-to-unit").value,
},
});
const result = formatCalculatorResult(payload.result);
$tool("#calc-history").textContent = `${operation} · ${expression}`;
$tool("#calc-output").textContent = result.exact || "完成";
$tool("#calc-decimal").textContent = result.decimal || result.exact || "—";
$tool("#calc-latex").textContent = result.latex || result.exact || "—";
$tool("#calc-steps").replaceChildren(
...(payload.steps || []).map((step) => {
const item = document.createElement("li");
item.textContent = step;
return item;
})
);
} catch (error) {
$tool("#calc-history").textContent = error.message;
$tool("#calc-output").textContent = "计算失败";
$tool("#calc-decimal").textContent = "—";
$tool("#calc-latex").textContent = "—";
$tool("#calc-steps").replaceChildren();
} finally {
button.disabled = false;
}
}
const GRAPH_COLORS = ["#196548", "#d86f45", "#5d73e8", "#8667b5"];
function drawFunctionPath(context, expression, variables, range, width, height, color) {
const toY = (value) => height / 2 - (value / range) * (height / 2);
context.strokeStyle = color;
context.lineWidth = 3;
context.beginPath();
let drawing = false;
const samples = [];
for (let pixel = 0; pixel <= width; pixel += 2) {
const x = (pixel / width) * range * 2 - range;
let y;
try {
y = evaluateExpression(expression, { ...variables, x });
} catch (error) {
if (pixel === 0) throw error;
drawing = false;
continue;
}
samples.push({ x, y });
const screenY = toY(y);
if (!Number.isFinite(screenY) || screenY < -height * 2 || screenY > height * 3) {
drawing = false;
continue;
}
if (!drawing) context.moveTo(pixel, screenY);
else context.lineTo(pixel, screenY);
drawing = true;
}
context.stroke();
return samples;
}
function graphAnalysis(samples) {
const roots = [];
let extrema = 0;
for (let index = 1; index < samples.length; index += 1) {
const before = samples[index - 1];
const current = samples[index];
if (before.y === 0 || before.y * current.y < 0) {
const root = (before.x + current.x) / 2;
if (!roots.length || Math.abs(root - roots.at(-1)) > 0.15) roots.push(root);
}
if (index > 1) {
const previousSlope = before.y - samples[index - 2].y;
const currentSlope = current.y - before.y;
if (previousSlope * currentSlope < 0) extrema += 1;
}
}
return { roots: roots.slice(0, 8), extrema };
}
function drawGraph() {
const canvas = $tool("#graph-canvas");
const context = canvas.getContext("2d");
const expressions = $tool("#graph-expression").value
.split("\n")
.map((item) => item.trim())
.filter(Boolean)
.slice(0, 4);
const range = Number($tool("#graph-range").value);
const parameter = Number($tool("#graph-parameter").value);
const width = canvas.width;
const height = canvas.height;
$tool("#graph-range-label").textContent = `${range}${range}`;
$tool("#graph-parameter-label").textContent = `a = ${parameter}`;
$tool("#graph-error").textContent = "";
context.clearRect(0, 0, width, height);
context.fillStyle = "#fbfbf7";
context.fillRect(0, 0, width, height);
const toX = (x) => ((x + range) / (range * 2)) * width;
const toY = (y) => height / 2 - (y / range) * (height / 2);
context.strokeStyle = "#e4e5df";
context.lineWidth = 1;
for (let value = -range; value <= range; value += 1) {
context.beginPath();
context.moveTo(toX(value), 0);
context.lineTo(toX(value), height);
context.moveTo(0, toY(value));
context.lineTo(width, toY(value));
context.stroke();
}
context.strokeStyle = "#718078";
context.lineWidth = 2;
context.beginPath();
context.moveTo(0, height / 2);
context.lineTo(width, height / 2);
context.moveTo(width / 2, 0);
context.lineTo(width / 2, height);
context.stroke();
if (!expressions.length) {
$tool("#graph-error").textContent = "请至少输入一个函数";
return;
}
try {
const firstSamples = drawFunctionPath(
context,
expressions[0],
{ a: parameter },
range,
width,
height,
GRAPH_COLORS[0],
);
expressions.slice(1).forEach((expression, index) => {
drawFunctionPath(
context,
expression,
{ a: parameter },
range,
width,
height,
GRAPH_COLORS[index + 1],
);
});
if ($tool("#graph-integral").checked) {
context.fillStyle = "rgba(25, 101, 72, .13)";
context.beginPath();
context.moveTo(0, height / 2);
firstSamples.forEach((item) => context.lineTo(toX(item.x), toY(item.y)));
context.lineTo(width, height / 2);
context.closePath();
context.fill();
}
if ($tool("#graph-derivative").checked) {
const derivative = firstSamples.slice(1, -1).map((item, index) => {
const before = firstSamples[index];
const after = firstSamples[index + 2];
return { x: item.x, y: (after.y - before.y) / (after.x - before.x) };
});
context.strokeStyle = "#111827";
context.lineWidth = 2;
context.setLineDash([9, 7]);
context.beginPath();
derivative.forEach((item, index) => {
const x = toX(item.x);
const y = toY(item.y);
if (index === 0) context.moveTo(x, y);
else context.lineTo(x, y);
});
context.stroke();
context.setLineDash([]);
}
const analysis = graphAnalysis(firstSamples);
const rootText = analysis.roots.length
? analysis.roots.map((item) => item.toFixed(2)).join("、")
: "当前范围未发现";
$tool("#graph-analysis").textContent =
`第一条曲线:近似零点 ${rootText};检测到 ${analysis.extrema} 个极值转折。`;
} catch (error) {
$tool("#graph-error").textContent = error.message;
}
}
function canvasPoint(canvas, event) {
const rect = canvas.getBoundingClientRect();
return {
x: ((event.clientX - rect.left) / rect.width) * canvas.width,
y: ((event.clientY - rect.top) / rect.height) * canvas.height,
};
}
function downloadCanvas(canvas, name) {
const link = document.createElement("a");
link.download = `${name}-${new Date().toISOString().slice(0, 10)}.png`;
link.href = canvas.toDataURL("image/png");
link.click();
}
class Whiteboard {
constructor(canvas) {
this.canvas = canvas;
this.context = canvas.getContext("2d");
this.tool = "pen";
this.history = [];
this.drawing = false;
this.start = null;
this.preview = null;
this.reset();
canvas.addEventListener("pointerdown", (event) => this.startDrawing(event));
canvas.addEventListener("pointermove", (event) => this.move(event));
canvas.addEventListener("pointerup", (event) => this.finish(event));
canvas.addEventListener("pointercancel", () => this.cancel());
}
reset() {
this.context.fillStyle = "#ffffff";
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
}
snapshot() {
this.history.push(this.canvas.toDataURL("image/png"));
if (this.history.length > 20) this.history.shift();
}
startDrawing(event) {
event.preventDefault();
this.snapshot();
this.drawing = true;
this.start = canvasPoint(this.canvas, event);
if (this.tool === "text") {
const text = $tool("#whiteboard-text").value.trim();
if (!text) {
this.history.pop();
showToast("先输入要放到白板的文字或公式");
} else {
const size = Math.max(18, Number($tool("#whiteboard-size").value) * 5);
this.context.fillStyle = $tool("#whiteboard-color").value;
this.context.font = `${size}px "SFMono-Regular", "PingFang SC", sans-serif`;
this.context.fillText(text, this.start.x, this.start.y);
}
this.drawing = false;
return;
}
this.preview = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
this.canvas.setPointerCapture(event.pointerId);
this.context.lineCap = "round";
this.context.lineJoin = "round";
this.context.lineWidth = Number($tool("#whiteboard-size").value);
this.context.strokeStyle =
this.tool === "eraser" ? "#ffffff" : $tool("#whiteboard-color").value;
if (this.tool === "pen" || this.tool === "eraser") {
this.context.beginPath();
this.context.moveTo(this.start.x, this.start.y);
}
}
move(event) {
if (!this.drawing) return;
event.preventDefault();
const point = canvasPoint(this.canvas, event);
if (this.tool === "pen" || this.tool === "eraser") {
this.context.lineTo(point.x, point.y);
this.context.stroke();
return;
}
this.context.putImageData(this.preview, 0, 0);
this.context.beginPath();
if (this.tool === "line") {
this.context.moveTo(this.start.x, this.start.y);
this.context.lineTo(point.x, point.y);
} else {
this.context.rect(
this.start.x,
this.start.y,
point.x - this.start.x,
point.y - this.start.y,
);
}
this.context.stroke();
}
finish(event) {
if (!this.drawing) return;
this.move(event);
this.drawing = false;
this.preview = null;
}
cancel() {
if (this.preview) this.context.putImageData(this.preview, 0, 0);
this.drawing = false;
}
undo() {
const source = this.history.pop();
if (!source) return;
const image = new Image();
image.onload = () => {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.drawImage(image, 0, 0);
};
image.src = source;
}
clear() {
this.snapshot();
this.reset();
}
addGrid() {
this.snapshot();
const context = this.context;
context.strokeStyle = "#e1e7e1";
context.lineWidth = 1;
for (let x = 0; x <= this.canvas.width; x += 50) {
context.beginPath();
context.moveTo(x, 0);
context.lineTo(x, this.canvas.height);
context.stroke();
}
for (let y = 0; y <= this.canvas.height; y += 50) {
context.beginPath();
context.moveTo(0, y);
context.lineTo(this.canvas.width, y);
context.stroke();
}
context.strokeStyle = "#7a877f";
context.lineWidth = 2;
context.beginPath();
context.moveTo(this.canvas.width / 2, 0);
context.lineTo(this.canvas.width / 2, this.canvas.height);
context.moveTo(0, this.canvas.height / 2);
context.lineTo(this.canvas.width, this.canvas.height / 2);
context.stroke();
}
addImage(file) {
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
const image = new Image();
image.onload = () => {
this.snapshot();
const scale = Math.min(
1,
(this.canvas.width * 0.8) / image.width,
(this.canvas.height * 0.8) / image.height,
);
this.context.drawImage(
image,
30,
30,
image.width * scale,
image.height * scale,
);
};
image.src = reader.result;
};
reader.readAsDataURL(file);
}
}
class GeometryBoard {
constructor(canvas) {
this.canvas = canvas;
this.context = canvas.getContext("2d");
this.tool = "point";
this.points = [];
this.segments = [];
this.circles = [];
this.history = [];
this.pending = [];
this.dragging = null;
canvas.addEventListener("pointerdown", (event) => this.pointerDown(event));
canvas.addEventListener("pointermove", (event) => this.pointerMove(event));
canvas.addEventListener("pointerup", (event) => this.pointerUp(event));
canvas.addEventListener("pointercancel", () => {
this.dragging = null;
});
this.draw();
}
save() {
this.history.push(
JSON.stringify({
points: this.points,
segments: this.segments,
circles: this.circles,
})
);
if (this.history.length > 30) this.history.shift();
}
findOrCreate(point) {
const nearest = this.findNearest(point);
if (nearest >= 0) return nearest;
this.points.push(point);
return this.points.length - 1;
}
findNearest(point) {
let nearest = -1;
let distance = 28;
this.points.forEach((item, index) => {
const current = Math.hypot(item.x - point.x, item.y - point.y);
if (current < distance) {
nearest = index;
distance = current;
}
});
return nearest;
}
pointerDown(event) {
if (this.tool !== "move") return;
event.preventDefault();
const nearest = this.findNearest(canvasPoint(this.canvas, event));
if (nearest < 0 || this.points[nearest].derived) return;
this.save();
this.dragging = nearest;
this.canvas.setPointerCapture(event.pointerId);
}
pointerMove(event) {
if (this.dragging === null) return;
event.preventDefault();
const point = canvasPoint(this.canvas, event);
this.points[this.dragging] = point;
this.draw();
}
pointerUp(event) {
if (this.tool === "move") {
this.pointerMove(event);
this.dragging = null;
return;
}
this.handlePoint(event);
}
handlePoint(event) {
event.preventDefault();
const point = canvasPoint(this.canvas, event);
this.save();
if (this.tool === "point") {
this.findOrCreate(point);
} else {
this.pending.push(this.findOrCreate(point));
if (this.pending.length === 2) {
const [first, second] = this.pending;
if (first !== second && this.tool === "segment") {
this.segments.push({ first, second });
} else if (first !== second && this.tool === "circle") {
this.circles.push({ center: first, edge: second });
} else if (first !== second && this.tool === "midpoint") {
const a = this.points[first];
const b = this.points[second];
this.points.push({
x: (a.x + b.x) / 2,
y: (a.y + b.y) / 2,
derived: true,
parents: [first, second],
});
this.segments.push({ first, second, guide: true });
}
this.pending = [];
}
}
this.draw();
$tool("#geometry-hint").textContent = this.pending.length
? "再选择一个点完成构造。"
: "可继续创建或切换构造工具。";
}
draw() {
const context = this.context;
const width = this.canvas.width;
const height = this.canvas.height;
this.points.forEach((point) => {
if (!point.derived || !point.parents) return;
const first = this.points[point.parents[0]];
const second = this.points[point.parents[1]];
point.x = (first.x + second.x) / 2;
point.y = (first.y + second.y) / 2;
});
context.fillStyle = "#fbfbf7";
context.fillRect(0, 0, width, height);
context.strokeStyle = "#e7e8e2";
context.lineWidth = 1;
for (let x = 0; x <= width; x += 50) {
context.beginPath();
context.moveTo(x, 0);
context.lineTo(x, height);
context.stroke();
}
for (let y = 0; y <= height; y += 50) {
context.beginPath();
context.moveTo(0, y);
context.lineTo(width, y);
context.stroke();
}
this.segments.forEach((segment) => {
const first = this.points[segment.first];
const second = this.points[segment.second];
context.strokeStyle = segment.guide ? "#9ca3af" : "#196548";
context.setLineDash(segment.guide ? [8, 6] : []);
context.lineWidth = 3;
context.beginPath();
context.moveTo(first.x, first.y);
context.lineTo(second.x, second.y);
context.stroke();
context.setLineDash([]);
if ($tool("#geometry-labels").checked) {
context.fillStyle = "#47534c";
context.font = "18px sans-serif";
context.fillText(
Math.hypot(first.x - second.x, first.y - second.y).toFixed(1),
(first.x + second.x) / 2 + 8,
(first.y + second.y) / 2 - 8,
);
}
});
this.circles.forEach((circle) => {
const center = this.points[circle.center];
const edge = this.points[circle.edge];
const radius = Math.hypot(center.x - edge.x, center.y - edge.y);
context.strokeStyle = "#5d73e8";
context.lineWidth = 3;
context.beginPath();
context.arc(center.x, center.y, radius, 0, Math.PI * 2);
context.stroke();
});
this.points.forEach((point, index) => {
context.fillStyle = point.derived ? "#d86f45" : "#17211b";
context.beginPath();
context.arc(point.x, point.y, 7, 0, Math.PI * 2);
context.fill();
if ($tool("#geometry-labels").checked) {
context.fillStyle = "#17211b";
context.font = "18px sans-serif";
context.fillText(
`${String.fromCharCode(65 + (index % 26))} (${Math.round(point.x)}, ${Math.round(point.y)})`,
point.x + 10,
point.y - 10,
);
}
});
}
undo() {
const state = this.history.pop();
if (!state) return;
const parsed = JSON.parse(state);
this.points = parsed.points;
this.segments = parsed.segments;
this.circles = parsed.circles;
this.pending = [];
this.draw();
}
clear() {
this.save();
this.points = [];
this.segments = [];
this.circles = [];
this.pending = [];
this.draw();
}
}
let whiteboard;
let geometry;
function initDrawingTools() {
whiteboard = new Whiteboard($tool("#whiteboard-canvas"));
geometry = new GeometryBoard($tool("#geometry-canvas"));
$$tool("[data-whiteboard-tool]").forEach((button) => {
button.addEventListener("click", () => {
whiteboard.tool = button.dataset.whiteboardTool;
$$tool("[data-whiteboard-tool]").forEach((item) =>
item.classList.toggle("active", item === button)
);
});
});
$tool("#whiteboard-undo").addEventListener("click", () => whiteboard.undo());
$tool("#whiteboard-clear").addEventListener("click", () => whiteboard.clear());
$tool("#whiteboard-grid").addEventListener("click", () => whiteboard.addGrid());
$tool("#whiteboard-image").addEventListener("change", (event) => {
whiteboard.addImage(event.target.files[0]);
event.target.value = "";
});
$tool("#whiteboard-export").addEventListener("click", () =>
downloadCanvas(whiteboard.canvas, "hulumath-whiteboard")
);
$$tool("[data-geometry-tool]").forEach((button) => {
button.addEventListener("click", () => {
geometry.tool = button.dataset.geometryTool;
geometry.pending = [];
$$tool("[data-geometry-tool]").forEach((item) =>
item.classList.toggle("active", item === button)
);
});
});
$tool("#geometry-labels").addEventListener("change", () => geometry.draw());
$tool("#geometry-undo").addEventListener("click", () => geometry.undo());
$tool("#geometry-clear").addEventListener("click", () => geometry.clear());
$tool("#geometry-export").addEventListener("click", () =>
downloadCanvas(geometry.canvas, "hulumath-geometry")
);
}
function init() {
$tool("#calc-operation").addEventListener("change", updateCalculatorFields);
$tool("#calc-run").addEventListener("click", runCalculator);
$tool("#calc-input").addEventListener("keydown", (event) => {
if ((event.metaKey || event.ctrlKey) && event.key === "Enter") runCalculator();
});
$$tool("[data-calc-example]").forEach((button) => {
button.addEventListener("click", () => {
$tool("#calc-operation").value = button.dataset.calcOperation;
$tool("#calc-input").value = button.dataset.calcExample;
updateCalculatorFields();
runCalculator();
});
});
["#graph-run", "#graph-range", "#graph-parameter", "#graph-derivative", "#graph-integral"]
.forEach((selector) => $tool(selector).addEventListener("input", drawGraph));
$tool("#graph-expression").addEventListener("keydown", (event) => {
if ((event.metaKey || event.ctrlKey) && event.key === "Enter") drawGraph();
});
initDrawingTools();
updateCalculatorFields();
drawGraph();
}
function activate(tool) {
if (tool === "graph") window.setTimeout(drawGraph, 30);
if (tool === "geometry") window.setTimeout(() => geometry.draw(), 30);
}
window.HuluToolbox = { init, activate, runCalculator, drawGraph };
})();