Files
Youtube_Math/www/scripts/problem.js
2026-05-04 15:32:19 -04:00

95 lines
2.8 KiB
JavaScript

// Copyright John Salguero All rights Reserved
function showProblem() {
const problemEl = document.getElementById("problem");
const mainEl = document.getElementById("equation-main");
const nextEl = document.getElementById("equation-next");
const expEl = document.getElementById("explanation");
const formatted = formatMath(problemData.problem);
// Set the top problem (static)
problemEl.innerHTML = `\\(${formatted}\\)`;
// Initialize the main equation (this is what evolves)
mainEl.innerHTML = `\\(${formatted}\\)`;
// Clear animation layer + explanation
nextEl.innerHTML = "";
nextEl.style.opacity = 0;
expEl.innerHTML = "";
expEl.style.opacity = 0;
MathJax.typesetPromise([problemEl, mainEl]);
}
function showStep() {
if (stepIndex >= problemData.steps.length) {
setTimeout(requestNextProblem, 3000);
return;
}
const mainEl = document.getElementById("equation-main");
const nextEl = document.getElementById("equation-next");
const expEl = document.getElementById("explanation");
const step = problemData.steps[stepIndex];
// 1. Show explanation
expEl.innerHTML = step.step;
expEl.style.opacity = 1;
// 2. Prepare next equation
nextEl.innerHTML = `\\(${formatMath(step.after)}\\)`;
nextEl.classList.remove("fade-in", "move-up");
nextEl.style.opacity = 0;
MathJax.typesetPromise([nextEl]);
setTimeout(() => {
// 3. Fade in next equation (below)
nextEl.style.opacity = 1;
nextEl.classList.add("move-up");
// 4. Fade out old + explanation
mainEl.classList.add("fade-out");
expEl.style.opacity = 0;
setTimeout(() => {
// 5. Promote next → main
mainEl.innerHTML = nextEl.innerHTML;
MathJax.typesetPromise([mainEl]);
// reset styles
mainEl.classList.remove("fade-out");
nextEl.style.opacity = 0;
stepIndex++;
setTimeout(showStep, 1500);
}, 500);
}, 1000); // time to read explanation
}
function startSteps() {
stepIndex = 0;
showStep();
}
function formatMath(str) {
return str
.replace(/\*\*/g, "^") // Exponent Fix
.replace(/(\d+)\s*\*\s*x/g, "$1x") // 4*x -> 4x
.replace(/x\s*\*\s*(\d+)/g, "$1x") // x*4 -> 4x
.replace(/\b1x\b/g, "x") // 1x -> x
.replace(/(\d+)\s*\*\s*\(/g, "$1(") // 4*( -> 4(
.replace(/\)\s*\*\s*\(/g, ")(") // )*( -> )(
.replace(/x\s*\*\s*\(/g, "x(") // x*( -> x(
// FRACTIONS (order matters!)
.replace(/\(([^()]+)\)\s*\/\s*\(([^()]+)\)/g, "\\frac{$1}{$2}")
.replace(/\(([^()]+)\)\s*\/\s*([a-zA-Z0-9]+)/g, "\\frac{$1}{$2}")
.replace(/([a-zA-Z0-9]+)\s*\/\s*\(([^()]+)\)/g, "\\frac{$1}{$2}")
.replace(/([a-zA-Z0-9]+)\s*\/\s*([a-zA-Z0-9]+)/g, "\\frac{$1}{$2}");
}