feat: upgrade toolbox for v1.2.1
This commit is contained in:
+123
-192
@@ -5,25 +5,107 @@
|
||||
const CALC_FIELDS = {
|
||||
derivative: ["order"],
|
||||
integral: ["bounds"],
|
||||
limit: ["point"],
|
||||
limit: ["point", "direction"],
|
||||
series: ["point", "order"],
|
||||
solve_system: ["variables"],
|
||||
gradient: ["variables"],
|
||||
hessian: ["variables"],
|
||||
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(", "),
|
||||
};
|
||||
const CALC_OPERATION_META = {
|
||||
statistics: {
|
||||
placeholder: "12, 15, 18, 21, 24",
|
||||
hint: "使用逗号分隔数据,返回四分位数、方差、标准差、极差等统计量。",
|
||||
},
|
||||
base: {
|
||||
placeholder: "FF",
|
||||
hint: "输入不带前缀的整数,原进制与目标进制均支持 2 到 36。",
|
||||
},
|
||||
solve: {
|
||||
placeholder: "x^2 - 5*x + 6 = 0",
|
||||
hint: "可省略等号右侧;通过“变量”指定要求解的未知量。",
|
||||
},
|
||||
solve_system: {
|
||||
placeholder: "x + y = 5; x - y = 1",
|
||||
hint: "使用分号分隔方程,通过“变量列表”指定未知量,最多 4 个变量、6 个方程。",
|
||||
},
|
||||
polynomial_roots: {
|
||||
placeholder: "x^5 - x + 1 = 0",
|
||||
hint: "返回至多 12 次单变量多项式的全部高精度数值根,包括复根。",
|
||||
},
|
||||
series: {
|
||||
placeholder: "exp(x) * cos(x)",
|
||||
hint: "在指定点附近展开;“阶数 6”表示保留到 5 阶并显示余项。",
|
||||
order: 6,
|
||||
},
|
||||
gradient: {
|
||||
placeholder: "x^2*y + sin(y)",
|
||||
hint: "变量列表示例:x,y。结果按该顺序组成梯度列向量。",
|
||||
},
|
||||
hessian: {
|
||||
placeholder: "x^2 + x*y + y^2",
|
||||
hint: "变量列表示例:x,y。结果为二阶偏导组成的 Hessian 矩阵。",
|
||||
},
|
||||
matrix_det: { placeholder: "1,2;3,4", hint: "逗号分列、分号分行,最多 36 个元素。" },
|
||||
matrix_inverse: { placeholder: "1,2;3,4", hint: "逆矩阵要求方阵且行列式非零。" },
|
||||
matrix_rref: { placeholder: "1,2,3;2,4,6", hint: "返回矩阵的行最简形。" },
|
||||
matrix_transpose: { placeholder: "1,2,3;4,5,6", hint: "交换矩阵的行与列。" },
|
||||
matrix_rank: { placeholder: "1,2,3;2,4,6", hint: "通过精确行变换计算矩阵秩。" },
|
||||
matrix_nullspace: { placeholder: "1,2;2,4", hint: "返回齐次方程组对应零空间的一组基。" },
|
||||
matrix_eigenvalues: { placeholder: "2,1;1,2", hint: "要求方阵,返回特征值及其代数重数。" },
|
||||
};
|
||||
|
||||
function calculatorCategoryFor(operation) {
|
||||
const option = [...$tool("#calc-operation").options].find(
|
||||
(item) => item.value === operation,
|
||||
);
|
||||
return option?.parentElement?.dataset.calcCategoryOptions || "algebra";
|
||||
}
|
||||
|
||||
function setCalculatorCategory(category, selectFirst = true) {
|
||||
const select = $tool("#calc-operation");
|
||||
$$tool("[data-calc-category-options]").forEach((group) => {
|
||||
const active = group.dataset.calcCategoryOptions === category;
|
||||
group.hidden = !active;
|
||||
group.disabled = !active;
|
||||
});
|
||||
$$tool("[data-calc-category]").forEach((button) => {
|
||||
button.classList.toggle(
|
||||
"active",
|
||||
button.dataset.calcCategory === category,
|
||||
);
|
||||
});
|
||||
if (selectFirst) {
|
||||
const group = $tool(
|
||||
`[data-calc-category-options="${category}"]`,
|
||||
);
|
||||
if (group?.querySelector("option")) {
|
||||
select.value = group.querySelector("option").value;
|
||||
}
|
||||
}
|
||||
if (result && typeof result === "object" && "exact" in result) return result;
|
||||
const entries = Object.entries(result || {});
|
||||
updateCalculatorFields();
|
||||
}
|
||||
|
||||
function resultText(value, field = "exact") {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => resultText(item, field)).join("; ");
|
||||
}
|
||||
if (value && typeof value === "object") {
|
||||
if ("exact" in value) return value[field] || value.exact;
|
||||
return Object.entries(value)
|
||||
.map(([key, item]) => `${key}: ${resultText(item, field)}`)
|
||||
.join("; ");
|
||||
}
|
||||
return String(value ?? "");
|
||||
}
|
||||
|
||||
function formatCalculatorResult(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(", "),
|
||||
exact: resultText(result, "exact"),
|
||||
decimal: resultText(result, "decimal"),
|
||||
latex: resultText(result, "latex"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -33,17 +115,13 @@
|
||||
$$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";
|
||||
const meta = CALC_OPERATION_META[operation] || {};
|
||||
$tool("#calc-input").placeholder = meta.placeholder || "例如:sqrt(2) + 1/3";
|
||||
$tool("#calc-hint").textContent =
|
||||
meta.hint || "支持精确常量、受限数学函数和变量;按 Command/Ctrl + Enter 运行。";
|
||||
$tool("#calc-order").max = operation === "derivative" ? 5 : 12;
|
||||
if (meta.order) $tool("#calc-order").value = meta.order;
|
||||
else if (operation === "derivative") $tool("#calc-order").value = 1;
|
||||
}
|
||||
|
||||
async function runCalculator() {
|
||||
@@ -59,10 +137,12 @@
|
||||
operation,
|
||||
expression,
|
||||
variable: $tool("#calc-variable").value,
|
||||
variables: $tool("#calc-variables").value,
|
||||
order: $tool("#calc-order").value,
|
||||
lower: $tool("#calc-lower").value,
|
||||
upper: $tool("#calc-upper").value,
|
||||
point: $tool("#calc-point").value,
|
||||
direction: $tool("#calc-direction").value,
|
||||
from_base: $tool("#calc-from-base").value,
|
||||
to_base: $tool("#calc-to-base").value,
|
||||
from_unit: $tool("#calc-from-unit").value,
|
||||
@@ -92,163 +172,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -930,7 +853,17 @@
|
||||
}
|
||||
|
||||
function init() {
|
||||
$tool("#calc-operation").addEventListener("change", updateCalculatorFields);
|
||||
$tool("#calc-operation").addEventListener("change", () => {
|
||||
setCalculatorCategory(
|
||||
calculatorCategoryFor($tool("#calc-operation").value),
|
||||
false,
|
||||
);
|
||||
});
|
||||
$$tool("[data-calc-category]").forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
setCalculatorCategory(button.dataset.calcCategory);
|
||||
});
|
||||
});
|
||||
$tool("#calc-run").addEventListener("click", runCalculator);
|
||||
$tool("#calc-input").addEventListener("keydown", (event) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key === "Enter") runCalculator();
|
||||
@@ -939,24 +872,22 @@
|
||||
button.addEventListener("click", () => {
|
||||
$tool("#calc-operation").value = button.dataset.calcOperation;
|
||||
$tool("#calc-input").value = button.dataset.calcExample;
|
||||
updateCalculatorFields();
|
||||
setCalculatorCategory(
|
||||
calculatorCategoryFor(button.dataset.calcOperation),
|
||||
false,
|
||||
);
|
||||
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();
|
||||
setCalculatorCategory("algebra", false);
|
||||
window.HuluGraph?.init();
|
||||
}
|
||||
|
||||
function activate(tool) {
|
||||
if (tool === "graph") window.setTimeout(drawGraph, 30);
|
||||
if (tool === "graph") window.setTimeout(() => window.HuluGraph?.resize(), 30);
|
||||
if (tool === "whiteboard") window.setTimeout(() => geometry.draw(), 30);
|
||||
}
|
||||
|
||||
window.HuluToolbox = { init, activate, runCalculator, drawGraph };
|
||||
window.HuluToolbox = { init, activate, runCalculator };
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user