diff --git a/.github/workflows/practice-verification.yml b/.github/workflows/practice-verification.yml index ae2449d8..758d16d8 100644 --- a/.github/workflows/practice-verification.yml +++ b/.github/workflows/practice-verification.yml @@ -79,6 +79,8 @@ jobs: run: npm run check - name: Check imports run: npm run lint:imports + - name: Check escaped LaTeX strings + run: npm run lint:escaped-latex - name: Check formatting run: npm run format:check - name: Check verification documentation diff --git a/package.json b/package.json index 47d8b740..7811c815 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "lint:imports": "biome check --only=organizeImports .", + "lint:escaped-latex": "node scripts/lint-escaped-latex.mjs", "lint:verification-docs": "node scripts/lint-verification-docs.mjs", "format:imports": "biome check --write --only=organizeImports .", "format": "prettier --write .", @@ -79,9 +80,10 @@ } }, "lint-staged": { - "*.{js,ts,svelte}": [ + "*.{js,mjs,cjs,mts,cts,jsx,ts,tsx,svelte}": [ "biome check --write --no-errors-on-unmatched", - "prettier --write" + "prettier --write", + "node scripts/lint-escaped-latex.mjs" ], "*.{json,json5,jsonc,css,md,yaml,yml,html,svg}": [ "prettier --write" diff --git a/scripts/lint-escaped-latex.mjs b/scripts/lint-escaped-latex.mjs new file mode 100644 index 00000000..2704ea55 --- /dev/null +++ b/scripts/lint-escaped-latex.mjs @@ -0,0 +1,632 @@ +#!/usr/bin/env node +import { readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import process from "node:process"; +import { pathToFileURL } from "node:url"; +import { parse as parseSvelte } from "svelte/compiler"; +import * as ts from "typescript"; + +/** + * @typedef {object} EscapedLatexViolation + * @property {number} line Source line containing the escaped LaTeX command. + * @property {string} command LaTeX command that uses JavaScript escaping. + * @property {number} offset Source offset of the command. + */ + +/** + * @typedef {object} FileViolation + * @property {string} file Path relative to the project root. + * @property {number} line Source line containing the escaped LaTeX command. + * @property {string} command LaTeX command that uses JavaScript escaping. + */ + +const DEFAULT_TARGETS = ["src", "tests", "scripts"]; +const SUPPORTED_EXTENSIONS = new Set([ + ".cjs", + ".cts", + ".js", + ".jsx", + ".mjs", + ".mts", + ".svelte", + ".ts", + ".tsx", +]); +const LATEX_COMMANDS = new Set([ + "alpha", + "angle", + "approx", + "arg", + "begin", + "beta", + "mathbf", + "cdot", + "circ", + "cos", + "deg", + "delta", + "Delta", + "dfrac", + "displaystyle", + "dots", + "end", + "equiv", + "epsilon", + "eta", + "exp", + "F", + "frac", + "Gamma", + "gamma", + "ge", + "iff", + "implies", + "in", + "infty", + "int", + "j", + "le", + "left", + "leftrightarrow", + "lim", + "ln", + "log", + "Lambda", + "lambda", + "longleftrightarrow", + "Longrightarrow", + "mathbb", + "mathcal", + "mathrm", + "max", + "min", + "mp", + "mu", + "ne", + "neq", + "omega", + "Omega", + "operatorname", + "phi", + "pi", + "pm", + "pmod", + "Phi", + "Psi", + "qquad", + "quad", + "Re", + "right", + "rm", + "sigma", + "Sigma", + "sin", + "sqrt", + "square", + "prod", + "sum", + "tan", + "tau", + "text", + "textasciicircum", + "texttt", + "tfrac", + "Theta", + "theta", + "tilde", + "times", + "to", + "X", +]); +const ESCAPED_CONTROL_SEQUENCE = /(?:\\\\)+([A-Za-z]+)/g; + +/** + * Finds escaped LaTeX commands in JavaScript, TypeScript, or Svelte source. + * + * @param {string} source Source contents to inspect. + * @param {string} filePath File path used to select the parser. + * @returns {EscapedLatexViolation[]} Escaped LaTeX commands found in the source. + */ +export function findEscapedLatexViolations(source, filePath) { + /** @type {EscapedLatexViolation[]} */ + const violations = []; + + if (path.extname(filePath) === ".svelte") { + scanSvelteSource(source, filePath, violations); + } else { + scanTypeScriptSource(source, filePath, violations); + } + + return violations; +} + +/** + * Scans JavaScript or TypeScript AST string and template nodes. + * + * @param {string} source Source contents to inspect. + * @param {string} filePath File path supplied to the TypeScript parser. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @returns {void} + */ +function scanTypeScriptSource(source, filePath, violations) { + const extension = path.extname(filePath); + const scriptKind = + extension === ".tsx" + ? ts.ScriptKind.TSX + : extension === ".jsx" + ? ts.ScriptKind.JSX + : extension === ".js" || + extension === ".mjs" || + extension === ".cjs" + ? ts.ScriptKind.JS + : ts.ScriptKind.TS; + const sourceFile = ts.createSourceFile( + filePath, + source, + ts.ScriptTarget.Latest, + true, + scriptKind, + ); + + /** + * Recursively visits a node in the parsed TypeScript source. + * + * @param {ts.Node} node AST node to inspect. + * @returns {void} + */ + function visit(node) { + visitTypeScriptNode(node, sourceFile, source, violations, visit); + } + + visit(sourceFile); +} + +/** + * Visits a TypeScript AST node and checks its string-bearing children. + * + * @param {ts.Node} node AST node to inspect. + * @param {ts.SourceFile} sourceFile Parsed source file. + * @param {string} source Full file contents. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @param {(node: ts.Node) => void} visit Recursive visitor callback. + * @returns {void} + */ +function visitTypeScriptNode(node, sourceFile, source, violations, visit) { + if (ts.isStringLiteral(node)) { + scanRawText( + node.getText(sourceFile), + node.getStart(sourceFile), + source, + violations, + ); + return; + } + + if (ts.isRegularExpressionLiteral(node)) return; + + if (ts.isNoSubstitutionTemplateLiteral(node)) { + scanRawText( + node.getText(sourceFile), + node.getStart(sourceFile), + source, + violations, + ); + return; + } + + if (ts.isTemplateExpression(node)) { + scanTypeScriptTemplateExpression( + node, + sourceFile, + source, + violations, + visit, + ); + return; + } + + if ( + ts.isTaggedTemplateExpression(node) && + isTypeScriptStringRawTag(node.tag) + ) { + visitTypeScriptRawTemplate(node.template, visit); + return; + } + + ts.forEachChild(node, visit); +} + +/** + * Scans an untagged TypeScript template and visits its interpolations. + * + * @param {ts.TemplateExpression} node Template expression AST node. + * @param {ts.SourceFile} sourceFile Parsed source file. + * @param {string} source Full file contents. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @param {(node: ts.Node) => void} visit Recursive visitor callback. + * @returns {void} + */ +function scanTypeScriptTemplateExpression( + node, + sourceFile, + source, + violations, + visit, +) { + scanRawText( + node.head.getText(sourceFile), + node.head.getStart(sourceFile), + source, + violations, + ); + for (const span of node.templateSpans) { + scanRawText( + span.literal.getText(sourceFile), + span.literal.getStart(sourceFile), + source, + violations, + ); + visit(span.expression); + } +} + +/** + * Visits interpolations without scanning the raw template portions. + * + * @param {ts.TemplateLiteral} template Tagged template AST node. + * @param {(node: ts.Node) => void} visit Recursive visitor callback. + * @returns {void} + */ +function visitTypeScriptRawTemplate(template, visit) { + if (!ts.isTemplateExpression(template)) return; + for (const span of template.templateSpans) visit(span.expression); +} + +/** + * Scans Svelte script and markup-expression AST nodes. + * + * @param {string} source Svelte component contents. + * @param {string} filePath File path supplied to the Svelte parser. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @returns {void} + */ +function scanSvelteSource(source, filePath, violations) { + const root = parseSvelte(source, { filename: filePath, modern: true }); + /** @type {WeakSet} */ + const visited = new WeakSet(); + + visitSvelteAst( + root.instance?.content ?? null, + null, + source, + violations, + visited, + ); + visitSvelteAst( + root.module?.content ?? null, + null, + source, + violations, + visited, + ); + visitSvelteAst(root.fragment, null, source, violations, visited); +} + +/** + * Visits Svelte and embedded JavaScript AST nodes without scanning comments or CSS. + * + * @param {unknown} value AST value to inspect. + * @param {Record | null} parent Parent AST node when available. + * @param {string} source Full file contents. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @param {WeakSet} visited Previously visited AST objects. + * @returns {void} + */ +function visitSvelteAst(value, parent, source, violations, visited) { + if (!value || typeof value !== "object" || visited.has(value)) return; + visited.add(value); + + if (Array.isArray(value)) { + for (const child of value) { + visitSvelteAst(child, parent, source, violations, visited); + } + return; + } + + const node = /** @type {Record} */ (value); + + if (node.type === "Literal") { + if (typeof node.raw === "string" && !node.regex) { + scanRawText(node.raw, node.start, source, violations); + } + return; + } + + if (node.type === "TemplateLiteral") { + scanSvelteTemplateLiteral(node, parent, source, violations, visited); + return; + } + + if (node.type === "TaggedTemplateExpression") { + visitSvelteTaggedTemplate(node, source, violations, visited); + return; + } + + for (const [key, child] of Object.entries(node)) { + if (key !== "loc" && key !== "parent") { + visitSvelteAst(child, node, source, violations, visited); + } + } +} + +/** + * Scans a Svelte template literal unless it is tagged with String.raw. + * + * @param {Record} node Template literal AST node. + * @param {Record | null} parent Parent AST node when available. + * @param {string} source Full file contents. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @param {WeakSet} visited Previously visited AST objects. + * @returns {void} + */ +function scanSvelteTemplateLiteral(node, parent, source, violations, visited) { + const isRaw = + parent?.type === "TaggedTemplateExpression" && + isSvelteStringRawTag(parent.tag); + + if (!isRaw) { + for (const quasi of node.quasis ?? []) { + scanRawText( + quasi.value?.raw ?? "", + quasi.start ?? node.start, + source, + violations, + ); + } + } + + for (const expression of node.expressions ?? []) { + visitSvelteAst(expression, node, source, violations, visited); + } +} + +/** + * Visits a Svelte tagged template while honoring String.raw template content. + * + * @param {Record} node Tagged template AST node. + * @param {string} source Full file contents. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @param {WeakSet} visited Previously visited AST objects. + * @returns {void} + */ +function visitSvelteTaggedTemplate(node, source, violations, visited) { + visitSvelteAst(node.tag, node, source, violations, visited); + if (isSvelteStringRawTag(node.tag)) { + for (const expression of node.quasi?.expressions ?? []) { + visitSvelteAst(expression, node.quasi, source, violations, visited); + } + } else { + visitSvelteAst(node.quasi, node, source, violations, visited); + } +} + +/** + * Adds matches from one raw source fragment to the diagnostics collection. + * + * @param {string} rawText Source fragment including its original escapes. + * @param {number} baseOffset Source offset where the fragment begins. + * @param {string} source Full file contents for line calculation. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @returns {void} + */ +function scanRawText(rawText, baseOffset, source, violations) { + ESCAPED_CONTROL_SEQUENCE.lastIndex = 0; + let match; + + while (true) { + match = ESCAPED_CONTROL_SEQUENCE.exec(rawText); + if (match === null) break; + + const command = match[1]; + if (command === undefined || !LATEX_COMMANDS.has(command)) continue; + + const offset = baseOffset + match.index; + violations.push({ + line: lineAt(source, offset), + command: String.fromCharCode(92) + command, + offset, + }); + } +} + +/** + * Calculates a one-based line number for a source offset. + * + * @param {string} source Full file contents. + * @param {number} offset Source offset. + * @returns {number} One-based line number. + */ +function lineAt(source, offset) { + let line = 1; + for (let index = 0; index < offset; index += 1) { + if (source[index] === "\n") line += 1; + } + return line; +} + +/** + * Checks whether a TypeScript tag expression is String.raw. + * + * @param {ts.Expression} tag Tag expression. + * @returns {boolean} Whether the tag is String.raw. + */ +function isTypeScriptStringRawTag(tag) { + return ( + ts.isPropertyAccessExpression(tag) && + tag.name.text === "raw" && + ts.isIdentifier(tag.expression) && + tag.expression.text === "String" + ); +} + +/** + * Checks whether a Svelte ESTree tag expression is String.raw. + * + * @param {Record | null | undefined} tag Tag expression. + * @returns {boolean} Whether the tag is String.raw. + */ +function isSvelteStringRawTag(tag) { + return ( + tag?.type === "MemberExpression" && + tag.computed === false && + tag.object?.type === "Identifier" && + tag.object.name === "String" && + tag.property?.type === "Identifier" && + tag.property.name === "raw" + ); +} + +/** + * Collects supported source files from supplied paths or the default project trees. + * + * @param {string[]} targets File or directory paths, possibly empty. + * @param {string} projectRoot Absolute project root. + * @returns {Promise} Sorted absolute source paths. + */ +export async function collectSourceFiles(targets, projectRoot = process.cwd()) { + const files = new Set(); + const paths = targets.length > 0 ? targets : DEFAULT_TARGETS; + + /** + * Sorts directory entries by name for stable file discovery. + * + * @param {import("node:fs").Dirent} left First directory entry. + * @param {import("node:fs").Dirent} right Second directory entry. + * @returns {number} Locale comparison result. + */ + function compareDirectoryEntries(left, right) { + return left.name.localeCompare(right.name); + } + + /** + * Adds source files beneath a file or directory path. + * + * @param {string} targetPath Absolute or project-relative path. + * @returns {Promise} + */ + async function collect(targetPath) { + const absolutePath = path.resolve(projectRoot, targetPath); + let details; + + try { + details = await stat(absolutePath); + } catch (error) { + if ( + error instanceof Error && + "code" in error && + error.code === "ENOENT" + ) { + return; + } + throw error; + } + + if (details.isDirectory()) { + const entries = await readdir(absolutePath, { + withFileTypes: true, + }); + entries.sort(compareDirectoryEntries); + for (const entry of entries) { + if (entry.isDirectory()) { + await collect(path.join(absolutePath, entry.name)); + } else if ( + entry.isFile() && + SUPPORTED_EXTENSIONS.has(path.extname(entry.name)) + ) { + files.add(path.join(absolutePath, entry.name)); + } + } + return; + } + + if ( + details.isFile() && + SUPPORTED_EXTENSIONS.has(path.extname(absolutePath)) + ) { + files.add(absolutePath); + } + } + + for (const targetPath of paths) await collect(targetPath); + return [...files].sort(); +} + +/** + * Lints file paths and returns paths and violations relative to the project root. + * + * @param {string[]} targets File or directory paths, possibly empty. + * @param {string} projectRoot Absolute project root. + * @returns {Promise<{files: string[], violations: FileViolation[]}>} Scan results. + */ +export async function lintPaths(targets, projectRoot = process.cwd()) { + const files = await collectSourceFiles(targets, projectRoot); + /** @type {FileViolation[]} */ + const violations = []; + const relativeFiles = []; + + for (const filePath of files) { + const source = await readFile(filePath, "utf8"); + const relativeFile = path + .relative(projectRoot, filePath) + .split(path.sep) + .join("/"); + relativeFiles.push(relativeFile); + + for (const violation of findEscapedLatexViolations(source, filePath)) { + violations.push({ + file: relativeFile, + line: violation.line, + command: violation.command, + }); + } + } + + return { files: relativeFiles, violations }; +} + +/** + * Runs the command-line check and prints actionable diagnostics. + * + * @param {string[]} targets File paths supplied on the command line. + * @returns {Promise} Process exit code. + */ +export async function main(targets = process.argv.slice(2)) { + try { + const { files, violations } = await lintPaths(targets); + for (const violation of violations) { + console.error( + violation.file + + ":" + + violation.line + + ": " + + violation.command + + " is escaped in a JavaScript string; use String.raw for LaTeX.", + ); + } + if (violations.length > 0) return 1; + + console.log( + "Escaped LaTeX check passed (" + files.length + " source files).", + ); + return 0; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error("Escaped LaTeX check failed: " + message); + return 2; + } +} + +const invokedPath = process.argv[1] + ? pathToFileURL(path.resolve(process.argv[1])).href + : null; +if (import.meta.url === invokedPath) process.exitCode = await main(); diff --git a/src/lib/components/canvas/CtftSpectrum.svelte b/src/lib/components/canvas/CtftSpectrum.svelte index 5593d004..9fd07afc 100644 --- a/src/lib/components/canvas/CtftSpectrum.svelte +++ b/src/lib/components/canvas/CtftSpectrum.svelte @@ -115,7 +115,7 @@ >{impulse.location} Harmonic Spectrum Magnitude - + 💡 Notice the Gibbs phenomenon overshoot near jump discontinuities as - . At a jump, the series - converges to the midpoint of the left and right limits. Overshoot - persists near the jump while its width shrinks. + . At a jump, the + series converges to the midpoint of the left and right limits. + Overshoot persists near the jump while its width shrinks. {:else}
`$N_{${percent}\\%}=${powerThresholds[key]}$`).join("; ")}. Here $N$ is the highest included harmonic; zero-valued harmonics add no power.`} + text={String.raw`Minimum highest-harmonic limits: ${FOURIER_POWER_TARGETS.map(({ key, percent }) => String.raw`$N_{${percent}\%}=${powerThresholds[key]}$`).join("; ")}. Here $N$ is the highest included harmonic; zero-valued harmonics add no power.`} />
diff --git a/src/lib/components/math/FourierCoefficientCard.svelte b/src/lib/components/math/FourierCoefficientCard.svelte index 2e5ca0df..bd02f4d6 100644 --- a/src/lib/components/math/FourierCoefficientCard.svelte +++ b/src/lib/components/math/FourierCoefficientCard.svelte @@ -55,8 +55,8 @@ direct = $bindable(""), coeffLatex, numPlaceholder = "e.g. 4 or 2", - denPlaceholder = "e.g. n \\pi or n^2 \\pi^2", - directPlaceholder = "e.g. 2 / (n \\pi)", + denPlaceholder = String.raw`e.g. n \pi or n^2 \pi^2`, + directPlaceholder = String.raw`e.g. 2 / (n \pi)`, onUpdate, }: Props = $props(); diff --git a/src/lib/components/math/FourierSeriesInput.svelte b/src/lib/components/math/FourierSeriesInput.svelte index 7d91b494..0666c3b1 100644 --- a/src/lib/components/math/FourierSeriesInput.svelte +++ b/src/lib/components/math/FourierSeriesInput.svelte @@ -51,7 +51,7 @@ let bnDen = $state("n pi"); let bnHarmonic = $state("odd"); let bnCustomHarmonic = $state(""); - let bnDirect = $state("\\frac{2}{n \\pi} (1 - (-1)^n)"); + let bnDirect = $state(String.raw`\frac{2}{n \pi} (1 - (-1)^n)`); // Complex exponential coefficient F_n let FnMode = $state("fraction"); @@ -59,7 +59,7 @@ let FnDen = $state("j n pi"); let FnHarmonic = $state("none"); let FnCustomHarmonic = $state(""); - let FnDirect = $state("\\frac{1}{j n \\pi}"); + let FnDirect = $state(String.raw`\frac{1}{j n \pi}`); /** * Converts simple math symbols and normalizes backslashes in user input into valid LaTeX syntax. @@ -73,10 +73,10 @@ .trim() .replace(/\*/g, " ") .replace(/\\{2,}/g, "\\") - .replace(/\\?\bpi\b/g, "\\pi") - .replace(/\\?\bomega_0\b/g, "\\omega_0") - .replace(/\\?\bomega\b/g, "\\omega") - .replace(/\bw0\b/g, "\\omega_0"); + .replace(/\\?\bpi\b/g, String.raw`\pi`) + .replace(/\\?\bomega_0\b/g, String.raw`\omega_0`) + .replace(/\\?\bomega\b/g, String.raw`\omega`) + .replace(/\bw0\b/g, String.raw`\omega_0`); } /** @@ -107,7 +107,7 @@ if (cleanDen === "1") { fractionPart = cleanNum; } else { - fractionPart = `\\frac{${cleanNum}}{${cleanDen}}`; + fractionPart = String.raw`\frac{${cleanNum}}{${cleanDen}}`; } let multiplierPart = ""; @@ -178,16 +178,16 @@ const cleanA0 = a0.trim(); const cleanAn = anLatex.trim(); const cleanBn = bnLatex.trim(); - const w0 = formatMathLatex(omega0) || "\\omega_0"; + const w0 = formatMathLatex(omega0) || String.raw`\omega_0`; let cosTerm = ""; if (cleanAn && cleanAn !== "0") { - cosTerm = `${cleanAn} \\cos(${w0} n t)`; + cosTerm = String.raw`${cleanAn} \cos(${w0} n t)`; } let sinTerm = ""; if (cleanBn && cleanBn !== "0") { - sinTerm = `${cleanBn} \\sin(${w0} n t)`; + sinTerm = String.raw`${cleanBn} \sin(${w0} n t)`; } let sumContent = ""; @@ -200,7 +200,7 @@ } const sumPart = sumContent - ? `\\sum_{n=1}^{\\infty} \\left[ ${sumContent} \\right]` + ? String.raw`\sum_{n=1}^{\infty} \left[ ${sumContent} \right]` : ""; if (cleanA0 && cleanA0 !== "0") { @@ -217,11 +217,11 @@ function synthesizeExp(): string { const cleanF0 = F0.trim(); const cleanFn = FnLatex.trim(); - const w0 = formatMathLatex(omega0) || "\\omega_0"; + const w0 = formatMathLatex(omega0) || String.raw`\omega_0`; const sumPart = cleanFn && cleanFn !== "0" - ? `\\sum_{n=-\\infty, n \\neq 0}^{\\infty} \\left( ${cleanFn} \\right) e^{j n ${w0} t}` + ? String.raw`\sum_{n=-\infty, n \neq 0}^{\infty} \left( ${cleanFn} \right) e^{j n ${w0} t}` : ""; if (cleanF0 && cleanF0 !== "0") { diff --git a/src/lib/components/math/MathBlock.svelte b/src/lib/components/math/MathBlock.svelte index b3535af6..086fc252 100644 --- a/src/lib/components/math/MathBlock.svelte +++ b/src/lib/components/math/MathBlock.svelte @@ -53,23 +53,23 @@ if (!trimmed) return ""; // If user explicitly requests matrix environment and expression is not already wrapped - if (matrix && !trimmed.startsWith(`\\begin{${matrix}}`)) { - return `\\begin{${matrix}}\n${trimmed}\n\\end{${matrix}}`; + if (matrix && !trimmed.startsWith(String.raw`\begin{${matrix}}`)) { + return String.raw`\begin{${matrix}}${"\n"}${trimmed}${"\n"}\end{${matrix}}`; } // If user explicitly requests cases environment and expression is not already wrapped - if (cases && !trimmed.startsWith("\\begin{cases}")) { - return `\\begin{cases}\n${trimmed}\n\\end{cases}`; + if (cases && !trimmed.startsWith(String.raw`\begin{cases}`)) { + return String.raw`\begin{cases}${"\n"}${trimmed}${"\n"}\end{cases}`; } // If user explicitly requests aligned environment and expression is not already wrapped - if (aligned && !trimmed.startsWith("\\begin{aligned}")) { - return `\\begin{aligned}\n${trimmed}\n\\end{aligned}`; + if (aligned && !trimmed.startsWith(String.raw`\begin{aligned}`)) { + return String.raw`\begin{aligned}${"\n"}${trimmed}${"\n"}\end{aligned}`; } // If user explicitly requests gathered environment and expression is not already wrapped - if (gathered && !trimmed.startsWith("\\begin{gathered}")) { - return `\\begin{gathered}\n${trimmed}\n\\end{gathered}`; + if (gathered && !trimmed.startsWith(String.raw`\begin{gathered}`)) { + return String.raw`\begin{gathered}${"\n"}${trimmed}${"\n"}\end{gathered}`; } return trimmed; diff --git a/src/lib/components/math/MathInline.svelte b/src/lib/components/math/MathInline.svelte index 3fc14478..46fd1d3e 100644 --- a/src/lib/components/math/MathInline.svelte +++ b/src/lib/components/math/MathInline.svelte @@ -72,7 +72,7 @@ ): string { try { const formattedExpr = useDisplayStyle - ? `\\displaystyle ${expr || ""}` + ? String.raw`\displaystyle ${expr || ""}` : expr || ""; return katex.renderToString(formattedExpr, { displayMode: false, diff --git a/src/lib/components/math/MathInputBar.svelte b/src/lib/components/math/MathInputBar.svelte index 8ac02e7f..d1414b4d 100644 --- a/src/lib/components/math/MathInputBar.svelte +++ b/src/lib/components/math/MathInputBar.svelte @@ -46,7 +46,7 @@ r1 = $bindable(""), r2 = $bindable(""), label = "Enter Math Solution:", - placeholder = "e.g. 2 e^{-2t} \\cos(3t) u(t)", + placeholder = String.raw`e.g. 2 e^{-2t} \cos(3t) u(t)`, inputType = "generic", onChange, }: Props = $props(); @@ -61,20 +61,40 @@ /** Common Symbol Shortcuts for freehand mode */ const symbols = [ - { label: "Fraction", math: "\\frac{a}{b}", latex: "\\frac{a}{b}" }, + { + label: "Fraction", + math: String.raw`\frac{a}{b}`, + latex: String.raw`\frac{a}{b}`, + }, { label: "e^x", math: "e^{-t}", latex: "e^{-t}" }, - { label: "cos", math: "\\cos(\\omega t)", latex: "\\cos(\\omega t)" }, - { label: "sin", math: "\\sin(\\omega t)", latex: "\\sin(\\omega t)" }, + { + label: "cos", + math: String.raw`\cos(\omega t)`, + latex: String.raw`\cos(\omega t)`, + }, + { + label: "sin", + math: String.raw`\sin(\omega t)`, + latex: String.raw`\sin(\omega t)`, + }, { label: "u(t)", math: "u(t)", latex: "u(t)" }, - { label: "delta(t)", math: "\\delta(t)", latex: "\\delta(t)" }, - { label: "pi", math: "\\pi", latex: "\\pi" }, - { label: "omega", math: "\\omega", latex: "\\omega" }, + { + label: "delta(t)", + math: String.raw`\delta(t)`, + latex: String.raw`\delta(t)`, + }, + { label: "pi", math: String.raw`\pi`, latex: String.raw`\pi` }, + { label: "omega", math: String.raw`\omega`, latex: String.raw`\omega` }, { label: "angle theta", - math: "\\angle \\theta^\\circ", - latex: "\\angle \\theta^\\circ", + math: String.raw`\angle \theta^\circ`, + latex: String.raw`\angle \theta^\circ`, + }, + { + label: "sqrt(x)", + math: String.raw`\sqrt{x}`, + latex: String.raw`\sqrt{x}`, }, - { label: "sqrt(x)", math: "\\sqrt{x}", latex: "\\sqrt{x}" }, ]; /** diff --git a/src/lib/components/math/OdeResponseInput.svelte b/src/lib/components/math/OdeResponseInput.svelte index 1878f381..5a7a0722 100644 --- a/src/lib/components/math/OdeResponseInput.svelte +++ b/src/lib/components/math/OdeResponseInput.svelte @@ -102,8 +102,16 @@ } case "underdamped": { // e^{\sigma t} (C1 \cos(\omega_d t) + C2 \sin(\omega_d t)) + yp - const cosTerm = formatTerm(c1, `\\cos(${omegaD}t)`, true); - const sinTerm = formatTerm(c2, `\\sin(${omegaD}t)`, !cosTerm); + const cosTerm = formatTerm( + c1, + String.raw`\cos(${omegaD}t)`, + true, + ); + const sinTerm = formatTerm( + c2, + String.raw`\sin(${omegaD}t)`, + !cosTerm, + ); const trigSum = [cosTerm, sinTerm].filter(Boolean).join(" "); let expPrefix = ""; diff --git a/src/lib/components/math/PhasorInput.svelte b/src/lib/components/math/PhasorInput.svelte index 131e4e55..ffcba617 100644 --- a/src/lib/components/math/PhasorInput.svelte +++ b/src/lib/components/math/PhasorInput.svelte @@ -29,16 +29,16 @@ /** Time domain inputs state */ let amp = $state("10"); - let omega = $state("100\\pi"); - let phaseStr = $state("45^\\circ"); + let omega = $state(String.raw`100\pi`); + let phaseStr = $state(String.raw`45^\circ`); /** Rectangular inputs state */ let realPart = $state("7.07"); let imagPart = $state("7.07"); // MathText formula constants for UI labels - const polarMath = "|V| \\angle \\theta^\\circ"; - const timeDomainMath = "A \\cos(\\omega t + \\phi)"; + const polarMath = String.raw`|V| \angle \theta^\circ`; + const timeDomainMath = String.raw`A \cos(\omega t + \phi)`; const rectangularMath = "X + jY"; /** @@ -49,9 +49,9 @@ const m = mag || "1"; const a = angleDeg || "0"; if (polarNotation === "exp_j") { - return `${m} e^{j ${a}^\\circ}`; + return String.raw`${m} e^{j ${a}^\circ}`; } - return `${m} \\angle ${a}^\\circ`; + return String.raw`${m} \angle ${a}^\circ`; } /** @@ -60,11 +60,11 @@ */ function getTimeDomainLatex(): string { const a = amp || "1"; - const w = omega || "\\omega"; + const w = omega || String.raw`\omega`; const p = phaseStr.trim(); const pFormatted = p.startsWith("+") || p.startsWith("-") ? p : `+ ${p}`; - return `${a} \\cos(${w} t ${p ? pFormatted : ""})`; + return String.raw`${a} \cos(${w} t ${p ? pFormatted : ""})`; } /** diff --git a/src/lib/components/math/PiecewiseIntervalInput.svelte b/src/lib/components/math/PiecewiseIntervalInput.svelte index b8d4abef..998f3b5d 100644 --- a/src/lib/components/math/PiecewiseIntervalInput.svelte +++ b/src/lib/components/math/PiecewiseIntervalInput.svelte @@ -78,9 +78,9 @@ case "t_less": return `t < ${row.upperBound || "0"}`; case "between": - return `${row.lowerBound || "0"} \\le t \\le ${row.upperBound || "1"}`; + return String.raw`${row.lowerBound || "0"} \le t \le ${row.upperBound || "1"}`; case "t_greater": - return `t \\ge ${row.lowerBound || "0"}`; + return String.raw`t \ge ${row.lowerBound || "0"}`; default: return "t"; } @@ -96,7 +96,7 @@ const first = intervals[0]; const expr = first.expression.trim() || "0"; const cond = formatCondition(first); - return `${expr} \\quad \\text{for } ${cond}`; + return String.raw`${expr} \quad \text{for } ${cond}`; } const casesStr = intervals @@ -105,9 +105,9 @@ const cond = formatCondition(row); return `${expr}, & ${cond}`; }) - .join(" \\\\ "); + .join(String.raw` \\ `); - return `\\begin{cases} ${casesStr} \\end{cases}`; + return String.raw`\begin{cases} ${casesStr} \end{cases}`; } /** @@ -227,7 +227,7 @@ aria-label="Lower boundary A" /> - + Partial Fractions Form diff --git a/src/lib/components/solvers/OdeFullSolutionView.svelte b/src/lib/components/solvers/OdeFullSolutionView.svelte index b926cfc5..c01b20ba 100644 --- a/src/lib/components/solvers/OdeFullSolutionView.svelte +++ b/src/lib/components/solvers/OdeFullSolutionView.svelte @@ -72,7 +72,7 @@ />

@@ -83,7 +83,7 @@ />

@@ -170,13 +170,13 @@ /> {#if problem.forcing.type === "sinusoid"} {:else} @@ -224,7 +224,7 @@ diff --git a/src/lib/components/solvers/convolution-solver-state/controller.svelte.ts b/src/lib/components/solvers/convolution-solver-state/controller.svelte.ts index b394d0fd..7380401d 100644 --- a/src/lib/components/solvers/convolution-solver-state/controller.svelte.ts +++ b/src/lib/components/solvers/convolution-solver-state/controller.svelte.ts @@ -436,7 +436,7 @@ export class ConvolutionStepSolverState extends BaseStepSolverState { this.checkOptionCardStep( this.step2, option, - "Use one fixed signal in $\\tau$ and one reflected signal in $t-\\tau$.", + String.raw`Use one fixed signal in $\tau$ and one reflected signal in $t-\tau$.`, "Select the convolution definition.", 3, ); diff --git a/src/lib/components/solvers/convolution-steps/ConvolutionIntervalDiagram.svelte b/src/lib/components/solvers/convolution-steps/ConvolutionIntervalDiagram.svelte index 0fe543c4..0da1f280 100644 --- a/src/lib/components/solvers/convolution-steps/ConvolutionIntervalDiagram.svelte +++ b/src/lib/components/solvers/convolution-steps/ConvolutionIntervalDiagram.svelte @@ -85,7 +85,7 @@
- +
- +
diff --git a/src/lib/components/solvers/convolution-steps/ConvolutionStep4Transitions.svelte b/src/lib/components/solvers/convolution-steps/ConvolutionStep4Transitions.svelte index a89bafbf..0b89f6eb 100644 --- a/src/lib/components/solvers/convolution-steps/ConvolutionStep4Transitions.svelte +++ b/src/lib/components/solvers/convolution-steps/ConvolutionStep4Transitions.svelte @@ -55,10 +55,10 @@ const completedTransitions = $derived( problem.itsData.step4.transitionGroups .map(({ time }) => `t=${time}`) - .join(",\\;"), + .join(String.raw`,\;`), ); const completedIntervals = $derived( - problem.itsData.step4.intervalLabels.join(",\\;"), + problem.itsData.step4.intervalLabels.join(String.raw`,\;`), ); /** Names one verified ledger entry by its role in the convolution workflow. */ @@ -115,7 +115,7 @@ {#if fixedPart && movingPart}

{/if} @@ -235,7 +235,7 @@

diff --git a/src/lib/components/solvers/ctft-solver-state/controller.svelte.ts b/src/lib/components/solvers/ctft-solver-state/controller.svelte.ts index caa7d4de..a1d56e45 100644 --- a/src/lib/components/solvers/ctft-solver-state/controller.svelte.ts +++ b/src/lib/components/solvers/ctft-solver-state/controller.svelte.ts @@ -334,7 +334,7 @@ export class CtftStepSolverState extends BaseStepSolverState { const shift = stageId === "base" ? 0 : this.problem.params.t0; return validateCtftConstant( input, - `\\pi e^{-j(${location})(${shift})}`, + String.raw`\pi e^{-j(${location})(${shift})}`, ); } @@ -494,6 +494,6 @@ export class CtftStepSolverState extends BaseStepSolverState { const location = this.stages[stageId]!.parts[task.id.replace("weight", "location")]! .input; - return `\\pi e^{-j(${location})(${stageId === "base" ? 0 : this.problem.params.t0})}`; + return String.raw`\pi e^{-j(${location})(${stageId === "base" ? 0 : this.problem.params.t0})}`; } } diff --git a/src/lib/components/solvers/fourier-series-step-solver.svelte.ts b/src/lib/components/solvers/fourier-series-step-solver.svelte.ts index df2d9878..00c42b5c 100644 --- a/src/lib/components/solvers/fourier-series-step-solver.svelte.ts +++ b/src/lib/components/solvers/fourier-series-step-solver.svelte.ts @@ -250,7 +250,7 @@ export class FourierSeriesStepSolverState extends BaseStepSolverState { if (pTrimmed === "" || fTrimmed === "") { this.setValidation( this.step1, - "Please enter numeric or symbolic values for both the period $T_0$ and fundamental frequency $\\omega_0$.", + String.raw`Please enter numeric or symbolic values for both the period $T_0$ and fundamental frequency $\omega_0$.`, ); return; } @@ -279,7 +279,7 @@ export class FourierSeriesStepSolverState extends BaseStepSolverState { if (!matchesFrequencyAnswer(fTrimmed, this.step1.freqUnit, s1Data)) { this.setIncorrect( this.step1, - "Incorrect Fundamental Frequency: use $\\omega_0 = \\frac{2\\pi}{T_0}$. (e.g. $\\pi$ or $\\pi/2$).", + String.raw`Incorrect Fundamental Frequency: use $\omega_0 = \frac{2\pi}{T_0}$. (e.g. $\pi$ or $\pi/2$).`, ); return; } diff --git a/src/lib/components/solvers/fourier-series-steps/FourierSeriesStep4Form.svelte b/src/lib/components/solvers/fourier-series-steps/FourierSeriesStep4Form.svelte index 3c2d1916..8c0a12ae 100644 --- a/src/lib/components/solvers/fourier-series-steps/FourierSeriesStep4Form.svelte +++ b/src/lib/components/solvers/fourier-series-steps/FourierSeriesStep4Form.svelte @@ -72,7 +72,7 @@ text={"Ideal when symmetries eliminate $a_n$ or $b_n$"} /> @@ -88,7 +88,7 @@
@@ -104,7 +104,7 @@
Amplitude-Phase diff --git a/src/lib/components/solvers/laplace-solver-state/controller.svelte.ts b/src/lib/components/solvers/laplace-solver-state/controller.svelte.ts index a59da1f0..12931d64 100644 --- a/src/lib/components/solvers/laplace-solver-state/controller.svelte.ts +++ b/src/lib/components/solvers/laplace-solver-state/controller.svelte.ts @@ -115,17 +115,20 @@ export class LaplaceStepSolverState extends BaseStepSolverState { try { if (task.kind === "scalar") { if (entryIssue(this.input, task.entry ?? { kind: "exact" })) - return "\\square"; + return String.raw`\square`; parseStrictLatex(this.input); return this.input; } const expression = laplaceExpression(this.input, task.kind, task.lhs).trim() || - "\\square"; - if (expression !== "\\square") parseStrictLatex(expression); + String.raw`\square`; + if (expression !== String.raw`\square`) + parseStrictLatex(expression); return task.lhs ? `${task.lhs}=${expression}` : expression; } catch { - return task.lhs ? `${task.lhs}=\\square` : "\\square"; + return task.lhs + ? String.raw`${task.lhs}=\square` + : String.raw`\square`; } } /** @returns Progress within the active stage. */ @@ -198,7 +201,7 @@ export class LaplaceStepSolverState extends BaseStepSolverState { ) .map( (field) => - `\\quad\\text{Term ${Number(field.id.slice("active-".length)) + 1}: ${this.fieldInputs[field.id] === "1" ? "Active" : "Inactive"}}`, + String.raw`\quad\text{Term ${Number(field.id.slice("active-".length)) + 1}: ${this.fieldInputs[field.id] === "1" ? "Active" : "Inactive"}}`, ) .join("") : ""), diff --git a/src/lib/components/solvers/laplace-steps/LaplaceConstructionInput.svelte b/src/lib/components/solvers/laplace-steps/LaplaceConstructionInput.svelte index 6ac5fd1c..f5357153 100644 --- a/src/lib/components/solvers/laplace-steps/LaplaceConstructionInput.svelte +++ b/src/lib/components/solvers/laplace-steps/LaplaceConstructionInput.svelte @@ -119,7 +119,7 @@ text={solver.task.kind === "roots" ? row.kind === "linear" ? "Root: $a$" - : "Roots: $a\\pm j b$, with $b>0$" + : String.raw`Roots: $a\pm j b$, with $b>0$` : row.kind === "linear" ? "Factor: $(s+b)^m$" : "Factor: $(s^2+bs+c)^m$"} diff --git a/src/lib/components/solvers/ode-solver-state/ode-previews.ts b/src/lib/components/solvers/ode-solver-state/ode-previews.ts index 194c3247..28663466 100644 --- a/src/lib/components/solvers/ode-solver-state/ode-previews.ts +++ b/src/lib/components/solvers/ode-solver-state/ode-previews.ts @@ -90,7 +90,7 @@ export function derivePreviewQuadSetup( ): string { const disc = a1 * a1 - 4 * a2 * a0; const negB = -a1; - return `s = \\frac{-(${a1}) \\pm \\sqrt{(${a1})^2 - 4(${a2})(${a0})}}{2(${a2})} = \\frac{${negB} \\pm \\sqrt{${disc}}}{${2 * a2}}`; + return String.raw`s = \frac{-(${a1}) \pm \sqrt{(${a1})^2 - 4(${a2})(${a0})}}{2(${a2})} = \frac{${negB} \pm \sqrt{${disc}}}{${2 * a2}}`; } /** @@ -104,9 +104,9 @@ export function derivePreviewComplexRoots( sigma: string, omegaD: string, ): string { - const sigStr = sigma.trim() !== "" ? sigma.trim() : "\\sigma"; - const omStr = omegaD.trim() !== "" ? omegaD.trim() : "\\omega_d"; - return `s = ${sigStr} \\pm j${omStr}`; + const sigStr = sigma.trim() !== "" ? sigma.trim() : String.raw`\sigma`; + const omStr = omegaD.trim() !== "" ? omegaD.trim() : String.raw`\omega_d`; + return String.raw`s = ${sigStr} \pm j${omStr}`; } /** diff --git a/src/lib/components/solvers/ode-solver-state/step2-roots-validation.ts b/src/lib/components/solvers/ode-solver-state/step2-roots-validation.ts index 82622d23..3c3caa71 100644 --- a/src/lib/components/solvers/ode-solver-state/step2-roots-validation.ts +++ b/src/lib/components/solvers/ode-solver-state/step2-roots-validation.ts @@ -69,8 +69,8 @@ export function validateStep1CharEq( return { kind: "incorrect", message: isFirstOrder - ? "Incorrect coefficients. Substitute $\\frac{dy}{dt} \\to s$ and $y(t) \\to 1$, setting the homogeneous right-hand side to $0$." - : "Incorrect coefficients. Substitute $\\frac{d^2 y}{dt^2} \\to s^2$, $\\frac{dy}{dt} \\to s$, and $y(t) \\to 1$, setting the homogeneous right-hand side to $0$.", + ? String.raw`Incorrect coefficients. Substitute $\frac{dy}{dt} \to s$ and $y(t) \to 1$, setting the homogeneous right-hand side to $0$.` + : String.raw`Incorrect coefficients. Substitute $\frac{d^2 y}{dt^2} \to s^2$, $\frac{dy}{dt} \to s$, and $y(t) \to 1$, setting the homogeneous right-hand side to $0$.`, }; } @@ -217,8 +217,7 @@ export function validateQuadClassChoice( } return { kind: "misconception", - message: - "Incorrect classification. Calculate the discriminant $\\Delta = b^2 - 4ac$ to confirm whether $\\Delta > 0$, $\\Delta = 0$, or $\\Delta < 0$.", + message: String.raw`Incorrect classification. Calculate the discriminant $\Delta = b^2 - 4ac$ to confirm whether $\Delta > 0$, $\Delta = 0$, or $\Delta < 0$.`, }; } @@ -246,7 +245,7 @@ export function validateDiscriminantInput( if (Number.isNaN(vDisc)) { return { kind: "validation", - message: "Please enter a numeric value for $\\Delta = b^2 - 4ac$.", + message: String.raw`Please enter a numeric value for $\Delta = b^2 - 4ac$.`, }; } @@ -257,7 +256,7 @@ export function validateDiscriminantInput( return { kind: "incorrect", - message: `Incorrect discriminant. $\\Delta = (${problem.params.a1})^2 - 4(${problem.params.a2})(${problem.params.a0}) = ${expDisc}$.`, + message: String.raw`Incorrect discriminant. $\Delta = (${problem.params.a1})^2 - 4(${problem.params.a2})(${problem.params.a0}) = ${expDisc}$.`, }; } @@ -290,8 +289,7 @@ export function validateQuadRoots( if (Number.isNaN(vSig) || Number.isNaN(vOm)) { return { kind: "validation", - message: - "Please enter numeric values for both real part $\\sigma$ and damped frequency $\\omega_d$.", + message: String.raw`Please enter numeric values for both real part $\sigma$ and damped frequency $\omega_d$.`, }; } @@ -308,13 +306,12 @@ export function validateQuadRoots( if (approximatelyEqual(vSig, -expSig) && isOmMatch) { return { kind: "misconception", - message: - "Check the sign of $\\sigma$. In the quadratic formula, $\\sigma = \\frac{-b}{2a}$.", + message: String.raw`Check the sign of $\sigma$. In the quadratic formula, $\sigma = \frac{-b}{2a}$.`, }; } return { kind: "incorrect", - message: `Incorrect roots. $\\sigma = \\frac{-(${problem.params.a1})}{${2 * problem.params.a2}} = ${expSig}$ and $\\omega_d = \\frac{\\sqrt{${Math.abs(s2Data.discriminant)}}}{${2 * Math.abs(problem.params.a2)}} = ${expOm}$.`, + message: String.raw`Incorrect roots. $\sigma = \frac{-(${problem.params.a1})}{${2 * problem.params.a2}} = ${expSig}$ and $\omega_d = \frac{\sqrt{${Math.abs(s2Data.discriminant)}}}{${2 * Math.abs(problem.params.a2)}} = ${expOm}$.`, }; } @@ -353,7 +350,7 @@ export function validateQuadRoots( } return { kind: "incorrect", - message: `Incorrect roots. $s = \\frac{-(${problem.params.a1}) \\pm \\sqrt{${s2Data.discriminant}}}{${2 * problem.params.a2}}$, yielding $r_1 = ${r1}, r_2 = ${r2}$.`, + message: String.raw`Incorrect roots. $s = \frac{-(${problem.params.a1}) \pm \sqrt{${s2Data.discriminant}}}{${2 * problem.params.a2}}$, yielding $r_1 = ${r1}, r_2 = ${r2}$.`, }; } @@ -375,13 +372,12 @@ export function validateQuadRoots( if (approximatelyEqual(v1, -r1) && Math.abs(r1) > 0.01) { return { kind: "misconception", - message: - "Check your sign. For a repeated root with $\\Delta = 0$, $r = \\frac{-b}{2a}$.", + message: String.raw`Check your sign. For a repeated root with $\Delta = 0$, $r = \frac{-b}{2a}$.`, }; } return { kind: "incorrect", - message: `Incorrect repeated root. With $\\Delta = 0$, $r = \\frac{-b}{2a} = \\frac{${-problem.params.a1}}{${2 * problem.params.a2}}$.`, + message: String.raw`Incorrect repeated root. With $\Delta = 0$, $r = \frac{-b}{2a} = \frac{${-problem.params.a1}}{${2 * problem.params.a2}}$.`, }; } diff --git a/src/lib/components/solvers/ode-solver-state/step5-coefficients-validation.ts b/src/lib/components/solvers/ode-solver-state/step5-coefficients-validation.ts index b1b5d3df..e1dbf606 100644 --- a/src/lib/components/solvers/ode-solver-state/step5-coefficients-validation.ts +++ b/src/lib/components/solvers/ode-solver-state/step5-coefficients-validation.ts @@ -46,15 +46,13 @@ export function validateStep5Coefficients( if (approximatelyEqual(vA, expB) && approximatelyEqual(vB, expA)) { return { kind: "misconception", - message: - "Swapped Coefficients: You inverted $A$ and $B$. Remember that $A$ is the coefficient for $\\cos(\\omega t)$ and $B$ is the coefficient for $\\sin(\\omega t)$.", + message: String.raw`Swapped Coefficients: You inverted $A$ and $B$. Remember that $A$ is the coefficient for $\cos(\omega t)$ and $B$ is the coefficient for $\sin(\omega t)$.`, }; } return { kind: "incorrect", - message: - "Incorrect coefficients $A$ and $B$. Solve the $2\\times 2$ system by substitution or Cramer's Rule.", + message: String.raw`Incorrect coefficients $A$ and $B$. Solve the $2\times 2$ system by substitution or Cramer's Rule.`, }; } diff --git a/src/lib/components/solvers/ode-steps/OdeStep6InitialConditions.svelte b/src/lib/components/solvers/ode-steps/OdeStep6InitialConditions.svelte index dc5fd7c3..d1972dae 100644 --- a/src/lib/components/solvers/ode-steps/OdeStep6InitialConditions.svelte +++ b/src/lib/components/solvers/ode-steps/OdeStep6InitialConditions.svelte @@ -39,7 +39,7 @@ const summaryLatex = $derived( problem.params.order === 1 ? `Constant: $C_1 = ${toFractionLatex(problem.itsData.step6.expectedC1)}$` - : `Constants: $C_1 = ${toFractionLatex(problem.itsData.step6.expectedC1)}, \\; C_2 = ${toFractionLatex(problem.itsData.step6.expectedC2 ?? 0)}$`, + : String.raw`Constants: $C_1 = ${toFractionLatex(problem.itsData.step6.expectedC1)}, \; C_2 = ${toFractionLatex(problem.itsData.step6.expectedC2 ?? 0)}$`, ); @@ -114,7 +114,7 @@ {#snippet summarySnippet()}
{/snippet} diff --git a/src/lib/components/solvers/ode-steps/OdeStep7PartAZiZs.svelte b/src/lib/components/solvers/ode-steps/OdeStep7PartAZiZs.svelte index f7a8214c..88f6c3ea 100644 --- a/src/lib/components/solvers/ode-steps/OdeStep7PartAZiZs.svelte +++ b/src/lib/components/solvers/ode-steps/OdeStep7PartAZiZs.svelte @@ -54,7 +54,7 @@

@@ -134,7 +134,7 @@
- + - + `t=${time}`) - .join(",\\;"); + .join(String.raw`,\;`); const setups = problem.itsData.step5.parts .map( (part) => part.setupBySignal?.[flippedSignal].integralLatex ?? "y(t)=0", ) - .join("\\\\[0.4em]"); + .join(String.raw`\\[0.4em]`); const evaluated = problem.intervals .map( ({ labelLatex, exprLatex }) => - `${labelLatex}:&\\quad y(t)=${exprLatex}`, + String.raw`${labelLatex}:&\quad y(t)=${exprLatex}`, ) - .join("\\\\[0.4em]"); + .join(String.raw`\\[0.4em]`); return [ { title: "Record input and output timing", @@ -84,7 +84,7 @@ "Adding the input starts and ends bounds the possible overlap span. Signed contributions can cancel even while overlap continues.", latex: problem.itsData.step1.parts .map(({ resultLatex }) => resultLatex) - .join("\\\\"), + .join(String.raw`\\`), aligned: true, responsive: true, }, @@ -101,7 +101,7 @@ { title: "Apply the selected flip-and-shift path", description: `The learner selected $${flippedSignal}(t)$ as the moving signal; this same path controls every later bound.`, - latex: `${formula}\\\\${transformedSections}`, + latex: String.raw`${formula}\\${transformedSections}`, aligned: true, responsive: true, }, @@ -109,7 +109,7 @@ title: "Find transitions and build intervals", description: "Each transition comes from a fixed breakpoint contacting a reflected moving breakpoint. Sorting them creates the time intervals.", - latex: `\\mathcal T=\\{${transitions}\\}\\\\\\mathcal R=\\{${problem.itsData.step4.intervalLabels.join(",\\;")}\\}`, + latex: String.raw`\mathcal T=\{${transitions}\}\\\mathcal R=\{${problem.itsData.step4.intervalLabels.join(String.raw`,\;`)}\}`, aligned: true, responsive: true, }, diff --git a/src/lib/components/ui/OdePracticeCard.svelte b/src/lib/components/ui/OdePracticeCard.svelte index 29d07948..b069385a 100644 --- a/src/lib/components/ui/OdePracticeCard.svelte +++ b/src/lib/components/ui/OdePracticeCard.svelte @@ -52,13 +52,13 @@ }, { label: "Zero-Input Response", - math: "y_{\\text{ZI}}(t)", + math: String.raw`y_{\text{ZI}}(t)`, color: "#10b981", eval: problem.evalZI, }, { label: "Zero-State Response", - math: "y_{\\text{ZS}}(t)", + math: String.raw`y_{\text{ZS}}(t)`, color: "#f59e0b", eval: problem.evalZS, }, @@ -127,7 +127,7 @@
diff --git a/src/lib/components/ui/formula-drawer/FourierFormulaReference.svelte b/src/lib/components/ui/formula-drawer/FourierFormulaReference.svelte index 1fd0d62b..dd238916 100644 --- a/src/lib/components/ui/formula-drawer/FourierFormulaReference.svelte +++ b/src/lib/components/ui/formula-drawer/FourierFormulaReference.svelte @@ -14,17 +14,17 @@

Fourier Series Representations

Trigonometric Form:

Exponential Form:

Coefficient Relations:

@@ -37,7 +37,7 @@ text={String.raw`Trigonometric Coefficients: Requires factor of $\frac{2}{T_0}$:`} /> @@ -46,7 +46,7 @@ text={String.raw`Exponential Coefficients: Requires factor of $\frac{1}{T_0}$:`} /> @@ -77,7 +77,7 @@

Parseval's Power & Gibbs Phenomenon

@@ -91,7 +91,7 @@

Dirichlet Conditions & Convergence

Weak Dirichlet Condition:

@@ -105,7 +105,7 @@

Discontinuity Midpoint Convergence:

diff --git a/src/lib/math-engine/circuits.ts b/src/lib/math-engine/circuits.ts index 6d1e83e5..39d68b60 100644 --- a/src/lib/math-engine/circuits.ts +++ b/src/lib/math-engine/circuits.ts @@ -420,7 +420,7 @@ export function createCircuitProblem( id: `circuit-${topology}-${Date.now()}`, topology, components: { ...components }, - promptLatex: `\\text{Derive the transfer function } H(s) \\text{ for the } \\text{${name}} \\text{ with } R = ${R}\\Omega${circuitUsesInductor(topology) ? `, L = ${L}\\text{H}` : ""}${circuitUsesCapacitor(topology) ? `, C = ${C}\\text{F}` : ""}.`, + promptLatex: String.raw`\text{Derive the transfer function } H(s) \text{ for the } \text{${name}} \text{ with } R = ${R}\Omega${circuitUsesInductor(topology) ? String.raw`, L = ${L}\text{H}` : ""}${circuitUsesCapacitor(topology) ? String.raw`, C = ${C}\text{F}` : ""}.`, referenceAnswerLatex: tf.hLatex, solutionSteps: [ { @@ -429,11 +429,11 @@ export function createCircuitProblem( }, { title: "Step 2: Apply Voltage Divider / Node Voltage Equations", - latex: `H(s) = \\frac{Z_{out}(s)}{Z_{in}(s)} = ${tf.hLatex}`, + latex: String.raw`H(s) = \frac{Z_{out}(s)}{Z_{in}(s)} = ${tf.hLatex}`, }, { title: "Step 3: Identify Characteristic Parameters", - latex: `\\text{Derived Transfer Function } H(s) = ${tf.hLatex}`, + latex: String.raw`\text{Derived Transfer Function } H(s) = ${tf.hLatex}`, }, ], }; diff --git a/src/lib/math-engine/convolution/configuration.ts b/src/lib/math-engine/convolution/configuration.ts index 7d3aa002..5e923e61 100644 --- a/src/lib/math-engine/convolution/configuration.ts +++ b/src/lib/math-engine/convolution/configuration.ts @@ -288,8 +288,8 @@ export function resolveConvolutionSignal( latex: scaleLatex( amplitude, parameter === 2 - ? `\\Delta\\left(${argument}\\right)` - : `\\Delta\\left(\\frac{2(${argument})}{${parameter}}\\right)`, + ? String.raw`\Delta\left(${argument}\right)` + : String.raw`\Delta\left(\frac{2(${argument})}{${parameter}}\right)`, ), sections: [section(`${key}-1`, start, end)], breakpoints: [start, shift, end], diff --git a/src/lib/math-engine/convolution/configured-solver.ts b/src/lib/math-engine/convolution/configured-solver.ts index 45ec41dc..e1e887ad 100644 --- a/src/lib/math-engine/convolution/configured-solver.ts +++ b/src/lib/math-engine/convolution/configured-solver.ts @@ -41,7 +41,7 @@ function scalarLatex(value: number, absolute = false): string { const numerator = absolute ? Math.abs(rawNumerator) : rawNumerator; return denominator === 1 ? String(numerator) - : `\\frac{${numerator}}{${denominator}}`; + : String.raw`\frac{${numerator}}{${denominator}}`; } function polynomialLatex(polynomial: Polynomial): string { @@ -84,8 +84,8 @@ function uniqueSorted(values: number[]): number[] { function intervalLabel(min: number, max: number): string { if (!Number.isFinite(min)) return `t < ${scalarLatex(max)}`; - if (!Number.isFinite(max)) return `t \\ge ${scalarLatex(min)}`; - return `${scalarLatex(min)} \\le t < ${scalarLatex(max)}`; + if (!Number.isFinite(max)) return String.raw`t \ge ${scalarLatex(min)}`; + return String.raw`${scalarLatex(min)} \le t < ${scalarLatex(max)}`; } function intervalRanges(boundaries: number[]): Array<[number, number]> { @@ -338,7 +338,7 @@ function solveExponentials( const equalRates = Math.abs(x.parameter - h.parameter) < EPSILON; const activeExpression = equalRates ? `${scalarLatex(coefficient)}(${formatShiftedTime(onset)})e^{-${x.parameter}(${formatShiftedTime(onset)})}` - : `\\frac{${scalarLatex(coefficient)}}{${scalarLatex(h.parameter - x.parameter)}}\\left(e^{-${x.parameter}(${formatShiftedTime(onset)})}-e^{-${h.parameter}(${formatShiftedTime(onset)})}\\right)`; + : String.raw`\frac{${scalarLatex(coefficient)}}{${scalarLatex(h.parameter - x.parameter)}}\left(e^{-${x.parameter}(${formatShiftedTime(onset)})}-e^{-${h.parameter}(${formatShiftedTime(onset)})}\right)`; const activeEval = (t: number): number => { if (t < onset) return 0; const elapsed = t - onset; diff --git a/src/lib/math-engine/convolution/engine.ts b/src/lib/math-engine/convolution/engine.ts index 0623acdc..d6362907 100644 --- a/src/lib/math-engine/convolution/engine.ts +++ b/src/lib/math-engine/convolution/engine.ts @@ -221,13 +221,13 @@ export function generateConfiguredConvolutionProblem( title: "Identify the Two Configured Signals", description: "Record each signal's exact support, breakpoints, amplitude, and translation.", - latex: `x(t)=${resolvedSignals.x.latex},\\quad h(t)=${resolvedSignals.h.latex}`, + latex: String.raw`x(t)=${resolvedSignals.x.latex},\quad h(t)=${resolvedSignals.h.latex}`, }, { title: "Build Every Geometric Overlap Region", description: "Add fixed and moving breakpoints, then integrate every connected overlap component.", - latex: "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(t-\\tau)\\,d\\tau", + latex: String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(t-\tau)\,d\tau`, }, { title: "Combine Signed Contributions", @@ -236,9 +236,9 @@ export function generateConfiguredConvolutionProblem( latex: result.intervals .map( (interval) => - `y(t)=${interval.exprLatex}\\quad(${interval.labelLatex})`, + String.raw`y(t)=${interval.exprLatex}\quad(${interval.labelLatex})`, ) - .join(",\\quad "), + .join(String.raw`,\quad `), }, ], intervals: result.intervals, diff --git a/src/lib/math-engine/convolution/its-scaffolding/evaluation-terms.ts b/src/lib/math-engine/convolution/its-scaffolding/evaluation-terms.ts index fc55524a..e7d56a07 100644 --- a/src/lib/math-engine/convolution/its-scaffolding/evaluation-terms.ts +++ b/src/lib/math-engine/convolution/its-scaffolding/evaluation-terms.ts @@ -53,20 +53,20 @@ function polynomialEvaluationTerm( String.raw`\tau`, ); const movingPieceLatex = sanitizeLatexMath( - `${formatConvolutionScalar(b0)}+${formatConvolutionScalar(b1)}(t-\\tau)`, + String.raw`${formatConvolutionScalar(b0)}+${formatConvolutionScalar(b1)}(t-\tau)`, ); const p0 = `(${formatConvolutionScalar(a0)})(${formatConvolutionScalar(b0)}+${formatConvolutionScalar(b1)}t)`; const p1 = `(${formatConvolutionScalar(a1)})(${formatConvolutionScalar(b0)}+${formatConvolutionScalar(b1)}t)-${formatConvolutionScalar(a0 * b1)}`; const p2 = formatConvolutionScalar(-a1 * b1); const integrandLatex = sanitizeLatexMath( - `${p0}+(${p1})\\tau+(${p2})\\tau^2`, + String.raw`${p0}+(${p1})\tau+(${p2})\tau^2`, ); const primitiveLatex = sanitizeLatexMath( - `F(\\tau,t)=(${p0})\\tau+\\frac{(${p1})\\tau^2}{2}+\\frac{(${p2})\\tau^3}{3}`, + String.raw`F(\tau,t)=(${p0})\tau+\frac{(${p1})\tau^2}{2}+\frac{(${p2})\tau^3}{3}`, ); const substitute = (bound: string): string => sanitizeLatexMath( - `(${p0})(${bound})+\\frac{(${p1})(${bound})^2}{2}+\\frac{(${p2})(${bound})^3}{3}`, + String.raw`(${p0})(${bound})+\frac{(${p1})(${bound})^2}{2}+\frac{(${p2})(${bound})^3}{3}`, ); const upperSubstitutionLatex = substitute(upperLatex); const lowerSubstitutionLatex = substitute(lowerLatex); @@ -166,13 +166,13 @@ function exponentialPrimitive( rate: number, ): string { if (Math.abs(rate) < 1e-12) - return `${prefactor}((${timeFactor(coefficients)})\\tau${slope === 0 ? "" : `+(${toFractionLatex(slope / 2)})\\tau^2`})`; + return String.raw`${prefactor}((${timeFactor(coefficients)})\tau${slope === 0 ? "" : String.raw`+(${toFractionLatex(slope / 2)})\tau^2`})`; const q0 = timeFactor([ coefficients[0] / rate - slope / (rate * rate), coefficients[1] / rate, ]); const q1 = slope / rate; - return `${prefactor}e^{${formatConvolutionScalar(rate)}\\tau}((${q0})${q1 === 0 ? "" : `+(${toFractionLatex(q1)})\\tau`})`; + return String.raw`${prefactor}e^{${formatConvolutionScalar(rate)}\tau}((${q0})${q1 === 0 ? "" : String.raw`+(${toFractionLatex(q1)})\tau`})`; } /** @@ -226,9 +226,9 @@ function exponentialEvaluationTerm( const exponential = Math.abs(exponentRate) < 1e-12 ? "" - : `e^{${formatConvolutionScalar(exponentRate)}\\tau}`; + : String.raw`e^{${formatConvolutionScalar(exponentRate)}\tau}`; const integrandLatex = sanitizeLatexMath( - `${prefactor}((${constant})${slope === 0 ? "" : `+(${toFractionLatex(slope)})\\tau`})${exponential}`, + String.raw`${prefactor}((${constant})${slope === 0 ? "" : String.raw`+(${toFractionLatex(slope)})\tau`})${exponential}`, ); const primitiveBody = exponentialPrimitive( prefactor, @@ -236,7 +236,9 @@ function exponentialEvaluationTerm( slope, exponentRate, ); - const primitiveLatex = sanitizeLatexMath(`F(\\tau,t)=${primitiveBody}`); + const primitiveLatex = sanitizeLatexMath( + String.raw`F(\tau,t)=${primitiveBody}`, + ); /** @param bound - Verified limit. @returns Primitive evaluated at that limit. */ const substitute = (bound: string): string => sanitizeLatexMath( diff --git a/src/lib/math-engine/convolution/its-scaffolding/helpers.ts b/src/lib/math-engine/convolution/its-scaffolding/helpers.ts index 727794e6..8a158a05 100644 --- a/src/lib/math-engine/convolution/its-scaffolding/helpers.ts +++ b/src/lib/math-engine/convolution/its-scaffolding/helpers.ts @@ -88,8 +88,8 @@ function buildTransitionGroups( ? `${moving}-${groupId}-contact-1` : undefined, formulationHints: [ - `The fixed breakpoint is $\\tau=${formatConvolutionScalar(fixed)}$.`, - `After reflection and translation, moving breakpoint $${formatConvolutionScalar(movingPoint)}$ appears at $\\tau=${transformedLatex}$.`, + String.raw`The fixed breakpoint is $\tau=${formatConvolutionScalar(fixed)}$.`, + String.raw`After reflection and translation, moving breakpoint $${formatConvolutionScalar(movingPoint)}$ appears at $\tau=${transformedLatex}$.`, `Set the breakpoint positions equal: $${equationLatex}$.`, ], solutionHints: [ @@ -135,7 +135,7 @@ function timingPart( start, end, width, - resultLatex: `${id}_{\\mathrm{${id === "y" ? "overlap,start" : "start"}}}=${formatConvolutionScalar(start)},\\quad ${id}_{\\mathrm{${id === "y" ? "overlap,end" : "end"}}}=${formatConvolutionScalar(end)},\\quad W_{${id}${id === "y" ? ",\\mathrm{overlap}" : ""}}=${formatConvolutionScalar(width)}`, + resultLatex: String.raw`${id}_{\mathrm{${id === "y" ? "overlap,start" : "start"}}}=${formatConvolutionScalar(start)},\quad ${id}_{\mathrm{${id === "y" ? "overlap,end" : "end"}}}=${formatConvolutionScalar(end)},\quad W_{${id}${id === "y" ? String.raw`,\mathrm{overlap}` : ""}}=${formatConvolutionScalar(width)}`, hints: id === "y" ? [ @@ -194,7 +194,7 @@ export function buildConvolutionItsData( const definitionOptions = [ { id: "convolution-integral", - latex: "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(t-\\tau)\\,d\\tau", + latex: String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(t-\tau)\,d\tau`, isCorrect: true, }, { @@ -206,14 +206,13 @@ export function buildConvolutionItsData( }, { id: "correlation-integral", - latex: "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(\\tau-t)\\,d\\tau", + latex: String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(\tau-t)\,d\tau`, isCorrect: false, - feedback: - "The moving argument has the wrong orientation; reflection requires $t-\\tau$.", + feedback: String.raw`The moving argument has the wrong orientation; reflection requires $t-\tau$.`, }, { id: "outside-variable", - latex: "y(t)=x(t)\\int_{-\\infty}^{\\infty}h(t-\\tau)\\,d\\tau", + latex: String.raw`y(t)=x(t)\int_{-\infty}^{\infty}h(t-\tau)\,d\tau`, isCorrect: false, feedback: "Both signals must depend on the integration variable inside the convolution integral.", @@ -245,8 +244,8 @@ export function buildConvolutionItsData( options: shuffledDefinitionOptions, hints: [ "Convolution combines reflection, translation, multiplication, and integration.", - "Use $\\tau$ as the integration variable while $t$ remains a parameter.", - "One signal is fixed in $\\tau$ and the other uses $t-\\tau$.", + String.raw`Use $\tau$ as the integration variable while $t$ remains a parameter.`, + String.raw`One signal is fixed in $\tau$ and the other uses $t-\tau$.`, ], }, step3: { @@ -266,7 +265,7 @@ export function buildConvolutionItsData( }, choiceHints: [ "Both choices produce the same convolution because convolution is commutative.", - "Keep one signal fixed in $\\tau$ and reflect and translate the other.", + String.raw`Keep one signal fixed in $\tau$ and reflect and translate the other.`, "Choose the shape whose reflected edges are easiest for you to track.", ], edgeHints: [ @@ -336,7 +335,7 @@ export function buildConvolutionItsData( intervalBuilderHints: [ "Use the verified transition times from smallest to largest.", "The first interval is left-unbounded and the final interval is right-unbounded.", - `The ordered boundaries are $${intervalBoundaries.map(formatConvolutionScalar).join(",\\;")}$.`, + String.raw`The ordered boundaries are $${intervalBoundaries.map(formatConvolutionScalar).join(String.raw`,\;`)}$.`, ], }, step5: { diff --git a/src/lib/math-engine/convolution/its-scaffolding/intervals.ts b/src/lib/math-engine/convolution/its-scaffolding/intervals.ts index 16c475d3..e9724354 100644 --- a/src/lib/math-engine/convolution/its-scaffolding/intervals.ts +++ b/src/lib/math-engine/convolution/its-scaffolding/intervals.ts @@ -120,7 +120,7 @@ function buildPathSetup( .slice(0, -1) .map( (lower, index) => - `\\int_{${lower}}^{${boundaries[index + 1]}}${fixedName}(\\tau)${movingSignal}(t-\\tau)\\,d\\tau`, + String.raw`\int_{${lower}}^{${boundaries[index + 1]}}${fixedName}(\tau)${movingSignal}(t-\tau)\,d\tau`, ); }); return { @@ -167,10 +167,10 @@ export function buildSetupPart( ]; const lowerCandidates = setup.overlaps .map(({ lowerCandidatesLatex }) => lowerCandidatesLatex.join(",")) - .join(";\\;"); + .join(String.raw`;\;`); const upperCandidates = setup.overlaps .map(({ upperCandidatesLatex }) => upperCandidatesLatex.join(",")) - .join(";\\;"); + .join(String.raw`;\;`); const splitPoints = setup.overlaps.flatMap( ({ splitPointsLatex }) => splitPointsLatex, ); @@ -178,7 +178,7 @@ export function buildSetupPart( `Use the representative interior time $t=${formatConvolutionScalar(representativeTime(interval))}$ for $${interval.labelLatex}$.`, `Compare lower candidates $${lowerCandidates}$ and upper candidates $${upperCandidates}$.`, splitPoints.length > 0 - ? `Split at $${splitPoints.join(",\\;")}$.` + ? String.raw`Split at $${splitPoints.join(String.raw`,\;`)}$.` : `The verified setup is $${setup.integralLatex}$.`, ]; }; @@ -245,7 +245,7 @@ export function buildEvaluationPart( id: `interval-${String(index + 1).padStart(2, "0")}`, title: `Evaluate Region ${index + 1}`, intervalLatex: interval.labelLatex, - resultLatex: `y(t)=${interval.exprLatex},\\quad ${interval.labelLatex}`, + resultLatex: String.raw`y(t)=${interval.exprLatex},\quad ${interval.labelLatex}`, options: [], carriedZero, primitiveLatex: carriedZero ? "0" : primitiveBySignal.h, diff --git a/src/lib/math-engine/convolution/its-scaffolding/presentation.ts b/src/lib/math-engine/convolution/its-scaffolding/presentation.ts index b9cdfcfa..077f8627 100644 --- a/src/lib/math-engine/convolution/its-scaffolding/presentation.ts +++ b/src/lib/math-engine/convolution/its-scaffolding/presentation.ts @@ -18,8 +18,8 @@ import { createSeededPrng, shuffleWithRandom } from "$lib/math-engine/random"; /** Formats one finite or infinite scalar as exact LaTeX. */ export function formatConvolutionScalar(value: number): string { - if (value === Number.POSITIVE_INFINITY) return "\\infty"; - if (value === Number.NEGATIVE_INFINITY) return "-\\infty"; + if (value === Number.POSITIVE_INFINITY) return String.raw`\infty`; + if (value === Number.NEGATIVE_INFINITY) return String.raw`-\infty`; return String(value); } @@ -33,7 +33,7 @@ export function formatConvolutionPiecewiseLatex( `${expressions[index] ?? interval.exprLatex} & ${interval.labelLatex}`, ); return sanitizeLatexMath( - `y(t) = \\begin{cases} ${rows.join(" \\\\ ")} \\end{cases}`, + String.raw`y(t) = \begin{cases} ${rows.join(String.raw` \\ `)} \end{cases}`, ); } @@ -52,8 +52,8 @@ export function getFiniteConvolutionTransitionTimes( /** Formats one transformed moving edge. */ export function formatTranslatedEdge(value: number): string { - if (value === Number.POSITIVE_INFINITY) return "-\\infty"; - if (value === Number.NEGATIVE_INFINITY) return "\\infty"; + if (value === Number.POSITIVE_INFINITY) return String.raw`-\infty`; + if (value === Number.NEGATIVE_INFINITY) return String.raw`\infty`; return formatTranslatedArgument("t", value); } @@ -94,28 +94,27 @@ export function buildFormulaStep( ): ConvolutionItsChoiceStep { const matching = moving === "h" - ? "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(t-\\tau)\\,d\\tau" - : "y(t)=\\int_{-\\infty}^{\\infty}h(\\tau)x(t-\\tau)\\,d\\tau"; + ? String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(t-\tau)\,d\tau` + : String.raw`y(t)=\int_{-\infty}^{\infty}h(\tau)x(t-\tau)\,d\tau`; const selectedWithoutFlip = moving === "h" - ? "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(\\tau-t)\\,d\\tau" - : "y(t)=\\int_{-\\infty}^{\\infty}h(\\tau)x(\\tau-t)\\,d\\tau"; + ? String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(\tau-t)\,d\tau` + : String.raw`y(t)=\int_{-\infty}^{\infty}h(\tau)x(\tau-t)\,d\tau`; const otherCorrect = moving === "h" - ? "y(t)=\\int_{-\\infty}^{\\infty}h(\\tau)x(t-\\tau)\\,d\\tau" - : "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(t-\\tau)\\,d\\tau"; + ? String.raw`y(t)=\int_{-\infty}^{\infty}h(\tau)x(t-\tau)\,d\tau` + : String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(t-\tau)\,d\tau`; const otherWithoutFlip = moving === "h" - ? "y(t)=\\int_{-\\infty}^{\\infty}h(\\tau)x(\\tau-t)\\,d\\tau" - : "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(\\tau-t)\\,d\\tau"; + ? String.raw`y(t)=\int_{-\infty}^{\infty}h(\tau)x(\tau-t)\,d\tau` + : String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(\tau-t)\,d\tau`; const options: ConvolutionItsOption[] = [ { id: `formula-${moving}-correct`, latex: matching, isCorrect: true }, { id: `formula-${moving}-no-flip`, latex: selectedWithoutFlip, isCorrect: false, - feedback: - "This shifts the selected signal without reflecting it. The moving argument must be $t-\\tau$.", + feedback: String.raw`This shifts the selected signal without reflecting it. The moving argument must be $t-\tau$.`, }, { id: `formula-${moving}-other-path`, @@ -135,11 +134,11 @@ export function buildFormulaStep( const optionSeed = (seed ^ (moving === "x" ? 0x58_33_ba_11 : 0x48_33_ba_11)) >>> 0; return { - prompt: `Which integral keeps $${moving === "h" ? "x" : "h"}(\\tau)$ fixed and moves $${moving}(t)$?`, + prompt: String.raw`Which integral keeps $${moving === "h" ? "x" : "h"}(\tau)$ fixed and moves $${moving}(t)$?`, options: shuffleWithRandom(options, createSeededPrng(optionSeed)), hints: [ - "The fixed signal keeps the argument $\\tau$.", - "The selected moving signal receives the argument $t-\\tau$.", + String.raw`The fixed signal keeps the argument $\tau$.`, + String.raw`The selected moving signal receives the argument $t-\tau$.`, `The matching path is $${matching}$.`, ], }; diff --git a/src/lib/math-engine/convolution/pulse-formatting.ts b/src/lib/math-engine/convolution/pulse-formatting.ts index 75377e56..5a23fbff 100644 --- a/src/lib/math-engine/convolution/pulse-formatting.ts +++ b/src/lib/math-engine/convolution/pulse-formatting.ts @@ -36,7 +36,7 @@ export function formatRectPulseLatex( const argument = formatTranslatedArgument("t", shift); const body = width === 1 - ? `\\operatorname{rect}(${argument})` - : `\\operatorname{rect}\\left(\\frac{${argument}}{${width}}\\right)`; + ? String.raw`\operatorname{rect}(${argument})` + : String.raw`\operatorname{rect}\left(\frac{${argument}}{${width}}\right)`; return sanitizeLatexMath(formatPulseScale(amplitude, body)); } diff --git a/src/lib/math-engine/evaluator.ts b/src/lib/math-engine/evaluator.ts index 1efeca87..e08b58df 100644 --- a/src/lib/math-engine/evaluator.ts +++ b/src/lib/math-engine/evaluator.ts @@ -94,7 +94,10 @@ export function parseStrictLatex(latex: string): unknown { (token: string): string => token.startsWith("\\") ? token - : token.replace(/u\s*$/, "\\operatorname{Heaviside}"), + : token.replace( + /u\s*$/, + String.raw`\operatorname{Heaviside}`, + ), ); return parse(normalizeMathLatex(expression, false)); } @@ -124,13 +127,16 @@ export function normalizeMathLatex( return ( normalized // Convert bare 'pi' followed by a variable (e.g. 100pit -> 100\pi t, pit -> \pi t) - .replace(/(^|[^a-zA-Z\\])pi([a-zA-Z])(?=[^a-zA-Z]|$)/g, "$1\\pi $2") + .replace( + /(^|[^a-zA-Z\\])pi([a-zA-Z])(?=[^a-zA-Z]|$)/g, + String.raw`$1\pi $2`, + ) // Convert standalone bare 'pi' (e.g. 100pi t -> 100\pi t, 2*pi -> 2*\pi) - .replace(/(^|[^a-zA-Z\\])pi(?=[^a-zA-Z]|$)/g, "$1\\pi") + .replace(/(^|[^a-zA-Z\\])pi(?=[^a-zA-Z]|$)/g, String.raw`$1\pi`) // Convert bare functions without leading backslash (e.g. cos, sin, tan, exp, sqrt, ln, log) .replace( /(^|[^a-zA-Z\\])(cos|sin|tan|exp|sqrt|ln|log)(?=[^a-zA-Z]|$)/g, - "$1\\$2", + String.raw`$1\$2`, ) ); } @@ -303,7 +309,7 @@ export function evaluatePiecewiseLatexAt(latex: string, t: number): number { const body = match[1]; const rows = body - .split("\\\\") + .split(String.raw`\\`) .map((r) => r.trim()) .filter(Boolean); @@ -315,8 +321,8 @@ export function evaluatePiecewiseLatexAt(latex: string, t: number): number { const parts = row.split("&"); exprPart = (parts[0] ?? "").trim().replace(/[,;]$/, "").trim(); condPart = parts.slice(1).join("&").trim(); - } else if (row.includes("\\text{for}")) { - const parts = row.split("\\text{for}"); + } else if (row.includes(String.raw`\text{for}`)) { + const parts = row.split(String.raw`\text{for}`); exprPart = (parts[0] ?? "") .trim() .replace(/\\quad$/, "") diff --git a/src/lib/math-engine/formatting.ts b/src/lib/math-engine/formatting.ts index 0cac827c..46c8657a 100644 --- a/src/lib/math-engine/formatting.ts +++ b/src/lib/math-engine/formatting.ts @@ -114,8 +114,8 @@ export function formatQuadraticPolynomial( */ export function formatOdeLhs(a2: number, a1: number, a0: number): string { const terms: PolynomialTerm[] = [ - { coeff: a2, symbol: "\\frac{d^2 y}{dt^2}" }, - { coeff: a1, symbol: "\\frac{dy}{dt}" }, + { coeff: a2, symbol: String.raw`\frac{d^2 y}{dt^2}` }, + { coeff: a1, symbol: String.raw`\frac{dy}{dt}` }, { coeff: a0, symbol: "y(t)" }, ]; @@ -301,7 +301,7 @@ export function sanitizeUnitCoefficients(latex: string): string { // Lookaround ensures we do NOT match multi-digit numbers like j10, j11, -j10, 10j, 31j, 151j, 0.1j s = s.replace(/(? x, -1x -> -x, + 1t -> + t, - 1t -> - t, (1t -> (t, (-1t -> (-t @@ -320,17 +320,17 @@ export function sanitizeUnitCoefficients(latex: string): string { // Lookahead (?![0-9]) preserves \cos(10t), \cos(11t), \sin(151t) s = s.replace( /\\(cos|sin|tan|cot|sec|csc)\(\s*(-?)1([a-zA-Z])(?![0-9])\s*\)/g, - "\\$1($2$3)", + String.raw`\$1($2$3)`, ); s = s.replace( /\\(cos|sin|tan|cot|sec|csc)\(\s*(-?)j1([a-zA-Z])(?![0-9])\s*\)/g, - "\\$1($2j$3)", + String.raw`\$1($2j$3)`, ); // Unit multiplier before functions: 1\cos -> \cos, -1\cos -> -\cos, 1e^{ -> e^{ s = s.replace( /(?0$, use $c_n=2|F_n|=\\sqrt{a_n^2+b_n^2}$.", - "Assign phase only to nonzero harmonics with $\\theta_n=\\operatorname{atan2}(-b_n,a_n)=\\angle F_n$.", + String.raw`For $n>0$, use $c_n=2|F_n|=\sqrt{a_n^2+b_n^2}$.`, + String.raw`Assign phase only to nonzero harmonics with $\theta_n=\operatorname{atan2}(-b_n,a_n)=\angle F_n$.`, ], }, ], @@ -121,13 +121,13 @@ export function generateFourierSeriesProblem( title: "Period and Fundamental Frequency", description: "Read one complete repetition from the waveform and convert its period to angular frequency.", - latex: `T_0=${periodLatex}\\text{ s},\\qquad \\omega_0=\\frac{2\\pi}{T_0}=\\frac{2\\pi}{${periodLatex}}=${w0Latex}\\text{ rad/s}`, + latex: String.raw`T_0=${periodLatex}\text{ s},\qquad \omega_0=\frac{2\pi}{T_0}=\frac{2\pi}{${periodLatex}}=${w0Latex}\text{ rad/s}`, }, { title: "Symmetry and Vanishing Terms", description: "Test origin parity and half-wave symmetry independently, then remove coefficient families that must vanish.", - latex: `\\begin{gathered}\\text{origin parity: }${coeffs.originParity},\\qquad \\text{half-wave symmetry: }${coeffs.hasHalfWaveSymmetry ? "\\text{yes}" : "\\text{no}"}\\\\${coeffs.originParity === "odd" ? "a_0=a_n=0" : coeffs.originParity === "even" ? "b_n=0" : "a_n\\text{ and }b_n\\text{ must both be evaluated}"}\\end{gathered}`, + latex: String.raw`\begin{gathered}\text{origin parity: }${coeffs.originParity},\qquad \text{half-wave symmetry: }${coeffs.hasHalfWaveSymmetry ? String.raw`\text{yes}` : String.raw`\text{no}`}\\${coeffs.originParity === "odd" ? String.raw`a_0=a_n=0` : coeffs.originParity === "even" ? String.raw`b_n=0` : String.raw`a_n\text{ and }b_n\text{ must both be evaluated}`}\end{gathered}`, }, { title: "Representation Selection", @@ -137,8 +137,8 @@ export function generateFourierSeriesProblem( : "The assigned trigonometric path evaluates the real coefficient families remaining after symmetry shortcuts.", latex: itsData.step4.correctForm === "exp" - ? "F_n=\\frac{1}{T_0}\\int_{T_0}x(t)e^{-jn\\omega_0t}\\,dt" - : "x(t)=\\frac{a_0}{2}+\\sum_{n=1}^{\\infty}[a_n\\cos(n\\omega_0t)+b_n\\sin(n\\omega_0t)]", + ? String.raw`F_n=\frac{1}{T_0}\int_{T_0}x(t)e^{-jn\omega_0t}\,dt` + : String.raw`x(t)=\frac{a_0}{2}+\sum_{n=1}^{\infty}[a_n\cos(n\omega_0t)+b_n\sin(n\omega_0t)]`, }, { title: "Piecewise Integral Setup", @@ -147,12 +147,11 @@ export function generateFourierSeriesProblem( latex: itsData.step4.correctForm === "exp" ? derivation.expIntegralLatex - : `\\begin{gathered}${itsData.step5.parts.map(({ resultLatex }) => resultLatex).join("\\\\")}\\end{gathered}`, + : String.raw`\begin{gathered}${itsData.step5.parts.map(({ resultLatex }) => resultLatex).join(String.raw`\\`)}\end{gathered}`, }, { title: "Definite Integral Evaluation", - description: - "Apply the bounds and simplify parity factors such as $(-1)^n$ and $\\sin(n\\pi/2)$.", + description: String.raw`Apply the bounds and simplify parity factors such as $(-1)^n$ and $\sin(n\pi/2)$.`, latex: itsData.step4.correctForm === "exp" ? getExponentialEvaluationLatex(derivation) @@ -162,7 +161,7 @@ export function generateFourierSeriesProblem( title: "DC Offset Derivation", description: "Evaluate the average separately; the constant appearing in the trigonometric series is $a_0/2$.", - latex: `a_0=\\frac{2}{T_0}\\int_{T_0}x(t)\\,dt=${derivation.a0Latex},\\qquad F_0=\\frac{a_0}{2}`, + latex: String.raw`a_0=\frac{2}{T_0}\int_{T_0}x(t)\,dt=${derivation.a0Latex},\qquad F_0=\frac{a_0}{2}`, }, { title: `${primaryName} Synthesis`, @@ -182,8 +181,8 @@ export function generateFourierSeriesProblem( seed, waveformType, title: "Practice Problem: Periodic Waveform", - periodLatex: `T_0 = ${periodLatex}\\text{ s}`, - omega0Latex: `\\omega_0 = \\frac{2\\pi}{${periodLatex}} = ${w0Latex}\\text{ rad/s}`, + periodLatex: String.raw`T_0 = ${periodLatex}\text{ s}`, + omega0Latex: String.raw`\omega_0 = \frac{2\pi}{${periodLatex}} = ${w0Latex}\text{ rad/s}`, signalLatex, a0Latex: derivation.a0Latex, anLatex: derivation.anLatex, diff --git a/src/lib/math-engine/fourier-series/its-scaffolding/step1-period-freq.ts b/src/lib/math-engine/fourier-series/its-scaffolding/step1-period-freq.ts index ca1ba191..34e485d5 100644 --- a/src/lib/math-engine/fourier-series/its-scaffolding/step1-period-freq.ts +++ b/src/lib/math-engine/fourier-series/its-scaffolding/step1-period-freq.ts @@ -24,9 +24,16 @@ export function buildStep1Data( const periodLatex = formatFourierNumber(T0); const w0Aliases = T0 === 2 - ? ["pi", "\\pi", "1pi", "3.14", "3.1415", "3.1416"] + ? ["pi", String.raw`\pi`, "1pi", "3.14", "3.1415", "3.1416"] : T0 === 4 - ? ["pi/2", "\\pi/2", "0.5pi", "0.5\\pi", "1.57", "1.5708"] + ? [ + "pi/2", + String.raw`\pi/2`, + "0.5pi", + String.raw`0.5\pi`, + "1.57", + "1.5708", + ] : [w0Latex, formatFourierNumber(w0)]; return { @@ -38,8 +45,8 @@ export function buildStep1Data( w0Aliases, hints: [ "Look at the bounds of the definition. Over what duration does the signal repeat itself entirely?", - `The signal repeats every period $T_0 = ${periodLatex}\\text{ s}$. The fundamental frequency is $\\omega_0 = \\frac{2\\pi}{T_0}$.`, - `Substitute $T_0 = ${periodLatex}$: $\\omega_0 = \\frac{2\\pi}{${periodLatex}} = ${w0Latex}\\text{ rad/s}$. Ensure units are $\\text{s}$ and $\\text{rad/s}$.`, + String.raw`The signal repeats every period $T_0 = ${periodLatex}\text{ s}$. The fundamental frequency is $\omega_0 = \frac{2\pi}{T_0}$.`, + String.raw`Substitute $T_0 = ${periodLatex}$: $\omega_0 = \frac{2\pi}{${periodLatex}} = ${w0Latex}\text{ rad/s}$. Ensure units are $\text{s}$ and $\text{rad/s}$.`, ], }; } diff --git a/src/lib/math-engine/fourier-series/its-scaffolding/step4-form.ts b/src/lib/math-engine/fourier-series/its-scaffolding/step4-form.ts index 487197f9..a5dfa95c 100644 --- a/src/lib/math-engine/fourier-series/its-scaffolding/step4-form.ts +++ b/src/lib/math-engine/fourier-series/its-scaffolding/step4-form.ts @@ -30,7 +30,7 @@ export function buildStep4Data( correctForm, hints: [ `This guided problem uses the ${assignedName} form. Both Trigonometric and Exponential representations are mathematically valid.`, - "Trigonometric form separates $a_n$ and $b_n$. Exponential form $F_n$ combines them using $e^{-j n \\omega_0 t}$.", + String.raw`Trigonometric form separates $a_n$ and $b_n$. Exponential form $F_n$ combines them using $e^{-j n \omega_0 t}$.`, correctForm === "trig" ? "Follow the Trigonometric path by evaluating DC and the real coefficient families not already eliminated by symmetry." : "Follow the Exponential path by evaluating $F_n$, including its DC case separately.", @@ -38,8 +38,7 @@ export function buildStep4Data( misconceptions: { trig: `Trigonometric form is valid. Select the assigned ${assignedName} form for this guided derivation.`, exp: `Exponential form is valid. Select the assigned ${assignedName} form for this guided derivation.`, - compact: - "Compact polar form ($C_n, \\theta_n$) is derived from Trigonometric or Exponential coefficients, not integrated directly.", + compact: String.raw`Compact polar form ($C_n, \theta_n$) is derived from Trigonometric or Exponential coefficients, not integrated directly.`, }, }; } diff --git a/src/lib/math-engine/fourier-series/its-scaffolding/step5-integrals.ts b/src/lib/math-engine/fourier-series/its-scaffolding/step5-integrals.ts index b5dca302..0288bbdf 100644 --- a/src/lib/math-engine/fourier-series/its-scaffolding/step5-integrals.ts +++ b/src/lib/math-engine/fourier-series/its-scaffolding/step5-integrals.ts @@ -43,23 +43,47 @@ export function buildIntegralOptions( }), })); } - const scalingDistractor = correct.includes("\\frac{4}{T_0}") - ? correct.replace("\\frac{4}{T_0}", "\\frac{2}{T_0}") - : correct.includes("\\frac{2j}{T_0}") - ? correct.replace("\\frac{2j}{T_0}", "\\frac{j}{T_0}") - : correct.includes("\\frac{2}{T_0}") - ? correct.replace("\\frac{2}{T_0}", "\\frac{1}{T_0}") - : correct.replace("\\frac{1}{T_0}", "\\frac{2}{T_0}"); - const kernelDistractor = correct.includes("e^{-jn\\omega_0t}") - ? correct.replace("e^{-jn\\omega_0t}", "e^{+jn\\omega_0t}") - : correct.includes("\\cos(n\\omega_0t)") - ? correct.replaceAll("\\cos(n\\omega_0t)", "\\sin(n\\omega_0t)") - : correct.includes("\\sin(n\\omega_0t)") - ? correct.replaceAll("\\sin(n\\omega_0t)", "\\cos(n\\omega_0t)") - : correct.replace("\\,dt", "\\cos(n\\omega_0t)\\,dt"); - const fullIntervalDistractor = correct.includes("\\int_0^{T_0/2}") - ? correct.replace("\\int_0^{T_0/2}", "\\int_0^{T_0}") - : correct.replace("\\int_0^{T_0/4}", "\\int_0^{T_0/2}"); + const scalingDistractor = correct.includes(String.raw`\frac{4}{T_0}`) + ? correct.replace(String.raw`\frac{4}{T_0}`, String.raw`\frac{2}{T_0}`) + : correct.includes(String.raw`\frac{2j}{T_0}`) + ? correct.replace( + String.raw`\frac{2j}{T_0}`, + String.raw`\frac{j}{T_0}`, + ) + : correct.includes(String.raw`\frac{2}{T_0}`) + ? correct.replace( + String.raw`\frac{2}{T_0}`, + String.raw`\frac{1}{T_0}`, + ) + : correct.replace( + String.raw`\frac{1}{T_0}`, + String.raw`\frac{2}{T_0}`, + ); + const kernelDistractor = correct.includes(String.raw`e^{-jn\omega_0t}`) + ? correct.replace( + String.raw`e^{-jn\omega_0t}`, + String.raw`e^{+jn\omega_0t}`, + ) + : correct.includes(String.raw`\cos(n\omega_0t)`) + ? correct.replaceAll( + String.raw`\cos(n\omega_0t)`, + String.raw`\sin(n\omega_0t)`, + ) + : correct.includes(String.raw`\sin(n\omega_0t)`) + ? correct.replaceAll( + String.raw`\sin(n\omega_0t)`, + String.raw`\cos(n\omega_0t)`, + ) + : correct.replace( + String.raw`\,dt`, + String.raw`\cos(n\omega_0t)\,dt`, + ); + const fullIntervalDistractor = correct.includes(String.raw`\int_0^{T_0/2}`) + ? correct.replace(String.raw`\int_0^{T_0/2}`, String.raw`\int_0^{T_0}`) + : correct.replace( + String.raw`\int_0^{T_0/4}`, + String.raw`\int_0^{T_0/2}`, + ); return [ { id: "c1", latex: correct, isCorrect: true }, @@ -74,8 +98,8 @@ export function buildIntegralOptions( id: "d2", latex: kernelDistractor, isCorrect: false, - feedback: correct.includes("e^{-jn\\omega_0t}") - ? "Sign Error: Exponential Fourier coefficients require the kernel $e^{-j n \\omega_0 t}$." + feedback: correct.includes(String.raw`e^{-jn\omega_0t}`) + ? String.raw`Sign Error: Exponential Fourier coefficients require the kernel $e^{-j n \omega_0 t}$.` : "Kernel Error: The selected sine or cosine kernel does not match the non-zero coefficient family.", }, { @@ -224,7 +248,7 @@ export function buildStep5Data( carriedCoefficients, hints: [ "Use symmetry to choose the non-zero coefficient family before writing an integral.", - "Trigonometric coefficients use $2/T_0$; exponential coefficients use $1/T_0$ and $e^{-jn\\omega_0t}$.", + String.raw`Trigonometric coefficients use $2/T_0$; exponential coefficients use $1/T_0$ and $e^{-jn\omega_0t}$.`, "Split the integral exactly where the waveform definition changes and omit intervals where the signal is zero.", ], }; diff --git a/src/lib/math-engine/fourier-series/its-scaffolding/step6-evaluation.ts b/src/lib/math-engine/fourier-series/its-scaffolding/step6-evaluation.ts index 02450011..d0ba995c 100644 --- a/src/lib/math-engine/fourier-series/its-scaffolding/step6-evaluation.ts +++ b/src/lib/math-engine/fourier-series/its-scaffolding/step6-evaluation.ts @@ -53,21 +53,21 @@ export function buildEvaluationOptions( }, { id: `${target}-scale`, - latex: `${label}=\\frac{1}{2}\\left(${resultLatex}\\right)`, + latex: String.raw`${label}=\frac{1}{2}\left(${resultLatex}\right)`, isCorrect: false, feedback: "Scale Factor Error: Recheck the Fourier normalization before applying the integration bounds.", }, { id: `${target}-sign`, - latex: `${label}=-\\left(${resultLatex}\\right)`, + latex: String.raw`${label}=-\left(${resultLatex}\right)`, isCorrect: false, feedback: "Sign Error: Re-evaluate the antiderivative at the upper and lower bounds in order.", }, { id: `${target}-support`, - latex: `${label}=2\\left(${resultLatex}\\right)`, + latex: String.raw`${label}=2\left(${resultLatex}\right)`, isCorrect: false, feedback: "Scale Factor Error: Do not apply the Fourier normalization a second time.", @@ -136,7 +136,7 @@ export function buildStep6Data( carriedCoefficients, hints: [ "Apply the antiderivative to every non-zero interval before simplifying the harmonic index.", - "Use $\\cos(n\\pi)=(-1)^n$ and $\\sin(n\\pi/2)$ to expose vanished or alternating harmonics.", + String.raw`Use $\cos(n\pi)=(-1)^n$ and $\sin(n\pi/2)$ to expose vanished or alternating harmonics.`, form === "exp" ? `The exponential integral evaluates to $${getExponentialEvaluationLatex(derivation)}$.` : `The evaluated result is $${derivation.evaluationLatex}$.`, diff --git a/src/lib/math-engine/fourier-series/its-scaffolding/step7-series.ts b/src/lib/math-engine/fourier-series/its-scaffolding/step7-series.ts index 9e3209fc..ae4a42b3 100644 --- a/src/lib/math-engine/fourier-series/its-scaffolding/step7-series.ts +++ b/src/lib/math-engine/fourier-series/its-scaffolding/step7-series.ts @@ -22,14 +22,14 @@ export function buildPrimarySeriesOptions( form: FourierPrimaryForm, ): FourierItsOption[] { // Coefficient definitions follow the synthesis expression and must stay intact. - const definitionIndex = correct.indexOf(",\\qquad"); + const definitionIndex = correct.indexOf(String.raw`,\qquad`); const synthesis = definitionIndex < 0 ? correct : correct.slice(0, definitionIndex); const definitions = definitionIndex < 0 ? "" : correct.slice(definitionIndex); const rhs = synthesis.slice(synthesis.indexOf("=") + 1).trim(); - const signDistractor = `x(t)=-\\left(${rhs}\\right)${definitions}`; - const scaleDistractor = `x(t)=\\frac{1}{2}\\left(${rhs}\\right)${definitions}`; + const signDistractor = String.raw`x(t)=-\left(${rhs}\right)${definitions}`; + const scaleDistractor = String.raw`x(t)=\frac{1}{2}\left(${rhs}\right)${definitions}`; // Double only the independent time symbol; preserve phase and coefficient symbols. const doubledTime = rhs.replace(/(? - `x(t)=\\frac{c_0}{2}+\\sum_{n=1}^{\\infty}c_n\\cos(n ${w0Latex} t+\\theta_n),\\qquad ${body}`; + String.raw`x(t)=\frac{c_0}{2}+\sum_{n=1}^{\infty}c_n\cos(n ${w0Latex} t+\theta_n),\qquad ${body}`; switch (waveformType) { case "square": case "square_odd": return harmonic( - `c_0=0,\\quad c_n=\\begin{cases}\\dfrac{4(${A})}{n\\pi},&n\\text{ odd}\\\\0,&n\\text{ even}\\end{cases},\\quad \\theta_n=-\\dfrac{\\pi}{2}\\ (n\\text{ odd})`, + String.raw`c_0=0,\quad c_n=\begin{cases}\dfrac{4(${A})}{n\pi},&n\text{ odd}\\0,&n\text{ even}\end{cases},\quad \theta_n=-\dfrac{\pi}{2}\ (n\text{ odd})`, ); case "square_even": return harmonic( - `c_0=0,\\quad c_n=\\begin{cases}\\dfrac{4(${A})}{n\\pi},&n\\text{ odd}\\\\0,&n\\text{ even}\\end{cases},\\quad \\theta_n=\\begin{cases}0,&n\\equiv1\\pmod4\\\\\\pi,&n\\equiv3\\pmod4\\end{cases}`, + String.raw`c_0=0,\quad c_n=\begin{cases}\dfrac{4(${A})}{n\pi},&n\text{ odd}\\0,&n\text{ even}\end{cases},\quad \theta_n=\begin{cases}0,&n\equiv1\pmod4\\\pi,&n\equiv3\pmod4\end{cases}`, ); case "triangle": case "triangle_even": return harmonic( - `c_0=0,\\quad c_n=\\begin{cases}\\dfrac{8(${A})}{n^2\\pi^2},&n\\text{ odd}\\\\0,&n\\text{ even}\\end{cases},\\quad \\theta_n=0\\ (n\\text{ odd})`, + String.raw`c_0=0,\quad c_n=\begin{cases}\dfrac{8(${A})}{n^2\pi^2},&n\text{ odd}\\0,&n\text{ even}\end{cases},\quad \theta_n=0\ (n\text{ odd})`, ); case "triangle_odd": return harmonic( - `c_0=0,\\quad c_n=\\begin{cases}\\dfrac{8(${A})}{n^2\\pi^2},&n\\text{ odd}\\\\0,&n\\text{ even}\\end{cases},\\quad \\theta_n=\\begin{cases}-\\dfrac{\\pi}{2},&n\\equiv1\\pmod4\\\\\\dfrac{\\pi}{2},&n\\equiv3\\pmod4\\end{cases}`, + String.raw`c_0=0,\quad c_n=\begin{cases}\dfrac{8(${A})}{n^2\pi^2},&n\text{ odd}\\0,&n\text{ even}\end{cases},\quad \theta_n=\begin{cases}-\dfrac{\pi}{2},&n\equiv1\pmod4\\\dfrac{\pi}{2},&n\equiv3\pmod4\end{cases}`, ); case "sawtooth": return harmonic( - `c_0=0,\\quad c_n=\\dfrac{2(${A})}{n\\pi},\\quad \\theta_n=\\dfrac{(-1)^n\\pi}{2}`, + String.raw`c_0=0,\quad c_n=\dfrac{2(${A})}{n\pi},\quad \theta_n=\dfrac{(-1)^n\pi}{2}`, ); case "half_wave_sine": return harmonic( - `c_0=\\dfrac{2(${A})}{\\pi},\\quad c_1=\\dfrac{${A}}{2},\\ \\theta_1=-\\dfrac{\\pi}{2},\\quad c_{2k}=\\dfrac{2(${A})}{\\pi(4k^2-1)},\\ \\theta_{2k}=\\pi,\\quad c_n=0\\ (n>1\\text{ odd})`, + String.raw`c_0=\dfrac{2(${A})}{\pi},\quad c_1=\dfrac{${A}}{2},\ \theta_1=-\dfrac{\pi}{2},\quad c_{2k}=\dfrac{2(${A})}{\pi(4k^2-1)},\ \theta_{2k}=\pi,\quad c_n=0\ (n>1\text{ odd})`, ); case "full_wave_sine": return harmonic( - `c_0=\\dfrac{4(${A})}{\\pi},\\quad c_n=\\dfrac{4(${A})}{\\pi(4n^2-1)},\\quad \\theta_n=\\pi`, + String.raw`c_0=\dfrac{4(${A})}{\pi},\quad c_n=\dfrac{4(${A})}{\pi(4n^2-1)},\quad \theta_n=\pi`, ); default: { const _exhaustiveCheck: never = waveformType; @@ -129,20 +129,20 @@ export function buildSignalLatex( switch (waveformType) { case "square": case "square_odd": - return `x(t)=\\begin{cases}-${A}&-${halfPeriod}1\\text{ odd}\\end{cases}`; - a0IntegralLatex = `a_0=\\frac{2}{T_0}\\int_0^{T_0/2}${A}\\sin(\\omega_0t)\\,dt`; - integralLatex = `F_n=\\frac{1}{T_0}\\int_0^{T_0/2}${A}\\sin(\\omega_0t)e^{-jn\\omega_0t}\\,dt`; + a0Latex = String.raw`\frac{2${amplitude}}{\pi}`; + anLatex = String.raw`\begin{cases}\dfrac{2${amplitude}}{\pi(1-n^2)},&n\text{ even}\\0,&n\text{ odd}\end{cases}`; + bnLatex = String.raw`\begin{cases}\dfrac{${A}}{2},&n=1\\0,&n\ne1\end{cases}`; + FnLatex = String.raw`\begin{cases}\dfrac{${A}}{\pi},&n=0\\-j\dfrac{${A}}{4},&n=1\\j\dfrac{${A}}{4},&n=-1\\\dfrac{${A}}{\pi(1-n^2)},&n\ne0\text{ even}\\0,&|n|>1\text{ odd}\end{cases}`; + a0IntegralLatex = String.raw`a_0=\frac{2}{T_0}\int_0^{T_0/2}${A}\sin(\omega_0t)\,dt`; + integralLatex = String.raw`F_n=\frac{1}{T_0}\int_0^{T_0/2}${A}\sin(\omega_0t)e^{-jn\omega_0t}\,dt`; expIntegralLatex = integralLatex; - evaluationLatex = `a_0=\\left[-\\frac{2${amplitude}\\cos(\\omega_0t)}{T_0\\omega_0}\\right]_0^{T_0/2}=\\frac{2${amplitude}}{\\pi},\\quad a_n=${anLatex},\\quad b_n=${bnLatex}`; + evaluationLatex = String.raw`a_0=\left[-\frac{2${amplitude}\cos(\omega_0t)}{T_0\omega_0}\right]_0^{T_0/2}=\frac{2${amplitude}}{\pi},\quad a_n=${anLatex},\quad b_n=${bnLatex}`; break; case "full_wave_sine": - a0Latex = `\\frac{4${amplitude}}{\\pi}`; - anLatex = `-\\frac{4${amplitude}}{\\pi(4n^2-1)}`; + a0Latex = String.raw`\frac{4${amplitude}}{\pi}`; + anLatex = String.raw`-\frac{4${amplitude}}{\pi(4n^2-1)}`; bnLatex = "0"; - FnLatex = `\\begin{cases}\\dfrac{2${amplitude}}{\\pi},&n=0\\\\-\\dfrac{2${amplitude}}{\\pi(4n^2-1)},&n\\ne0\\end{cases}`; - a0IntegralLatex = `a_0=\\frac{4}{T_0}\\int_0^{T_0/2}${A}\\sin\\left(\\frac{\\pi t}{T_0}\\right)\\,dt`; - integralLatex = `a_n=\\frac{4}{T_0}\\int_0^{T_0/2}${A}\\sin\\left(\\frac{\\pi t}{T_0}\\right)\\cos(n\\omega_0t)\\,dt`; - expIntegralLatex = `F_n=\\frac{2}{T_0}\\int_0^{T_0/2}${A}\\sin\\left(\\frac{\\pi t}{T_0}\\right)\\cos(n\\omega_0t)\\,dt`; - evaluationLatex = `a_0=\\frac{4${amplitude}}{\\pi},\\qquad a_n=-\\frac{4${amplitude}}{\\pi(4n^2-1)},\\qquad b_n=0`; + FnLatex = String.raw`\begin{cases}\dfrac{2${amplitude}}{\pi},&n=0\\-\dfrac{2${amplitude}}{\pi(4n^2-1)},&n\ne0\end{cases}`; + a0IntegralLatex = String.raw`a_0=\frac{4}{T_0}\int_0^{T_0/2}${A}\sin\left(\frac{\pi t}{T_0}\right)\,dt`; + integralLatex = String.raw`a_n=\frac{4}{T_0}\int_0^{T_0/2}${A}\sin\left(\frac{\pi t}{T_0}\right)\cos(n\omega_0t)\,dt`; + expIntegralLatex = String.raw`F_n=\frac{2}{T_0}\int_0^{T_0/2}${A}\sin\left(\frac{\pi t}{T_0}\right)\cos(n\omega_0t)\,dt`; + evaluationLatex = String.raw`a_0=\frac{4${amplitude}}{\pi},\qquad a_n=-\frac{4${amplitude}}{\pi(4n^2-1)},\qquad b_n=0`; break; default: { const _exhaustiveCheck: never = waveformType; @@ -257,16 +257,16 @@ export function buildFourierSeriesSymbolicDerivation( } } - const finalExpLatex = `x(t)=\\sum_{n=-\\infty}^{\\infty}F_ne^{j n ${w0Latex} t},\\qquad F_n=${FnLatex}`; + const finalExpLatex = String.raw`x(t)=\sum_{n=-\infty}^{\infty}F_ne^{j n ${w0Latex} t},\qquad F_n=${FnLatex}`; const anIntegralLatex = waveformType === "half_wave_sine" - ? `a_n=\\frac{2}{T_0}\\int_0^{T_0/2}${A}\\sin(\\omega_0t)\\cos(n\\omega_0t)\\,dt` + ? String.raw`a_n=\frac{2}{T_0}\int_0^{T_0/2}${A}\sin(\omega_0t)\cos(n\omega_0t)\,dt` : coeffs.originParity === "even" ? integralLatex : buildFullPeriodIntegral(coeffs, "an"); const bnIntegralLatex = waveformType === "half_wave_sine" - ? `b_n=\\frac{2}{T_0}\\int_0^{T_0/2}${A}\\sin(\\omega_0t)\\sin(n\\omega_0t)\\,dt` + ? String.raw`b_n=\frac{2}{T_0}\int_0^{T_0/2}${A}\sin(\omega_0t)\sin(n\omega_0t)\,dt` : coeffs.originParity === "odd" ? integralLatex : buildFullPeriodIntegral(coeffs, "bn"); @@ -298,42 +298,42 @@ function buildExponentialEvaluation( result: string, ): string { const A = `(${formatFourierNumber(coeffs.A)})`; - const k = "n\\omega_0"; - const sinePrimitive = `-\\frac{\\cos(n\\omega_0t)}{${k}}`; - const cosinePrimitive = `\\frac{\\sin(n\\omega_0t)}{${k}}`; + const k = String.raw`n\omega_0`; + const sinePrimitive = String.raw`-\frac{\cos(n\omega_0t)}{${k}}`; + const cosinePrimitive = String.raw`\frac{\sin(n\omega_0t)}{${k}}`; let evaluation: string; let dc = "0"; - let dcEvaluation = `\\frac{1}{2}\\left(${buildFullPeriodIntegral(coeffs, "a0").split("=")[1]}\\right)`; + let dcEvaluation = String.raw`\frac{1}{2}\left(${buildFullPeriodIntegral(coeffs, "a0").split("=")[1]}\right)`; switch (coeffs.waveformType) { case "square": case "square_odd": - evaluation = `-\\frac{2j${A}}{T_0}\\left[${sinePrimitive}\\right]_0^{T_0/2}`; + evaluation = String.raw`-\frac{2j${A}}{T_0}\left[${sinePrimitive}\right]_0^{T_0/2}`; break; case "square_even": - evaluation = `\\frac{2${A}}{T_0}\\left(\\left[${cosinePrimitive}\\right]_0^{T_0/4}-\\left[${cosinePrimitive}\\right]_{T_0/4}^{T_0/2}\\right)`; + evaluation = String.raw`\frac{2${A}}{T_0}\left(\left[${cosinePrimitive}\right]_0^{T_0/4}-\left[${cosinePrimitive}\right]_{T_0/4}^{T_0/2}\right)`; break; case "triangle": case "triangle_even": - evaluation = `\\frac{2${A}}{T_0}\\left[\\frac{(1-4t/T_0)\\sin(n\\omega_0t)}{${k}}-\\frac{4\\cos(n\\omega_0t)}{T_0n^2\\omega_0^2}\\right]_0^{T_0/2}`; + evaluation = String.raw`\frac{2${A}}{T_0}\left[\frac{(1-4t/T_0)\sin(n\omega_0t)}{${k}}-\frac{4\cos(n\omega_0t)}{T_0n^2\omega_0^2}\right]_0^{T_0/2}`; break; case "triangle_odd": - evaluation = `-\\frac{2j${A}}{T_0}\\left(\\left[-\\frac{4t\\cos(n\\omega_0t)}{T_0${k}}+\\frac{4\\sin(n\\omega_0t)}{T_0n^2\\omega_0^2}\\right]_0^{T_0/4}+\\left[-\\frac{(2-4t/T_0)\\cos(n\\omega_0t)}{${k}}-\\frac{4\\sin(n\\omega_0t)}{T_0n^2\\omega_0^2}\\right]_{T_0/4}^{T_0/2}\\right)`; + evaluation = String.raw`-\frac{2j${A}}{T_0}\left(\left[-\frac{4t\cos(n\omega_0t)}{T_0${k}}+\frac{4\sin(n\omega_0t)}{T_0n^2\omega_0^2}\right]_0^{T_0/4}+\left[-\frac{(2-4t/T_0)\cos(n\omega_0t)}{${k}}-\frac{4\sin(n\omega_0t)}{T_0n^2\omega_0^2}\right]_{T_0/4}^{T_0/2}\right)`; break; case "sawtooth": - evaluation = `-\\frac{4j${A}}{T_0^2}\\left[-\\frac{t\\cos(n\\omega_0t)}{${k}}+\\frac{\\sin(n\\omega_0t)}{n^2\\omega_0^2}\\right]_0^{T_0/2}`; + evaluation = String.raw`-\frac{4j${A}}{T_0^2}\left[-\frac{t\cos(n\omega_0t)}{${k}}+\frac{\sin(n\omega_0t)}{n^2\omega_0^2}\right]_0^{T_0/2}`; break; case "half_wave_sine": - dc = `\\frac{${A}}{\\pi}`; - dcEvaluation = `\\frac{${A}}{T_0}\\left[-\\frac{\\cos(\\omega_0t)}{\\omega_0}\\right]_0^{T_0/2}`; - evaluation = `\\frac{${A}}{2jT_0}\\left[\\frac{e^{-j(n-1)\\omega_0t}}{-j(n-1)\\omega_0}-\\frac{e^{-j(n+1)\\omega_0t}}{-j(n+1)\\omega_0}\\right]_0^{T_0/2}`; - return `\\begin{gathered}F_n=${evaluation}\\quad(n\\ne0,\\pm1)\\\\F_0=${dcEvaluation}=${dc}\\\\F_1=\\frac{${A}}{2jT_0}\\left[t-\\frac{e^{-2j\\omega_0t}}{-2j\\omega_0}\\right]_0^{T_0/2}=-j\\frac{${A}}{4}\\\\F_{-1}=\\frac{${A}}{2jT_0}\\left[\\frac{e^{2j\\omega_0t}}{2j\\omega_0}-t\\right]_0^{T_0/2}=j\\frac{${A}}{4}\\\\F_n=${result}\\end{gathered}`; + dc = String.raw`\frac{${A}}{\pi}`; + dcEvaluation = String.raw`\frac{${A}}{T_0}\left[-\frac{\cos(\omega_0t)}{\omega_0}\right]_0^{T_0/2}`; + evaluation = String.raw`\frac{${A}}{2jT_0}\left[\frac{e^{-j(n-1)\omega_0t}}{-j(n-1)\omega_0}-\frac{e^{-j(n+1)\omega_0t}}{-j(n+1)\omega_0}\right]_0^{T_0/2}`; + return String.raw`\begin{gathered}F_n=${evaluation}\quad(n\ne0,\pm1)\\F_0=${dcEvaluation}=${dc}\\F_1=\frac{${A}}{2jT_0}\left[t-\frac{e^{-2j\omega_0t}}{-2j\omega_0}\right]_0^{T_0/2}=-j\frac{${A}}{4}\\F_{-1}=\frac{${A}}{2jT_0}\left[\frac{e^{2j\omega_0t}}{2j\omega_0}-t\right]_0^{T_0/2}=j\frac{${A}}{4}\\F_n=${result}\end{gathered}`; case "full_wave_sine": - dc = `\\frac{2${A}}{\\pi}`; - dcEvaluation = `\\frac{2${A}}{T_0}\\left[-\\frac{\\cos(\\pi t/T_0)}{\\pi/T_0}\\right]_0^{T_0/2}`; - evaluation = `-\\frac{${A}}{T_0}\\left[\\frac{\\cos((1+2n)\\pi t/T_0)}{(1+2n)\\pi/T_0}+\\frac{\\cos((1-2n)\\pi t/T_0)}{(1-2n)\\pi/T_0}\\right]_0^{T_0/2}`; + dc = String.raw`\frac{2${A}}{\pi}`; + dcEvaluation = String.raw`\frac{2${A}}{T_0}\left[-\frac{\cos(\pi t/T_0)}{\pi/T_0}\right]_0^{T_0/2}`; + evaluation = String.raw`-\frac{${A}}{T_0}\left[\frac{\cos((1+2n)\pi t/T_0)}{(1+2n)\pi/T_0}+\frac{\cos((1-2n)\pi t/T_0)}{(1-2n)\pi/T_0}\right]_0^{T_0/2}`; break; } - return `\\begin{gathered}F_n=${evaluation}\\quad(n\\ne0)\\\\F_0=${dcEvaluation}=${dc}\\\\F_n=${result}\\end{gathered}`; + return String.raw`\begin{gathered}F_n=${evaluation}\quad(n\ne0)\\F_0=${dcEvaluation}=${dc}\\F_n=${result}\end{gathered}`; } /** @@ -351,8 +351,8 @@ function buildFullPeriodIntegral( target === "a0" ? "" : target === "an" - ? "\\cos(n\\omega_0t)" - : "\\sin(n\\omega_0t)"; + ? String.raw`\cos(n\omega_0t)` + : String.raw`\sin(n\omega_0t)`; const { label } = FOURIER_COEFFICIENT_METADATA[target]; let pieces: [string, string, string][]; switch (coeffs.waveformType) { @@ -372,32 +372,32 @@ function buildFullPeriodIntegral( break; case "triangle_odd": pieces = [ - ["-T_0/2", "-T_0/4", `-2${A}-\\frac{4${A}t}{T_0}`], - ["-T_0/4", "T_0/4", `\\frac{4${A}t}{T_0}`], - ["T_0/4", "T_0/2", `2${A}-\\frac{4${A}t}{T_0}`], + ["-T_0/2", "-T_0/4", String.raw`-2${A}-\frac{4${A}t}{T_0}`], + ["-T_0/4", "T_0/4", String.raw`\frac{4${A}t}{T_0}`], + ["T_0/4", "T_0/2", String.raw`2${A}-\frac{4${A}t}{T_0}`], ]; break; case "sawtooth": - pieces = [["-T_0/2", "T_0/2", `\\frac{2${A}t}{T_0}`]]; + pieces = [["-T_0/2", "T_0/2", String.raw`\frac{2${A}t}{T_0}`]]; break; case "half_wave_sine": - pieces = [["0", "T_0/2", `${A}\\sin(\\omega_0t)`]]; + pieces = [["0", "T_0/2", String.raw`${A}\sin(\omega_0t)`]]; break; case "full_wave_sine": - pieces = [["0", "T_0", `${A}\\sin(\\frac{\\pi t}{T_0})`]]; + pieces = [["0", "T_0", String.raw`${A}\sin(\frac{\pi t}{T_0})`]]; break; default: pieces = [ - ["-T_0/2", "0", `${A}(1+\\frac{4t}{T_0})`], - ["0", "T_0/2", `${A}(1-\\frac{4t}{T_0})`], + ["-T_0/2", "0", String.raw`${A}(1+\frac{4t}{T_0})`], + ["0", "T_0/2", String.raw`${A}(1-\frac{4t}{T_0})`], ]; } const integrals = pieces.map( /** @param piece - Interval bounds and waveform expression. @returns One integral. */ ([lower, upper, signal]): string => - `\\int_{${lower}}^{${upper}}\\left(${signal}\\right)${kernel}\\,dt`, + String.raw`\int_{${lower}}^{${upper}}\left(${signal}\right)${kernel}\,dt`, ); - return `${label}=\\frac{2}{T_0}\\left[${integrals.join("+")}\\right]`; + return String.raw`${label}=\frac{2}{T_0}\left[${integrals.join("+")}\right]`; } /** diff --git a/src/lib/math-engine/fourier-transform/engine.ts b/src/lib/math-engine/fourier-transform/engine.ts index 6ada5e95..6f5214bd 100644 --- a/src/lib/math-engine/fourier-transform/engine.ts +++ b/src/lib/math-engine/fourier-transform/engine.ts @@ -96,15 +96,15 @@ export function getCtftPairLatex( case "rect": { const T = params.T ?? 1; return { - timeLatex: `\\operatorname{rect}\\left(\\frac{t}{${T}}\\right)`, - freqLatex: `${T} \\operatorname{sinc}\\left(\\frac{${T} \\omega}{2 \\pi}\\right)`, + timeLatex: String.raw`\operatorname{rect}\left(\frac{t}{${T}}\right)`, + freqLatex: String.raw`${T} \operatorname{sinc}\left(\frac{${T} \omega}{2 \pi}\right)`, }; } case "exponential": { const a = params.a ?? 1; return { timeLatex: `e^{-${a} t} u(t)`, - freqLatex: `\\frac{1}{${a} + j\\omega}`, + freqLatex: String.raw`\frac{1}{${a} + j\omega}`, }; } case "gaussian": { @@ -116,15 +116,15 @@ export function getCtftPairLatex( } case "delta": { return { - timeLatex: "\\delta(t)", + timeLatex: String.raw`\delta(t)`, freqLatex: "1", }; } case "cos": { const w0 = params.w0 ?? 1; return { - timeLatex: `\\cos(${w0} t)`, - freqLatex: `\\pi \\delta(\\omega - ${w0}) + \\pi \\delta(\\omega + ${w0})`, + timeLatex: String.raw`\cos(${w0} t)`, + freqLatex: String.raw`\pi \delta(\omega - ${w0}) + \pi \delta(\omega + ${w0})`, }; } default: { @@ -292,15 +292,15 @@ export function createCtftProblem( solutionSteps: [ { title: "Step 1: Identify Base Transform Pair", - latex: `x_0(t) \\iff X_0(\\omega) = ${pair.freqLatex}`, + latex: String.raw`x_0(t) \iff X_0(\omega) = ${pair.freqLatex}`, }, { title: "Step 2: Apply Time-Shift Property", - latex: `x(t - t_0) \\iff X_0(\\omega) e^{-j \\omega t_0} \\quad \\text{with } t_0 = ${t0}`, + latex: String.raw`x(t - t_0) \iff X_0(\omega) e^{-j \omega t_0} \quad \text{with } t_0 = ${t0}`, }, { title: "Step 3: Combine Terms for Final CTFT", - latex: `X(\\omega) = ${shiftedFreqLatex}`, + latex: String.raw`X(\omega) = ${shiftedFreqLatex}`, }, ], }; @@ -316,11 +316,11 @@ export function createCtftProblem( solutionSteps: [ { title: "Step 1: Identify Base Signal Pair", - latex: `\\text{Recall standard CTFT transform pair: } x(t) \\iff X(\\omega)`, + latex: String.raw`\text{Recall standard CTFT transform pair: } x(t) \iff X(\omega)`, }, { title: "Step 2: Substitute Parameter Values", - latex: `X(\\omega) = \\int_{-\\infty}^{\\infty} x(t) e^{-j\\omega t} dt = ${pair.freqLatex}`, + latex: String.raw`X(\omega) = \int_{-\infty}^{\infty} x(t) e^{-j\omega t} dt = ${pair.freqLatex}`, }, ], }; diff --git a/src/lib/math-engine/fourier-transform/its-scaffolding/derivation.ts b/src/lib/math-engine/fourier-transform/its-scaffolding/derivation.ts index 334dcce9..b0d27898 100644 --- a/src/lib/math-engine/fourier-transform/its-scaffolding/derivation.ts +++ b/src/lib/math-engine/fourier-transform/its-scaffolding/derivation.ts @@ -60,7 +60,8 @@ export function buildCtftDerivation( const { T, a, w0 } = problem.params; const halfWidth = formatCtftHalfWidth(T); /** Simplified half-width frequency used in endpoint and sine prompts. */ - const halfFrequency = T === 2 ? String.raw`\omega` : `${halfWidth}\\omega`; + const halfFrequency = + T === 2 ? String.raw`\omega` : String.raw`${halfWidth}\omega`; switch (problem.signalType) { case "rect": return { diff --git a/src/lib/math-engine/fourier-transform/its-scaffolding/guidance.ts b/src/lib/math-engine/fourier-transform/its-scaffolding/guidance.ts index c31bb613..24645523 100644 --- a/src/lib/math-engine/fourier-transform/its-scaffolding/guidance.ts +++ b/src/lib/math-engine/fourier-transform/its-scaffolding/guidance.ts @@ -293,7 +293,7 @@ function inputMetadata( const labels: Record = { T: "$T =$", a: "$a =$", - w0: "$\\omega_0 =$", + w0: String.raw`$\omega_0 =$`, t0: "$t_0 =$", limit: "$X_0(0) =$", }; @@ -308,7 +308,7 @@ function inputMetadata( inputSize: compact ? "scalar" : "expression", inputLabel: labels[task.id] ?? - (task.kind === "location" ? "$\\omega =$" : "Value"), + (task.kind === "location" ? String.raw`$\omega =$` : "Value"), answerForm, }; } diff --git a/src/lib/math-engine/fourier-transform/its-scaffolding/lesson.ts b/src/lib/math-engine/fourier-transform/its-scaffolding/lesson.ts index c7095baa..58a22eab 100644 --- a/src/lib/math-engine/fourier-transform/its-scaffolding/lesson.ts +++ b/src/lib/math-engine/fourier-transform/its-scaffolding/lesson.ts @@ -275,7 +275,7 @@ export function buildCtftLesson( setup.mathChoices = true; const derivation = mode === "derivation" ? buildCtftDerivation(baseProblem) : null; - const phase = params.t0 === 0 ? "1" : `e^{${-params.t0}j\\omega}`; + const phase = params.t0 === 0 ? "1" : String.raw`e^{${-params.t0}j\omega}`; const property = part( "operation", "Choose the operational property", @@ -304,7 +304,7 @@ export function buildCtftLesson( `weight-${row}`, `Impulse ${row + 1} complex weight`, "weight", - "\\pi", + String.raw`\pi`, shift === 0 ? String.raw`Each base cosine impulse has weight $\pi$, not $1/2$ or $2\pi$.` : String.raw`Evaluate $\pi e^{-j\omega t_0}$ at this row's verified impulse location.`, diff --git a/src/lib/math-engine/fourier-transform/presentation.ts b/src/lib/math-engine/fourier-transform/presentation.ts index 9dc1adc5..06eab8be 100644 --- a/src/lib/math-engine/fourier-transform/presentation.ts +++ b/src/lib/math-engine/fourier-transform/presentation.ts @@ -104,8 +104,8 @@ export function exactCtftSolution( task.kind === "location" ? String(location) : shift === 0 - ? "\\pi" - : `\\pi e^{-j(${location})(${shift})}`; + ? String.raw`\pi` + : String.raw`\pi e^{-j(${location})(${shift})}`; } return summarizeCtftInput(task, target); } @@ -120,7 +120,7 @@ export function displayCtftInput(input: string): string { return normalizeMathLatex( normalizeTransformNotation(input, "omega"), false, - ).replace(/\\operatorname\{DiracDelta\}/g, "\\delta"); + ).replace(/\\operatorname\{DiracDelta\}/g, String.raw`\delta`); } catch { return input; } diff --git a/src/lib/math-engine/fraction.ts b/src/lib/math-engine/fraction.ts index a4c165e0..c3590493 100644 --- a/src/lib/math-engine/fraction.ts +++ b/src/lib/math-engine/fraction.ts @@ -84,7 +84,7 @@ export function toFractionLatex( return isNegative ? `-${num}` : `${num}`; } - const fracStr = `\\frac{${num}}{${den}}`; + const fracStr = String.raw`\frac{${num}}{${den}}`; return isNegative ? `-${fracStr}` : fracStr; } diff --git a/src/lib/math-engine/laplace/algebra.ts b/src/lib/math-engine/laplace/algebra.ts index fdaff50b..4eefa2ea 100644 --- a/src/lib/math-engine/laplace/algebra.ts +++ b/src/lib/math-engine/laplace/algebra.ts @@ -157,7 +157,7 @@ export function rationalLatex(value: Rational): string { ) return polynomialLatex(value.n); const negative = value.n.at(-1)!.numerator < 0n; - return `${negative ? "-" : ""}\\frac{${polynomialLatex(negative ? scale(value.n, fraction(-1)) : value.n)}}{${polynomialLatex(value.d)}}`; + return String.raw`${negative ? "-" : ""}\frac{${polynomialLatex(negative ? scale(value.n, fraction(-1)) : value.n)}}{${polynomialLatex(value.d)}}`; } /** @param rows - Square augmented matrix. @returns Exact unique solution. */ diff --git a/src/lib/math-engine/laplace/answer-entry.ts b/src/lib/math-engine/laplace/answer-entry.ts index 7aff4023..7a8abadf 100644 --- a/src/lib/math-engine/laplace/answer-entry.ts +++ b/src/lib/math-engine/laplace/answer-entry.ts @@ -56,7 +56,7 @@ export function renderLaplaceFields( ): string { return frame.replace( /\{\{([a-z0-9-]+)\}\}/g, - (_match, id: string) => values[id]?.trim() || "\\square", + (_match, id: string) => values[id]?.trim() || String.raw`\square`, ); } @@ -69,19 +69,21 @@ export function renderLaplaceFieldTask( task.fields.map((field) => { const value = values[field.id] ?? ""; if (field.entry?.kind === "degree" && value === ZERO_POLYNOMIAL) - return [field.id, "\\mathrm{undefined}"]; + return [field.id, String.raw`\mathrm{undefined}`]; if (field.entry?.kind === "boolean") return [ field.id, - value === "1" ? "\\text{Active}" : "\\text{Inactive}", + value === "1" + ? String.raw`\text{Active}` + : String.raw`\text{Inactive}`, ]; try { if (entryIssue(value, field.entry ?? { kind: "exact" })) - return [field.id, "\\square"]; + return [field.id, String.raw`\square`]; parseStrictLatex(value); return [field.id, value]; } catch { - return [field.id, "\\square"]; + return [field.id, String.raw`\square`]; } }), ); @@ -94,12 +96,12 @@ export function laplaceAnswerLabel(id: string, kind: "s" | "t"): string { "forward-final": "X(s)", "factor-numerator": "N(s)", "factor-denominator": "D(s)", - "ode-zi": "Y_{\\mathrm{ZI}}(s)", - "ode-zs": "Y_{\\mathrm{ZS}}(s)", + "ode-zi": String.raw`Y_{\mathrm{ZI}}(s)`, + "ode-zs": String.raw`Y_{\mathrm{ZS}}(s)`, "ode-total": "Y(s)", "ode-response": "y(t)", - "ode-check-zi": "y_{\\mathrm{ZI}}(t)", - "ode-check-zs": "y_{\\mathrm{ZS}}(t)", + "ode-check-zi": String.raw`y_{\mathrm{ZI}}(t)`, + "ode-check-zs": String.raw`y_{\mathrm{ZS}}(t)`, }; return labels[id] ?? (kind === "t" ? "x(t)" : "F(s)"); } diff --git a/src/lib/math-engine/laplace/construction.ts b/src/lib/math-engine/laplace/construction.ts index d03bcf97..1d699685 100644 --- a/src/lib/math-engine/laplace/construction.ts +++ b/src/lib/math-engine/laplace/construction.ts @@ -204,19 +204,19 @@ export function constructionPreview( ): string { if (draft.mode !== "finite") return draft.mode === "zero" - ? "\\text{Identically zero}" - : "\\text{No finite roots}"; + ? String.raw`\text{Identically zero}` + : String.raw`\text{No finite roots}`; /** @param value - Incomplete literal. @returns Safe exact preview or an empty slot. */ const slot = (value: string): string => entryIssue(value, { kind: "literal" }) - ? "\\square" + ? String.raw`\square` : fraction(value).toLatex(); const rows = draft.rows.map((row, index) => { const a = slot(row.first), b = slot(row.second), p = slot(row.power); if (task.kind === "roots") - return `${a}${row.kind === "quadratic" ? `\\pm j${b === "1" ? "" : b}` : ""}\\quad\\text{multiplicity }${p}`; + return String.raw`${a}${row.kind === "quadratic" ? String.raw`\pm j${b === "1" ? "" : b}` : ""}\quad\text{multiplicity }${p}`; const complete = !entryIssue(row.first, { kind: "literal" }) && (row.kind === "linear" || @@ -236,7 +236,7 @@ export function constructionPreview( : `s^2+(${a})s+${b}`; const power = p === "1" ? factor : `(${factor})^{${p}}`; if (task.kind === "template") - return `\\frac{${row.numerator === "linear" ? `A_{${index + 1}}s+B_{${index + 1}}` : `C_{${index + 1}}`}}{${power}}`; + return String.raw`\frac{${row.numerator === "linear" ? `A_{${index + 1}}s+B_{${index + 1}}` : `C_{${index + 1}}`}}{${power}}`; return p === "1" && (draft.rows.length > 1 || draft.gain !== "1") ? `(${factor})` : power; @@ -246,10 +246,10 @@ export function constructionPreview( ? draft.gain : slot(draft.gain); return task.kind === "roots" - ? rows.join(";\\quad ") || "\\square" + ? rows.join(String.raw`;\quad `) || String.raw`\square` : task.kind === "template" ? sumLatex([gain, ...rows]) - : gain === "\\square" - ? `\\square${rows.join("")}` + : gain === String.raw`\square` + ? String.raw`\square${rows.join("")}` : scaledLatex(fraction(draft.gain), rows.join("") || "1"); } diff --git a/src/lib/math-engine/laplace/its-scaffolding/elimination.ts b/src/lib/math-engine/laplace/its-scaffolding/elimination.ts index 5931337f..7188ab02 100644 --- a/src/lib/math-engine/laplace/its-scaffolding/elimination.ts +++ b/src/lib/math-engine/laplace/its-scaffolding/elimination.ts @@ -5,7 +5,7 @@ import { teaching } from "./teaching"; /** @param rows - Exact augmented rows. @param labels - Consistent unknown names. @returns Current equations for an elimination task. */ function systemLatex(rows: Poly[], labels: string[]): string { - return `\\begin{aligned}${rows.map((row) => `${labels.map((label, index) => `(${row[index]!.toLatex()})${label}`).join("+")}&=${row.at(-1)!.toLatex()}`).join("\\\\")}\\end{aligned}`; + return String.raw`\begin{aligned}${rows.map((row) => `${labels.map((label, index) => `(${row[index]!.toLatex()})${label}`).join("+")}&=${row.at(-1)!.toLatex()}`).join(String.raw`\\`)}\end{aligned}`; } /** @param initial - Independently derived augmented system. @param labels - Canonical coefficient names. @returns Checked rows for every nonidentity Gauss-Jordan operation. */ @@ -55,7 +55,7 @@ export function eliminationTasks( : `coefficient of $${labels[focus]}$`; const calculation = source === null - ? `\\frac{${previous[focus]!.toLatex()}}{${factor.toLatex()}}` + ? String.raw`\frac{${previous[focus]!.toLatex()}}{${factor.toLatex()}}` : `(${previous[focus]!.toLatex()})-(${factor.toLatex()})(${rows[source]![focus]!.toLatex()})`; const fields = next.map((value, index) => ({ id: `entry-${index}`, diff --git a/src/lib/math-engine/laplace/its-scaffolding/forward.ts b/src/lib/math-engine/laplace/its-scaffolding/forward.ts index ea5db960..7f7b24b8 100644 --- a/src/lib/math-engine/laplace/its-scaffolding/forward.ts +++ b/src/lib/math-engine/laplace/its-scaffolding/forward.ts @@ -76,7 +76,7 @@ export function blockAnalysis(blocks: TransformBlock[]): LaplaceStage { `block-${index}-copies-values`, "Count exact common copies", "Compare this block's numerator and denominator factors and count matching copies only.", - "\\text{Common copies}={{copies}}", + String.raw`\text{Common copies}={{copies}}`, [ { id: "copies", @@ -190,7 +190,7 @@ function zeroTasks( `block-${index}-zero-formula-values`, "Construct the exact quadratic roots", "Enter the signed linear coefficient, discriminant, and twice the leading coefficient from this reduced numerator.", - "s=\\frac{-({{b}})\\pm\\sqrt{ {{disc}} }}{ {{twoa}} }", + String.raw`s=\frac{-({{b}})\pm\sqrt{ {{disc}} }}{ {{twoa}} }`, [ { id: "b", diff --git a/src/lib/math-engine/laplace/its-scaffolding/inverse.ts b/src/lib/math-engine/laplace/its-scaffolding/inverse.ts index 5efa8464..2b23e16e 100644 --- a/src/lib/math-engine/laplace/its-scaffolding/inverse.ts +++ b/src/lib/math-engine/laplace/its-scaffolding/inverse.ts @@ -138,9 +138,9 @@ export function pairingStage(terms: LaplaceResponseTerm[]): LaplaceStage { fields .map( (field) => - `\\text{${field.label}}={{${field.id}}}`, + String.raw`\text{${field.label}}={{${field.id}}}`, ) - .join(",\\quad "), + .join(String.raw`,\quad `), fields, ), ...teaching( diff --git a/src/lib/math-engine/laplace/its-scaffolding/ode.ts b/src/lib/math-engine/laplace/its-scaffolding/ode.ts index 4ebde0db..35d2e48e 100644 --- a/src/lib/math-engine/laplace/its-scaffolding/ode.ts +++ b/src/lib/math-engine/laplace/its-scaffolding/ode.ts @@ -154,7 +154,7 @@ export function createOdeExercise(input: OdeExercise): LaplaceExercise { "ode-derivative-values", "Apply the first-derivative rule", "Substitute the supplied initial output into the verified rule, retaining its sign, including zero.", - "\\mathcal L_+\\{y'\\}=sY(s)-({{y0}})", + String.raw`\mathcal L_+\{y'\}=sY(s)-({{y0}})`, [ { id: "y0", @@ -181,7 +181,7 @@ export function createOdeExercise(input: OdeExercise): LaplaceExercise { "ode-second-values", "Apply the second-derivative rule", "Substitute the supplied initial output and derivative into their matching slots, retaining their signs, including zeros.", - "\\mathcal L_+\\{y''\\}=s^2Y(s)-s({{y0}})-({{dy0}})", + String.raw`\mathcal L_+\{y''\}=s^2Y(s)-s({{y0}})-({{dy0}})`, [ { id: "y0", @@ -309,7 +309,7 @@ export function createOdeExercise(input: OdeExercise): LaplaceExercise { return { spec, prompt, - conditions: `Unilateral IVP for $t\\ge0$: $y(0^-)=${y0.toLatex()}${order === 2 ? `,\\ y'(0^-)=${dy0.toLatex()}` : ""}$.`, + conditions: String.raw`Unilateral IVP for $t\ge0$: $y(0^-)=${y0.toLatex()}${order === 2 ? String.raw`,\ y'(0^-)=${dy0.toLatex()}` : ""}$.`, transform: solution.transform, response: solution.response, terms, diff --git a/src/lib/math-engine/laplace/its-scaffolding/roc.ts b/src/lib/math-engine/laplace/its-scaffolding/roc.ts index 1dacaf8c..f0a13ceb 100644 --- a/src/lib/math-engine/laplace/its-scaffolding/roc.ts +++ b/src/lib/math-engine/laplace/its-scaffolding/roc.ts @@ -108,7 +108,7 @@ export function createRocExercise(input: RationalExercise): LaplaceExercise { task( "axis", "Check the imaginary axis", - "The entire line $\\Re(s)=0$ must lie inside the ROC.", + String.raw`The entire line $\Re(s)=0$ must lie inside the ROC.`, "choice", problem.stable ? "Axis is inside the ROC" diff --git a/src/lib/math-engine/laplace/its-scaffolding/shared.ts b/src/lib/math-engine/laplace/its-scaffolding/shared.ts index bff3f985..b153fca9 100644 --- a/src/lib/math-engine/laplace/its-scaffolding/shared.ts +++ b/src/lib/math-engine/laplace/its-scaffolding/shared.ts @@ -110,7 +110,7 @@ export function rootList(factors: LaplaceFactor[]): string { ? factors .map( (factor) => - `$${factor.real}${fraction(factor.frequency).numerator !== 0n ? `\\pm j(${factor.frequency})` : ""}$ (multiplicity ${factor.multiplicity})`, + String.raw`$${factor.real}${fraction(factor.frequency).numerator !== 0n ? String.raw`\pm j(${factor.frequency})` : ""}$ (multiplicity ${factor.multiplicity})`, ) .join("; ") : "No finite roots"; @@ -146,7 +146,7 @@ export function rootTask( "A root is a value that makes a polynomial zero. Multiplicity counts factor copies. The imaginary unit satisfies $j^2=-1$; conjugate roots $a+jb$ and $a-jb$ share real part $a$ and opposite imaginary parts.", setup, first - ? `For the factor $${polynomialLatex(factorPoly(first))}$, ${fraction(first.frequency).numerator ? `complete the square to obtain $(s-(${first.real}))^2+(${first.frequency})^2=0$, giving the pair $${first.real}\\pm j(${first.frequency})$` : `subtract its constant from both sides to obtain $s=${first.real}$`}. Count its copies separately from solving its location.` + ? String.raw`For the factor $${polynomialLatex(factorPoly(first))}$, ${fraction(first.frequency).numerator ? String.raw`complete the square to obtain $(s-(${first.real}))^2+(${first.frequency})^2=0$, giving the pair $${first.real}\pm j(${first.frequency})$` : `subtract its constant from both sides to obtain $s=${first.real}$`}. Count its copies separately from solving its location.` : "A nonzero constant cannot equal zero, so it has no finite roots. This differs from the zero polynomial, which vanishes at every value.", "Check Roots", ), @@ -314,7 +314,7 @@ export function analysisStage( "degrees-values", "Compare the reduced polynomial degrees", "Enter the highest nonzero power in each reduced polynomial. For a zero numerator, choose Zero polynomial—degree undefined.", - "\\deg N={{numerator}},\\quad\\deg D={{denominator}}", + String.raw`\deg N={{numerator}},\quad\deg D={{denominator}}`, [ { id: "numerator", @@ -382,7 +382,7 @@ function divisionTeaching(data: LaplaceDecomposition) { `Compare $N(s)=${polynomialLatex(data.numerator)}$ and $D(s)=${polynomialLatex(data.denominator)}$ after cancellation.`, zero(data.numerator) ? "The numerator is zero, so the complete expression is zero. No polynomial division is needed." - : `Here $\\deg N=${n}$ and $\\deg D=${d}$. Since $${n}${n < d ? "<" : "\\ge"}${d}$, ${n < d ? "the fraction is proper and no division is needed" : `divide the leading coefficients first to obtain constant quotient $${data.quotient}$`}.`, + : String.raw`Here $\deg N=${n}$ and $\deg D=${d}$. Since $${n}${n < d ? "<" : String.raw`\ge`}${d}$, ${n < d ? "the fraction is proper and no division is needed" : `divide the leading coefficients first to obtain constant quotient $${data.quotient}$`}.`, "Check Division Decision", ); } @@ -477,7 +477,7 @@ function coefficientTasks(data: LaplaceDecomposition): LaplaceTask[] { slot.factor.real, ).toLatex(), ), - formula: `N(s)=${polynomialLatex(data.numerator)},\\quad s=${slot.factor.real}`, + formula: String.raw`N(s)=${polynomialLatex(data.numerator)},\quad s=${slot.factor.real}`, ...teaching( "For a simple pole, cover-up evaluates the numerator at the pole location after removing its factor.", `In $N(s)=${polynomialLatex(data.numerator)}$, replace every $s$ by $${slot.factor.real}$, including inside powers.`, @@ -496,7 +496,7 @@ function coefficientTasks(data: LaplaceDecomposition): LaplaceTask[] { slot.factor.real, ).toLatex(), ), - formula: `D_{\\mathrm{remaining}}(s)=${polynomialLatex(divide(data.denominator, slot.denominator)[0])},\\quad s=${slot.factor.real}`, + formula: String.raw`D_{\mathrm{remaining}}(s)=${polynomialLatex(divide(data.denominator, slot.denominator)[0])},\quad s=${slot.factor.real}`, ...teaching( "The remaining denominator is the original reduced denominator divided by the selected simple-pole factor.", `Remove $${polynomialLatex(slot.denominator)}$, then evaluate $${polynomialLatex(divide(data.denominator, slot.denominator)[0])}$ at $s=${slot.factor.real}$.`, @@ -509,7 +509,7 @@ function coefficientTasks(data: LaplaceDecomposition): LaplaceTask[] { ...task( `coefficient-${slot.label}`, `Calculate $${slot.label}$`, - `Solve the verified identity for the coefficient of $\\frac{${polynomialLatex(slot.basis)}}{${polynomialLatex(slot.denominator)}}$.`, + String.raw`Solve the verified identity for the coefficient of $\frac{${polynomialLatex(slot.basis)}}{${polynomialLatex(slot.denominator)}}$.`, "scalar", slot.value, ), @@ -603,7 +603,7 @@ export function decompositionStages( "factor-counts-values", "Classify the denominator factors", "Count linear and irreducible quadratic factor copies in the verified reduced denominator.", - "\\text{Linear copies}={{linear}},\\quad\\text{Quadratic copies}={{quadratic}}", + String.raw`\text{Linear copies}={{linear}},\quad\text{Quadratic copies}={{quadratic}}`, [ { id: "linear", @@ -762,7 +762,7 @@ function methodDegreeTasks(data: LaplaceDecomposition): LaplaceTask[] { "method-degrees-values", "Compare reduced degrees", "Enter each reduced polynomial's highest nonzero power before choosing whether to divide.", - "\\deg N={{numerator}},\\quad\\deg D={{denominator}}", + String.raw`\deg N={{numerator}},\quad\deg D={{denominator}}`, [ { id: "numerator", @@ -852,7 +852,7 @@ function methodCoefficientTasks( ...teaching( "A simple-pole residue is the evaluated numerator divided by the evaluated remaining denominator.", `Use the numerator value $${numerator}$ and remaining-denominator value $${denominator}$ checked at $s=${slot.factor.real}$. The removed pole factor must not appear in the divisor.`, - `$${slot.label}=\\frac{${numerator}}{${denominator}}=${slot.value}$. Dividing the signed values preserves the residue's sign.`, + String.raw`$${slot.label}=\frac{${numerator}}{${denominator}}=${slot.value}$. Dividing the signed values preserves the residue's sign.`, "Check Coefficient", ), }, diff --git a/src/lib/math-engine/laplace/its-scaffolding/support.ts b/src/lib/math-engine/laplace/its-scaffolding/support.ts index 9edf6dd4..885fc041 100644 --- a/src/lib/math-engine/laplace/its-scaffolding/support.ts +++ b/src/lib/math-engine/laplace/its-scaffolding/support.ts @@ -56,7 +56,7 @@ export function supportTasks( min: min === null ? null : `${min.numerator}/${min.denominator}`, max: max === null ? null : `${max.numerator}/${max.denominator}`, }; - const range = `${min?.toLatex() ?? "-\\infty"} ({ @@ -105,7 +105,7 @@ export function supportTasks( "Transform the original terms without checking a common ROC", ]), prompt: "Your checked intervals assemble the ordinary signal below. The independently verified supported representation has a common ROC; carry it into the transform pairs.", - formula: `x_{\\mathrm{regular}}(t)=\\begin{cases}${intervals.join("\\\\")}\\end{cases}`, + formula: String.raw`x_{\mathrm{regular}}(t)=\begin{cases}${intervals.join(String.raw`\\`)}\end{cases}`, ...teaching( "Linearity permits adding individual Laplace transforms where those transforms have a common region of convergence. Combining canceled tails first can expose that region.", `Use your checked interval sums, preserving these separate impulse terms: $${responseLatex(original.filter((term) => term.kind === "impulse"))}$.`, diff --git a/src/lib/math-engine/laplace/its-scaffolding/teaching.ts b/src/lib/math-engine/laplace/its-scaffolding/teaching.ts index dc63f9da..f0731e64 100644 --- a/src/lib/math-engine/laplace/its-scaffolding/teaching.ts +++ b/src/lib/math-engine/laplace/its-scaffolding/teaching.ts @@ -102,7 +102,7 @@ function initialStateTeaching( "Differentiation in time becomes multiplication by $s$, with subtracted initial-state terms in the unilateral transform.", id.includes("second") ? "Apply the first-derivative rule twice: the second application also subtracts $y'(0^-)$, while the initial output acquires a factor of $s$." - : "Use $\\mathcal L_+\\{y'\\}=sY(s)-y(0^-)$. Substitute a signed initial value inside the subtraction; enter zero explicitly.", + : String.raw`Use $\mathcal L_+\{y'\}=sY(s)-y(0^-)$. Substitute a signed initial value inside the subtraction; enter zero explicitly.`, "For example, if $y(0^-)=-2$, the first-derivative transform is $sY(s)-(-2)=sY(s)+2$. The rule subtracts the value, not its magnitude.", "Check Initial-Condition Substitution", ); @@ -256,14 +256,14 @@ function regionTeaching(id: string): Teaching | undefined { return teaching( "The ROC is the open set of complex values where the transform converges. Poles are excluded; zeros do not set its boundaries.", "Sort the distinct real parts of surviving poles. Right-sided modes require a region to their right; left-sided modes require one to their left. Intersect these requirements.", - "For poles at $-5$ and $-3$, candidate regions are $\\Re(s)<-5$, $-5<\\Re(s)<-3$, and $\\Re(s)>-3$. Finite-duration sums require checking cancellation of their infinite tails.", + String.raw`For poles at $-5$ and $-3$, candidate regions are $\Re(s)<-5$, $-5<\Re(s)<-3$, and $\Re(s)>-3$. Finite-duration sums require checking cancellation of their infinite tails.`, "Check Region of Convergence", ); if (["axis", "bibo", "stability"].includes(id)) return teaching( "BIBO stability concerns bounded inputs producing bounded outputs. For this system-analysis family, check whether the entire imaginary axis lies in the ROC.", "The imaginary axis has real part zero. Substitute zero into the strict ROC inequalities; a boundary at zero does not count as inside.", - "For example, $\\Re(s)>-3$ contains the imaginary axis, but $\\Re(s)>0$ excludes it. This establishes input-output stability, not hidden internal stability.", + String.raw`For example, $\Re(s)>-3$ contains the imaginary axis, but $\Re(s)>0$ excludes it. This establishes input-output stability, not hidden internal stability.`, "Check System Stability", ); if (id === "side" || id === "causality") @@ -341,18 +341,18 @@ export function signalFamilyChoices( ): NonNullable { const support = side === "left" ? "u(d-t)" : "u(t-d)"; return { - impulse: { label: "Impulse", math: "A\\delta(t-d)" }, + impulse: { label: "Impulse", math: String.raw`A\delta(t-d)` }, exponential: { label: "Step / polynomial exponential", math: `A(t-d)^n e^{a(t-d)}${support}`, }, cosine: { label: "Damped cosine", - math: `Ae^{a(t-d)}\\cos(\\omega(t-d))${support}`, + math: String.raw`Ae^{a(t-d)}\cos(\omega(t-d))${support}`, }, sine: { label: "Damped sine", - math: `Ae^{a(t-d)}\\sin(\\omega(t-d))${support}`, + math: String.raw`Ae^{a(t-d)}\sin(\omega(t-d))${support}`, }, }; } @@ -381,7 +381,7 @@ export function teachRoc( ? poles .map( (pole) => - `$${pole.real}${fraction(pole.frequency).numerator ? `\\pm j(${pole.frequency})` : ""}$`, + String.raw`$${pole.real}${fraction(pole.frequency).numerator ? String.raw`\pm j(${pole.frequency})` : ""}$`, ) .join(", ") : "none"; @@ -404,7 +404,7 @@ export function teachRoc( : support ? `Here the selected region has ${bounds[0] === -Infinity && bounds[1] === Infinity ? "no pole boundary, so ordinary left/right exponential classification alone is insufficient" : bounds[0] === -Infinity ? "an upper boundary, requiring left-sided ordinary modes" : bounds[1] === Infinity ? "a lower boundary, requiring right-sided ordinary modes" : "two boundaries, requiring a mixture of left- and right-sided modes"}. A causal response must additionally vanish at every negative time.` : boundary - ? `One boundary is $\\Re(s)=${boundary.real}$. The leftmost candidate region lies strictly to its left. Adjacent distinct real parts create interior strips; repeated poles or equal real parts do not create extra strips.` + ? String.raw`One boundary is $\Re(s)=${boundary.real}$. The leftmost candidate region lies strictly to its left. Adjacent distinct real parts create interior strips; repeated poles or equal real parts do not create extra strips.` : "There are no surviving poles. For a zero or impulse-only response, the entire finite complex plane is available; do not introduce boundaries from canceled factors.", ], explanation: `${stability ? "The imaginary-axis check establishes the input-output stability conclusion." : support ? "The supplied region and time support establish this classification." : "The selected region is open, excludes poles, and respects the supplied support."} ${task.answer}`, diff --git a/src/lib/math-engine/laplace/legacy.ts b/src/lib/math-engine/laplace/legacy.ts index c164039d..f1459096 100644 --- a/src/lib/math-engine/laplace/legacy.ts +++ b/src/lib/math-engine/laplace/legacy.ts @@ -201,21 +201,21 @@ export function determineStability( const isBiboStable = maxPole < 0; return { isBiboStable, - rocLatex: `\\operatorname{Re}(s) > ${maxPole}`, + rocLatex: String.raw`\operatorname{Re}(s) > ${maxPole}`, }; } case "left-sided": { const isBiboStable = minPole > 0; return { isBiboStable, - rocLatex: `\\operatorname{Re}(s) < ${minPole}`, + rocLatex: String.raw`\operatorname{Re}(s) < ${minPole}`, }; } case "two-sided": { const isBiboStable = minPole < 0 && maxPole > 0; return { isBiboStable, - rocLatex: `${minPole} < \\operatorname{Re}(s) < ${maxPole}`, + rocLatex: String.raw`${minPole} < \operatorname{Re}(s) < ${maxPole}`, }; } default: { @@ -241,12 +241,12 @@ export function getLaplacePairLatex(type: string): { case "exp": return { timeLatex: "e^{-a t} u(t)", - laplaceLatex: "\\frac{1}{s + a}", + laplaceLatex: String.raw`\frac{1}{s + a}`, }; case "step": - return { timeLatex: "u(t)", laplaceLatex: "\\frac{1}{s}" }; + return { timeLatex: "u(t)", laplaceLatex: String.raw`\frac{1}{s}` }; case "delta": - return { timeLatex: "\\delta(t)", laplaceLatex: "1" }; + return { timeLatex: String.raw`\delta(t)`, laplaceLatex: "1" }; default: throw new Error(`Unknown Laplace pair: ${type}`); } @@ -346,20 +346,20 @@ function createTrigonometricInverse(id: string): LaplaceProblem { return { id, problemType: "inverse_direct", - promptLatex: `\\text{Find } x(t) = \\mathcal{L}^{-1}\\left\\{\\frac{${A}s + ${bOmega}}{s^2 + ${wSq}}\\right\\}`, - referenceAnswerLatex: `(${A} \\cos(${omega}t) + ${B} \\sin(${omega}t)) u(t)`, + promptLatex: String.raw`\text{Find } x(t) = \mathcal{L}^{-1}\left\{\frac{${A}s + ${bOmega}}{s^2 + ${wSq}}\right\}`, + referenceAnswerLatex: String.raw`(${A} \cos(${omega}t) + ${B} \sin(${omega}t)) u(t)`, solutionSteps: [ { title: "Step 1: Separate into Cosine and Sine Terms", - latex: `X(s) = ${A} \\cdot \\frac{s}{s^2 + ${omega}^2} + ${B} \\cdot \\frac{${omega}}{s^2 + ${omega}^2}`, + latex: String.raw`X(s) = ${A} \cdot \frac{s}{s^2 + ${omega}^2} + ${B} \cdot \frac{${omega}}{s^2 + ${omega}^2}`, }, { title: "Step 2: Recall Standard Trigonometric Pairs", - latex: `\\mathcal{L}^{-1}\\left\\{\\frac{s}{s^2 + ${omega}^2}\\right\\} = \\cos(${omega}t) u(t), \\quad \\mathcal{L}^{-1}\\left\\{\\frac{${omega}}{s^2 + ${omega}^2}\\right\\} = \\sin(${omega}t) u(t)`, + latex: String.raw`\mathcal{L}^{-1}\left\{\frac{s}{s^2 + ${omega}^2}\right\} = \cos(${omega}t) u(t), \quad \mathcal{L}^{-1}\left\{\frac{${omega}}{s^2 + ${omega}^2}\right\} = \sin(${omega}t) u(t)`, }, { title: "Step 3: Combine Terms by Linearity", - latex: `x(t) = (${A} \\cos(${omega}t) + ${B} \\sin(${omega}t)) u(t)`, + latex: String.raw`x(t) = (${A} \cos(${omega}t) + ${B} \sin(${omega}t)) u(t)`, }, ], }; @@ -378,20 +378,20 @@ function createDelayedInverse(id: string): LaplaceProblem { return { id, problemType: "inverse_direct", - promptLatex: `\\text{Find } x(t) = \\mathcal{L}^{-1}\\left\\{\\frac{${A} e^{-${t0}s}}{s + ${a}}\\right\\}`, + promptLatex: String.raw`\text{Find } x(t) = \mathcal{L}^{-1}\left\{\frac{${A} e^{-${t0}s}}{s + ${a}}\right\}`, referenceAnswerLatex: `${A} e^{-${a}(t-${t0})} u(t-${t0})`, solutionSteps: [ { title: "Step 1: Identify Time-Shift Property", - latex: `\\mathcal{L}^{-1}\\{e^{-${t0}s} F(s)\\} = f(t - ${t0}) u(t - ${t0})`, + latex: String.raw`\mathcal{L}^{-1}\{e^{-${t0}s} F(s)\} = f(t - ${t0}) u(t - ${t0})`, }, { title: "Step 2: Inverse Transform of Unshifted Term", - latex: `\\mathcal{L}^{-1}\\left\\{\\frac{${A}}{s + ${a}}\\right\\} = ${A} e^{-${a}t} u(t)`, + latex: String.raw`\mathcal{L}^{-1}\left\{\frac{${A}}{s + ${a}}\right\} = ${A} e^{-${a}t} u(t)`, }, { title: "Step 3: Apply Time Shift", - latex: `x(t) = ${A} e^{-${a}(t-${t0})} u(t-${t0})`, + latex: String.raw`x(t) = ${A} e^{-${a}(t-${t0})} u(t-${t0})`, }, ], }; @@ -410,16 +410,16 @@ function createImpulseInverse(id: string): LaplaceProblem { return { id, problemType: "inverse_direct", - promptLatex: `\\text{Find } x(t) = \\mathcal{L}^{-1}\\left\\{${A} + \\frac{${B}}{s + ${a}}\\right\\}`, - referenceAnswerLatex: `${A} \\delta(t) + ${B} e^{-${a}t} u(t)`, + promptLatex: String.raw`\text{Find } x(t) = \mathcal{L}^{-1}\left\{${A} + \frac{${B}}{s + ${a}}\right\}`, + referenceAnswerLatex: String.raw`${A} \delta(t) + ${B} e^{-${a}t} u(t)`, solutionSteps: [ { title: "Step 1: Identify Impulse & Exponential Pairs", - latex: `\\mathcal{L}^{-1}\\{1\\} = \\delta(t), \\quad \\mathcal{L}^{-1}\\left\\{\\frac{1}{s + ${a}}\\right\\} = e^{-${a}t} u(t)`, + latex: String.raw`\mathcal{L}^{-1}\{1\} = \delta(t), \quad \mathcal{L}^{-1}\left\{\frac{1}{s + ${a}}\right\} = e^{-${a}t} u(t)`, }, { title: "Step 2: Combine Terms", - latex: `x(t) = ${A} \\delta(t) + ${B} e^{-${a}t} u(t)`, + latex: String.raw`x(t) = ${A} \delta(t) + ${B} e^{-${a}t} u(t)`, }, ], }; @@ -445,16 +445,16 @@ function generateForwardTransform(id: string): LaplaceProblem { return { id, problemType: "forward", - promptLatex: `\\text{Find } X(s) = \\mathcal{L}\\{x(t)\\} \\text{ for } x(t) = (${c1} e^{-${a1}t} + ${c2} e^{-${a2}t}) u(t)`, - referenceAnswerLatex: `\\frac{${b1}s + ${b0}}{s^2 + ${d1}s + ${d0}}`, + promptLatex: String.raw`\text{Find } X(s) = \mathcal{L}\{x(t)\} \text{ for } x(t) = (${c1} e^{-${a1}t} + ${c2} e^{-${a2}t}) u(t)`, + referenceAnswerLatex: String.raw`\frac{${b1}s + ${b0}}{s^2 + ${d1}s + ${d0}}`, solutionSteps: [ { title: "Step 1: Apply Exponential Transform Pair", - latex: `\\mathcal{L}\\{e^{-at} u(t)\\} = \\frac{1}{s + a} \\implies X(s) = \\frac{${c1}}{s+${a1}} + \\frac{${c2}}{s+${a2}}`, + latex: String.raw`\mathcal{L}\{e^{-at} u(t)\} = \frac{1}{s + a} \implies X(s) = \frac{${c1}}{s+${a1}} + \frac{${c2}}{s+${a2}}`, }, { title: "Step 2: Combine Terms Over Common Denominator", - latex: `X(s) = \\frac{${c1}(s+${a2}) + ${c2}(s+${a1})}{(s+${a1})(s+${a2})} = \\frac{${b1}s + ${b0}}{s^2 + ${d1}s + ${d0}}`, + latex: String.raw`X(s) = \frac{${c1}(s+${a2}) + ${c2}(s+${a1})}{(s+${a1})(s+${a2})} = \frac{${b1}s + ${b0}}{s^2 + ${d1}s + ${d0}}`, }, ], }; @@ -486,20 +486,20 @@ function generateRocProblem(id: string): LaplaceProblem { return { id, problemType: "roc_stability", - promptLatex: `\\text{Determine ROC and BIBO stability for } ${direction} \\text{ system } X(s) = \\frac{1}{(s - (${p1}))(s - (${p2}))}`, - referenceAnswerLatex: `${stability.rocLatex}, \\quad \\text{${stability.isBiboStable ? "BIBO Stable" : "Unstable"}}`, + promptLatex: String.raw`\text{Determine ROC and BIBO stability for } ${direction} \text{ system } X(s) = \frac{1}{(s - (${p1}))(s - (${p2}))}`, + referenceAnswerLatex: String.raw`${stability.rocLatex}, \quad \text{${stability.isBiboStable ? "BIBO Stable" : "Unstable"}}`, solutionSteps: [ { title: "Step 1: Identify System Poles", - latex: `D(s) = 0 \\implies p_1 = ${p1}, \\quad p_2 = ${p2}`, + latex: String.raw`D(s) = 0 \implies p_1 = ${p1}, \quad p_2 = ${p2}`, }, { title: "Step 2: Determine ROC Region", - latex: `\\text{ROC for } ${direction} \\text{ system is } ${stability.rocLatex}`, + latex: String.raw`\text{ROC for } ${direction} \text{ system is } ${stability.rocLatex}`, }, { title: "Step 3: Check Stability Criteria", - latex: `\\operatorname{Re}(s) = 0 \\text{ ${stability.isBiboStable ? "is contained in" : "is NOT contained in"} ROC } \\implies \\text{${stability.isBiboStable ? "BIBO Stable" : "Unstable"}}`, + latex: String.raw`\operatorname{Re}(s) = 0 \text{ ${stability.isBiboStable ? "is contained in" : "is NOT contained in"} ROC } \implies \text{${stability.isBiboStable ? "BIBO Stable" : "Unstable"}}`, }, ], }; diff --git a/src/lib/math-engine/laplace/pfd.ts b/src/lib/math-engine/laplace/pfd.ts index bb6587ae..f9b52100 100644 --- a/src/lib/math-engine/laplace/pfd.ts +++ b/src/lib/math-engine/laplace/pfd.ts @@ -226,7 +226,7 @@ export function decompose( n: scale(slot.basis, fractionLatex(slot.value)), d: slot.denominator, }) - : `\\frac{${slot.label}${slot.basis.length === 1 && slot.basis[0]!.numerator === slot.basis[0]!.denominator ? "" : `(${polynomialLatex(slot.basis)})`}}{${polynomialLatex(slot.denominator)}}`, + : String.raw`\frac{${slot.label}${slot.basis.length === 1 && slot.basis[0]!.numerator === slot.basis[0]!.denominator ? "" : `(${polynomialLatex(slot.basis)})`}}{${polynomialLatex(slot.denominator)}}`, ), ]); return { @@ -284,11 +284,11 @@ export function formatRoc( }; return lower === -Infinity ? upper === Infinity - ? "s\\in\\mathbb C" - : `\\operatorname{Re}(s)<${label(upper)}` + ? String.raw`s\in\mathbb C` + : String.raw`\operatorname{Re}(s)<${label(upper)}` : upper === Infinity - ? `\\operatorname{Re}(s)>${label(lower)}` - : `${label(lower)}<\\operatorname{Re}(s)<${label(upper)}`; + ? String.raw`\operatorname{Re}(s)>${label(lower)}` + : String.raw`${label(lower)}<\operatorname{Re}(s)<${label(upper)}`; } /** @param value - Nonnegative integer. @returns Exact small factorial. */ diff --git a/src/lib/math-engine/laplace/signals.ts b/src/lib/math-engine/laplace/signals.ts index 8e85e408..cd30f17d 100644 --- a/src/lib/math-engine/laplace/signals.ts +++ b/src/lib/math-engine/laplace/signals.ts @@ -101,7 +101,7 @@ function formatSignal(term: LaplaceSignalTerm, supported: boolean): string { amplitude = fractionLatex(term.amplitude); const time = shiftedTime(term.delay); if (term.kind === "impulse") - return scaledLatex(amplitude, `\\delta(${time})`); + return scaledLatex(amplitude, String.raw`\delta(${time})`); const rate = fraction(term.rate), frequency = fraction(term.frequency); const polynomial = @@ -113,7 +113,9 @@ function formatSignal(term: LaplaceSignalTerm, supported: boolean): string { : ""; const trig = term.kind === "cosine" || term.kind === "sine" - ? `\\${term.kind === "cosine" ? "cos" : "sin"}(${scaledLatex(frequency, time, !!delay.numerator)})` + ? term.kind === "cosine" + ? String.raw`\cos(${scaledLatex(frequency, time, !!delay.numerator)})` + : String.raw`\sin(${scaledLatex(frequency, time, !!delay.numerator)})` : ""; const support = term.side === "left" diff --git a/src/lib/math-engine/laplace/transform.ts b/src/lib/math-engine/laplace/transform.ts index e766563b..6ceee16c 100644 --- a/src/lib/math-engine/laplace/transform.ts +++ b/src/lib/math-engine/laplace/transform.ts @@ -138,7 +138,7 @@ export function zeroDescription(numerator: Poly): string { const discriminant = b! .multiply(b!) .add(a!.multiply(c!).multiply(fraction(-4))); - return `$s=\\frac{-(${b!.toLatex()})\\pm\\sqrt{${discriminant.toLatex()}}}{${a!.multiply(fraction(2)).toLatex()}}$`; + return String.raw`$s=\frac{-(${b!.toLatex()})\pm\sqrt{${discriminant.toLatex()}}}{${a!.multiply(fraction(2)).toLatex()}}$`; } return `The finite solutions of $${polynomialLatex(numerator)}=0$`; } diff --git a/src/lib/math-engine/odes/formatting.ts b/src/lib/math-engine/odes/formatting.ts index 2fcf0a3a..4c319f1e 100644 --- a/src/lib/math-engine/odes/formatting.ts +++ b/src/lib/math-engine/odes/formatting.ts @@ -24,7 +24,7 @@ export function formatHarmonicScalar(value: number): string { if (!Number.isFinite(value) || value === 0) return ordinary; if (ordinary !== "0" && !/[eE][+-]?\d/.test(ordinary)) return ordinary; const [mantissa, exponent] = value.toExponential().split("e"); - return `${mantissa} \\times 10^{${Number(exponent)}}`; + return String.raw`${mantissa} \times 10^{${Number(exponent)}}`; } /** @@ -76,12 +76,12 @@ export function formatHomogeneousResponse( case "complex_conjugate": { const term1 = formatSignedLinearTerm( c1, - `\\cos(${roots.im ?? 0}t)`, + String.raw`\cos(${roots.im ?? 0}t)`, true, ); const term2 = formatSignedLinearTerm( c2, - `\\sin(${roots.im ?? 0}t)`, + String.raw`\sin(${roots.im ?? 0}t)`, false, ); const expTerm = roots.r1 !== 0 ? formatExpTerm(roots.r1) : ""; diff --git a/src/lib/math-engine/odes/its-scaffolding/step5-coefficients.ts b/src/lib/math-engine/odes/its-scaffolding/step5-coefficients.ts index effa4f3e..66b2fd2b 100644 --- a/src/lib/math-engine/odes/its-scaffolding/step5-coefficients.ts +++ b/src/lib/math-engine/odes/its-scaffolding/step5-coefficients.ts @@ -258,7 +258,7 @@ function formatCoefficientSystem(equation: TrialTerm[]): string { } return equations.length === 1 ? equations.join("") - : `\\begin{cases} ${equations.join(" \\\\ ")} \\end{cases}`; + : String.raw`\begin{cases} ${equations.join(String.raw` \\ `)} \end{cases}`; } /** @@ -361,7 +361,7 @@ export function buildStep5Data(params: BuildStep5Params): OdeItsStep5 { } = context; const systemLatex = formatCoefficientSystem(equation); const firstDerivLatex = `y_p'(t) = ${formatTrial(first, rate, frequency)}`; - const substitutionLatex = `${resolvedOrder === 2 ? `${toFractionLatex(a2)}\\left(${formatTrial(second, rate, frequency)}\\right) + ` : ""}${toFractionLatex(a1)}\\left(${formatTrial(first, rate, frequency)}\\right) + ${toFractionLatex(a0)}\\left(${formatTrial(trial, rate, frequency)}\\right) = ${forcing.latex}`; + const substitutionLatex = String.raw`${resolvedOrder === 2 ? String.raw`${toFractionLatex(a2)}\left(${formatTrial(second, rate, frequency)}\right) + ` : ""}${toFractionLatex(a1)}\left(${formatTrial(first, rate, frequency)}\right) + ${toFractionLatex(a0)}\left(${formatTrial(trial, rate, frequency)}\right) = ${forcing.latex}`; const secondDerivLatex = `y_p''(t) = ${formatTrial(second, rate, frequency)}`; const firstDerivativeOptions = shuffleWithRandom( derivativeChoices(first, rate, frequency, 1, trial), @@ -374,7 +374,7 @@ export function buildStep5Data(params: BuildStep5Params): OdeItsStep5 { const systemOptions = buildSystemChoices(context); const solved = forcing.type === "sinusoid" - ? `$A = ${toFractionLatex(particular.coeffs.A ?? 0)}, \\quad B = ${toFractionLatex(particular.coeffs.B ?? 0)}$.` + ? String.raw`$A = ${toFractionLatex(particular.coeffs.A ?? 0)}, \quad B = ${toFractionLatex(particular.coeffs.B ?? 0)}$.` : `$K_p = ${toFractionLatex(particular.coeffs.Kp ?? 0)}$.`; const derivativeHint = power > 0 @@ -393,7 +393,7 @@ export function buildStep5Data(params: BuildStep5Params): OdeItsStep5 { derivativesLatex: resolvedOrder === 1 ? firstDerivLatex - : `${firstDerivLatex}, \\quad ${secondDerivLatex}`, + : String.raw`${firstDerivLatex}, \quad ${secondDerivLatex}`, systemLatex, substitutionLatex, hints: [ diff --git a/src/lib/math-engine/odes/its-scaffolding/step7-decomposition.ts b/src/lib/math-engine/odes/its-scaffolding/step7-decomposition.ts index 9b29bd62..67cf8880 100644 --- a/src/lib/math-engine/odes/its-scaffolding/step7-decomposition.ts +++ b/src/lib/math-engine/odes/its-scaffolding/step7-decomposition.ts @@ -84,7 +84,7 @@ export const CONCEPT_QUESTIONS_POOL: OdeItsConceptQuestion[] = [ "By definition, the Zero-Input response $y_{ZI}(t)$ depends linearly on the initial state. When $y(0^-)=0$ and $y'(0^-)=0$, $y_{ZI}(t) = 0$, so $y(t) = y_{ZI}(t) + y_{ZS}(t) = y_{ZS}(t)$.", }, { - prompt: "For a stable system with characteristic roots $\\operatorname{Re}(r_i) < 0$, what happens to the transient response $y_{tr}(t)$ as $t \\to \\infty$?", + prompt: String.raw`For a stable system with characteristic roots $\operatorname{Re}(r_i) < 0$, what happens to the transient response $y_{tr}(t)$ as $t \to \infty$?`, options: [ { id: "cq3_opt1", @@ -272,7 +272,7 @@ function buildResponseChoices(params: BuildStep7Params) { A: particularScale * (particular.coeffs.A ?? 0), B: particularScale * (particular.coeffs.B ?? 0), }); - const firstBasis = `${formatExpTerm(roots.r1)}${resolvedOrder === 2 && resolvedRootType === "complex_conjugate" ? ` \\cos(${roots.im ?? 1}t)` : ""}`; + const firstBasis = `${formatExpTerm(roots.r1)}${resolvedOrder === 2 && resolvedRootType === "complex_conjugate" ? String.raw` \cos(${roots.im ?? 1}t)` : ""}`; // The legacy array names retain compatibility; the mode defines their meaning. const transientOptions: OdeItsOption[] = [ { diff --git a/src/lib/math-engine/odes/its-scaffolding/trial-algebra.ts b/src/lib/math-engine/odes/its-scaffolding/trial-algebra.ts index cd32c81d..ccb01b17 100644 --- a/src/lib/math-engine/odes/its-scaffolding/trial-algebra.ts +++ b/src/lib/math-engine/odes/its-scaffolding/trial-algebra.ts @@ -118,7 +118,9 @@ export function formatTrial( ? rate === 0 ? "" : formatExpTerm(rate) - : `\\${term.harmonic}(${toFractionLatex(frequency)}t)`; + : term.harmonic === "cos" + ? String.raw`\cos(${toFractionLatex(frequency)}t)` + : String.raw`\sin(${toFractionLatex(frequency)}t)`; const symbol = term.symbol === "input" ? "" : term.symbol; fragments.push( formatSignedLinearTerm( diff --git a/src/lib/math-engine/odes/solver.ts b/src/lib/math-engine/odes/solver.ts index 2f8a3c1e..5e576226 100644 --- a/src/lib/math-engine/odes/solver.ts +++ b/src/lib/math-engine/odes/solver.ts @@ -393,13 +393,12 @@ function computeSinusoidalParticular( ); if (multiplicity === 1) { return { - formDescription: - "y_p(t) = t[A \\cos(\\omega t) + B \\sin(\\omega t)]", + formDescription: String.raw`y_p(t) = t[A \cos(\omega t) + B \sin(\omega t)]`, latex: sanitizeLatexMath( formatSignedLinearTerm( formatHarmonicScalar(B), - `t \\sin(${frequencyLatex}t)`, + String.raw`t \sin(${frequencyLatex}t)`, true, ), ) || "0", @@ -416,15 +415,15 @@ function computeSinusoidalParticular( const latexB = formatHarmonicScalar(B); let latexStr = ""; - if (A !== 0) latexStr += `${latexA} \\cos(${frequencyLatex}t)`; + if (A !== 0) latexStr += String.raw`${latexA} \cos(${frequencyLatex}t)`; if (B > 0) - latexStr += `${latexStr ? " + " : ""}${latexB} \\sin(${frequencyLatex}t)`; + latexStr += String.raw`${latexStr ? " + " : ""}${latexB} \sin(${frequencyLatex}t)`; else if (B < 0) - latexStr += `${latexStr ? " - " : "-"}${formatHarmonicScalar(Math.abs(B))} \\sin(${frequencyLatex}t)`; + latexStr += String.raw`${latexStr ? " - " : "-"}${formatHarmonicScalar(Math.abs(B))} \sin(${frequencyLatex}t)`; if (!latexStr) latexStr = "0"; return { - formDescription: "y_p(t) = A \\cos(\\omega t) + B \\sin(\\omega t)", + formDescription: String.raw`y_p(t) = A \cos(\omega t) + B \sin(\omega t)`, latex: latexStr, /** @param t - Evaluation time. @returns Harmonic particular response. */ eval: (t: number) => evaluateHarmonic(A, B, w, t), @@ -544,12 +543,12 @@ export function solveHomogeneousConstants( const cosTerm = formatSignedLinearTerm( c1Str, - `\\cos(${toFractionLatex(omega_d)}t)`, + String.raw`\cos(${toFractionLatex(omega_d)}t)`, true, ); const sinTerm = formatSignedLinearTerm( c2Str, - `\\sin(${toFractionLatex(omega_d)}t)`, + String.raw`\sin(${toFractionLatex(omega_d)}t)`, false, ); const inner = `${cosTerm} ${sinTerm}`.trim(); diff --git a/src/lib/math-engine/real-evaluation.ts b/src/lib/math-engine/real-evaluation.ts index 48ee07c2..47b7b43b 100644 --- a/src/lib/math-engine/real-evaluation.ts +++ b/src/lib/math-engine/real-evaluation.ts @@ -13,7 +13,7 @@ type Operation = (args: unknown[], vars: Bindings) => number | null; * @returns Assigned value, known constant, or null. */ function resolveSymbol(symbol: string, vars: Bindings): number | null { - if (["Pi", "pi", "\\pi"].includes(symbol)) return Math.PI; + if (["Pi", "pi", String.raw`\pi`].includes(symbol)) return Math.PI; if (["ExponentialE", "e"].includes(symbol)) return Math.E; return symbol in vars ? (vars[symbol] ?? null) : null; } diff --git a/src/lib/math-engine/transform-notation.ts b/src/lib/math-engine/transform-notation.ts index 3a393b26..294400d8 100644 --- a/src/lib/math-engine/transform-notation.ts +++ b/src/lib/math-engine/transform-notation.ts @@ -77,12 +77,12 @@ function normalizeGroups(source: string): string { let previous = ""; for (let index = 0; index < tokens.length; index++) { const token = tokens[index]!; - if (token === "\\left" || token === "\\right") { + if (token === String.raw`\left` || token === String.raw`\right`) { index = sizedDelimiter(tokens, index + 1); output.push( groupToken( tokens[index]!, - token === "\\right", + token === String.raw`\right`, true, false, stack, @@ -94,7 +94,7 @@ function normalizeGroups(source: string): string { token, ")]}".includes(token), false, - token === "[" && previous === "\\sqrt", + token === "[" && previous === String.raw`\sqrt`, stack, ), ); @@ -163,11 +163,14 @@ export function normalizeTransformNotation( "Enter one expression or use the problem's supported equation prefix.", ); return expression - .replace(/π/g, "\\pi ") - .replace(/\\delta\b/g, "\\operatorname{DiracDelta}") - .replace(/(^|[^a-zA-Z\\])sinc(?=\s*\()/g, "$1\\operatorname{sinc}") - .replace(/(^|[^a-zA-Z\\])([ij])(?:omega|w)\b/g, "$1$2\\omega") - .replace(/(^|[^a-zA-Z\\])omega\b/g, "$1\\omega") - .replace(/(^|[^a-zA-Z\\])w\b/g, "$1\\omega") + .replace(/π/g, String.raw`\pi `) + .replace(/\\delta\b/g, String.raw`\operatorname{DiracDelta}`) + .replace( + /(^|[^a-zA-Z\\])sinc(?=\s*\()/g, + String.raw`$1\operatorname{sinc}`, + ) + .replace(/(^|[^a-zA-Z\\])([ij])(?:omega|w)\b/g, String.raw`$1$2\omega`) + .replace(/(^|[^a-zA-Z\\])omega\b/g, String.raw`$1\omega`) + .replace(/(^|[^a-zA-Z\\])w\b/g, String.raw`$1\omega`) .trim(); } diff --git a/src/lib/problems/bank/circuits-bank.ts b/src/lib/problems/bank/circuits-bank.ts index 182cceff..1bbc7a35 100644 --- a/src/lib/problems/bank/circuits-bank.ts +++ b/src/lib/problems/bank/circuits-bank.ts @@ -12,17 +12,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-1", components: { R: 20, L: 2, C: 0.05 }, topology: "series-rlc", - promptLatex: - "\\text{Derive } H(s) = \\frac{V_R(s)}{V_{in}(s)} \\text{ for Series RLC with } R = 20\\Omega, L = 2\\text{H}, C = 0.05\\text{F}", - referenceAnswerLatex: "\\frac{10 s}{s^2 + 10 s + 10}", + promptLatex: String.raw`\text{Derive } H(s) = \frac{V_R(s)}{V_{in}(s)} \text{ for Series RLC with } R = 20\Omega, L = 2\text{H}, C = 0.05\text{F}`, + referenceAnswerLatex: String.raw`\frac{10 s}{s^2 + 10 s + 10}`, solutionSteps: [ { title: "Step 1: Impedance Voltage Divider", - latex: "H(s) = \\frac{R}{sL + R + \\frac{1}{sC}} = \\frac{\\frac{R}{L} s}{s^2 + \\frac{R}{L} s + \\frac{1}{LC}}", + latex: String.raw`H(s) = \frac{R}{sL + R + \frac{1}{sC}} = \frac{\frac{R}{L} s}{s^2 + \frac{R}{L} s + \frac{1}{LC}}`, }, { title: "Step 2: Plug in Values", - latex: "\\frac{R}{L} = 10, \\quad \\omega_0^2 = \\frac{1}{2 \\times 0.05} = 10 \\implies H(s) = \\frac{10s}{s^2 + 10s + 10}", + latex: String.raw`\frac{R}{L} = 10, \quad \omega_0^2 = \frac{1}{2 \times 0.05} = 10 \implies H(s) = \frac{10s}{s^2 + 10s + 10}`, }, ], }, @@ -30,17 +29,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-2", components: { R: 4, L: 1, C: 0.25 }, topology: "series-rlc", - promptLatex: - "\\text{Find } H(s) \\text{ for Series RLC Bandpass filter with } R = 4\\Omega, L = 1\\text{H}, C = 0.25\\text{F}", - referenceAnswerLatex: "\\frac{4 s}{s^2 + 4 s + 4}", + promptLatex: String.raw`\text{Find } H(s) \text{ for Series RLC Bandpass filter with } R = 4\Omega, L = 1\text{H}, C = 0.25\text{F}`, + referenceAnswerLatex: String.raw`\frac{4 s}{s^2 + 4 s + 4}`, solutionSteps: [ { title: "Step 1: Apply Transfer Function Formula", - latex: "H(s) = \\frac{\\frac{R}{L} s}{s^2 + \\frac{R}{L} s + \\frac{1}{LC}}", + latex: String.raw`H(s) = \frac{\frac{R}{L} s}{s^2 + \frac{R}{L} s + \frac{1}{LC}}`, }, { title: "Step 2: Calculate Parameters", - latex: "\\frac{R}{L} = 4, \\quad \\frac{1}{LC} = 4 \\implies H(s) = \\frac{4s}{s^2 + 4s + 4}", + latex: String.raw`\frac{R}{L} = 4, \quad \frac{1}{LC} = 4 \implies H(s) = \frac{4s}{s^2 + 4s + 4}`, }, ], }, @@ -50,17 +48,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-3", components: { R: 5, L: 2, C: 0.1 }, topology: "parallel-rlc", - promptLatex: - "\\text{Derive } H(s) = \\frac{I_R(s)}{I_{in}(s)} \\text{ for Parallel RLC with } R = 5\\Omega, L = 2\\text{H}, C = 0.1\\text{F}", - referenceAnswerLatex: "\\frac{2 s}{s^2 + 2 s + 5}", + promptLatex: String.raw`\text{Derive } H(s) = \frac{I_R(s)}{I_{in}(s)} \text{ for Parallel RLC with } R = 5\Omega, L = 2\text{H}, C = 0.1\text{F}`, + referenceAnswerLatex: String.raw`\frac{2 s}{s^2 + 2 s + 5}`, solutionSteps: [ { title: "Step 1: Admittance Division", - latex: "H(s) = \\frac{\\frac{1}{R}}{\\frac{1}{R} + \\frac{1}{sL} + sC} = \\frac{\\frac{1}{RC} s}{s^2 + \\frac{1}{RC} s + \\frac{1}{LC}}", + latex: String.raw`H(s) = \frac{\frac{1}{R}}{\frac{1}{R} + \frac{1}{sL} + sC} = \frac{\frac{1}{RC} s}{s^2 + \frac{1}{RC} s + \frac{1}{LC}}`, }, { title: "Step 2: Plug in Values", - latex: "\\frac{1}{RC} = \\frac{1}{0.5} = 2, \\quad \\frac{1}{LC} = 5 \\implies H(s) = \\frac{2s}{s^2 + 2s + 5}", + latex: String.raw`\frac{1}{RC} = \frac{1}{0.5} = 2, \quad \frac{1}{LC} = 5 \implies H(s) = \frac{2s}{s^2 + 2s + 5}`, }, ], }, @@ -68,17 +65,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-4", components: { R: 10, L: 1, C: 0.05 }, topology: "parallel-rlc", - promptLatex: - "\\text{Find } H(s) \\text{ for Parallel RLC filter with } R = 10\\Omega, L = 1\\text{H}, C = 0.05\\text{F}", - referenceAnswerLatex: "\\frac{2 s}{s^2 + 2 s + 20}", + promptLatex: String.raw`\text{Find } H(s) \text{ for Parallel RLC filter with } R = 10\Omega, L = 1\text{H}, C = 0.05\text{F}`, + referenceAnswerLatex: String.raw`\frac{2 s}{s^2 + 2 s + 20}`, solutionSteps: [ { title: "Step 1: Apply Parallel RLC Formula", - latex: "H(s) = \\frac{\\frac{1}{RC} s}{s^2 + \\frac{1}{RC} s + \\frac{1}{LC}}", + latex: String.raw`H(s) = \frac{\frac{1}{RC} s}{s^2 + \frac{1}{RC} s + \frac{1}{LC}}`, }, { title: "Step 2: Calculate Coefficients", - latex: "\\frac{1}{RC} = 2, \\quad \\frac{1}{LC} = 20 \\implies H(s) = \\frac{2s}{s^2 + 2s + 20}", + latex: String.raw`\frac{1}{RC} = 2, \quad \frac{1}{LC} = 20 \implies H(s) = \frac{2s}{s^2 + 2s + 20}`, }, ], }, @@ -88,17 +84,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-5", components: { R: 10, L: 1, C: 0.01 }, topology: "parallel-lc-series-r", - promptLatex: - "\\text{Find } H(s) \\text{ for Notch Filter with } R = 10\\Omega, L = 1\\text{H}, C = 0.01\\text{F}", - referenceAnswerLatex: "\\frac{s^2 + 100}{s^2 + 10 s + 100}", + promptLatex: String.raw`\text{Find } H(s) \text{ for Notch Filter with } R = 10\Omega, L = 1\text{H}, C = 0.01\text{F}`, + referenceAnswerLatex: String.raw`\frac{s^2 + 100}{s^2 + 10 s + 100}`, solutionSteps: [ { title: "Step 1: Derive Notch Transfer Function", - latex: "H(s) = \\frac{s^2 + \\omega_0^2}{s^2 + \\frac{1}{RC} s + \\omega_0^2}", + latex: String.raw`H(s) = \frac{s^2 + \omega_0^2}{s^2 + \frac{1}{RC} s + \omega_0^2}`, }, { title: "Step 2: Calculate Corner Frequencies", - latex: "\\omega_0^2 = \\frac{1}{LC} = 100, \\quad \\frac{1}{RC} = 10 \\implies H(s) = \\frac{s^2 + 100}{s^2 + 10s + 100}", + latex: String.raw`\omega_0^2 = \frac{1}{LC} = 100, \quad \frac{1}{RC} = 10 \implies H(s) = \frac{s^2 + 100}{s^2 + 10s + 100}`, }, ], }, @@ -106,17 +101,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-6", components: { R: 5, L: 2, C: 0.02 }, topology: "parallel-lc-series-r", - promptLatex: - "\\text{Find } H(s) \\text{ for Notch Filter with } R = 5\\Omega, L = 2\\text{H}, C = 0.02\\text{F}", - referenceAnswerLatex: "\\frac{s^2 + 25}{s^2 + 10 s + 25}", + promptLatex: String.raw`\text{Find } H(s) \text{ for Notch Filter with } R = 5\Omega, L = 2\text{H}, C = 0.02\text{F}`, + referenceAnswerLatex: String.raw`\frac{s^2 + 25}{s^2 + 10 s + 25}`, solutionSteps: [ { title: "Step 1: Apply Notch Transfer Function", - latex: "H(s) = \\frac{s^2 + \\frac{1}{LC}}{s^2 + \\frac{1}{RC} s + \\frac{1}{LC}}", + latex: String.raw`H(s) = \frac{s^2 + \frac{1}{LC}}{s^2 + \frac{1}{RC} s + \frac{1}{LC}}`, }, { title: "Step 2: Substitute Values", - latex: "\\frac{1}{LC} = 25, \\quad \\frac{1}{RC} = 10 \\implies H(s) = \\frac{s^2 + 25}{s^2 + 10s + 25}", + latex: String.raw`\frac{1}{LC} = 25, \quad \frac{1}{RC} = 10 \implies H(s) = \frac{s^2 + 25}{s^2 + 10s + 25}`, }, ], }, @@ -126,17 +120,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-7", components: { R: 10, L: 1, C: 0.01 }, topology: "parallel-rc-series-l", - promptLatex: - "\\text{Find } H(s) \\text{ for Parallel RC in Series with L with } R = 10\\Omega, L = 1\\text{H}, C = 0.01\\text{F}", - referenceAnswerLatex: "\\frac{s^2 + 10 s}{s^2 + 10 s + 100}", + promptLatex: String.raw`\text{Find } H(s) \text{ for Parallel RC in Series with L with } R = 10\Omega, L = 1\text{H}, C = 0.01\text{F}`, + referenceAnswerLatex: String.raw`\frac{s^2 + 10 s}{s^2 + 10 s + 100}`, solutionSteps: [ { title: "Step 1: Impedance Derivation", - latex: "H(s) = \\frac{s^2 + \\frac{1}{RC} s}{s^2 + \\frac{1}{RC} s + \\frac{1}{LC}}", + latex: String.raw`H(s) = \frac{s^2 + \frac{1}{RC} s}{s^2 + \frac{1}{RC} s + \frac{1}{LC}}`, }, { title: "Step 2: Substitute Parameters", - latex: "\\frac{1}{RC} = 10, \\quad \\frac{1}{LC} = 100 \\implies H(s) = \\frac{s^2 + 10s}{s^2 + 10s + 100}", + latex: String.raw`\frac{1}{RC} = 10, \quad \frac{1}{LC} = 100 \implies H(s) = \frac{s^2 + 10s}{s^2 + 10s + 100}`, }, ], }, @@ -144,17 +137,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-8", components: { R: 20, L: 2, C: 0.025 }, topology: "parallel-rc-series-l", - promptLatex: - "\\text{Find } H(s) \\text{ for Parallel RC in Series with L with } R = 20\\Omega, L = 2\\text{H}, C = 0.025\\text{F}", - referenceAnswerLatex: "\\frac{s^2 + 2 s}{s^2 + 2 s + 20}", + promptLatex: String.raw`\text{Find } H(s) \text{ for Parallel RC in Series with L with } R = 20\Omega, L = 2\text{H}, C = 0.025\text{F}`, + referenceAnswerLatex: String.raw`\frac{s^2 + 2 s}{s^2 + 2 s + 20}`, solutionSteps: [ { title: "Step 1: Impedance Derivation", - latex: "H(s) = \\frac{s^2 + \\frac{1}{RC} s}{s^2 + \\frac{1}{RC} s + \\frac{1}{LC}}", + latex: String.raw`H(s) = \frac{s^2 + \frac{1}{RC} s}{s^2 + \frac{1}{RC} s + \frac{1}{LC}}`, }, { title: "Step 2: Substitute Parameters", - latex: "\\frac{1}{RC} = 2, \\quad \\frac{1}{LC} = 20 \\implies H(s) = \\frac{s^2 + 2s}{s^2 + 2s + 20}", + latex: String.raw`\frac{1}{RC} = 2, \quad \frac{1}{LC} = 20 \implies H(s) = \frac{s^2 + 2s}{s^2 + 2s + 20}`, }, ], }, @@ -164,17 +156,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-9", components: { R: 1000, L: 1, C: 0.000001 }, topology: "rc-lpf", - promptLatex: - "\\text{Derive 1st-order RC LPF transfer function with } R = 1\\text{k}\\Omega, C = 1\\mu\\text{F}", - referenceAnswerLatex: "\\frac{1000}{s + 1000}", + promptLatex: String.raw`\text{Derive 1st-order RC LPF transfer function with } R = 1\text{k}\Omega, C = 1\mu\text{F}`, + referenceAnswerLatex: String.raw`\frac{1000}{s + 1000}`, solutionSteps: [ { title: "Step 1: Voltage Divider Formula", - latex: "H(s) = \\frac{\\frac{1}{sC}}{R + \\frac{1}{sC}} = \\frac{1}{1 + s R C} = \\frac{\\frac{1}{RC}}{s + \\frac{1}{RC}}", + latex: String.raw`H(s) = \frac{\frac{1}{sC}}{R + \frac{1}{sC}} = \frac{1}{1 + s R C} = \frac{\frac{1}{RC}}{s + \frac{1}{RC}}`, }, { title: "Step 2: Calculate Corner Frequency w_c", - latex: "\\omega_c = \\frac{1}{RC} = \\frac{1}{1000 \\times 10^{-6}} = 1000 \\text{ rad/s} \\implies H(s) = \\frac{1000}{s + 1000}", + latex: String.raw`\omega_c = \frac{1}{RC} = \frac{1}{1000 \times 10^{-6}} = 1000 \text{ rad/s} \implies H(s) = \frac{1000}{s + 1000}`, }, ], }, @@ -182,17 +173,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-10", components: { R: 500, L: 1, C: 0.000002 }, topology: "rc-lpf", - promptLatex: - "\\text{Find 3dB corner frequency } \\omega_c \\text{ for RC LPF with } R = 500\\Omega, C = 2\\mu\\text{F}", - referenceAnswerLatex: "\\omega_c = 1000 \\text{ rad/s}", + promptLatex: String.raw`\text{Find 3dB corner frequency } \omega_c \text{ for RC LPF with } R = 500\Omega, C = 2\mu\text{F}`, + referenceAnswerLatex: String.raw`\omega_c = 1000 \text{ rad/s}`, solutionSteps: [ { title: "Step 1: Corner Frequency Formula", - latex: "\\omega_c = \\frac{1}{R C}", + latex: String.raw`\omega_c = \frac{1}{R C}`, }, { title: "Step 2: Plug in Values", - latex: "\\omega_c = \\frac{1}{500 \\times 2 \\times 10^{-6}} = 1000 \\text{ rad/s}", + latex: String.raw`\omega_c = \frac{1}{500 \times 2 \times 10^{-6}} = 1000 \text{ rad/s}`, }, ], }, @@ -202,17 +192,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-11", components: { R: 100, L: 1, C: 0.0001 }, topology: "active-sallen-key", - promptLatex: - "\\text{Derive 2nd-Order Sallen-Key LPF transfer function with } R = 100\\Omega, C = 100\\mu\\text{F}", - referenceAnswerLatex: "\\frac{10000}{s^2 + 200 s + 10000}", + promptLatex: String.raw`\text{Derive 2nd-Order Sallen-Key LPF transfer function with } R = 100\Omega, C = 100\mu\text{F}`, + referenceAnswerLatex: String.raw`\frac{10000}{s^2 + 200 s + 10000}`, solutionSteps: [ { title: "Step 1: Sallen-Key Transfer Function Formula", - latex: "H(s) = \\frac{\\omega_c^2}{s^2 + 2 \\omega_c s + \\omega_c^2}", + latex: String.raw`H(s) = \frac{\omega_c^2}{s^2 + 2 \omega_c s + \omega_c^2}`, }, { title: "Step 2: Calculate Corner Frequency w_c", - latex: "\\omega_c = \\frac{1}{RC} = 100 \\text{ rad/s} \\implies \\omega_c^2 = 10000 \\implies H(s) = \\frac{10000}{s^2 + 200s + 10000}", + latex: String.raw`\omega_c = \frac{1}{RC} = 100 \text{ rad/s} \implies \omega_c^2 = 10000 \implies H(s) = \frac{10000}{s^2 + 200s + 10000}`, }, ], }, @@ -220,17 +209,16 @@ export const CIRCUITS_EXAM_BANK: CircuitProblem[] = [ id: "circuits-bank-12", components: { R: 50, L: 1, C: 0.0004 }, topology: "active-sallen-key", - promptLatex: - "\\text{Derive 2nd-Order Sallen-Key LPF with } R = 50\\Omega, C = 400\\mu\\text{F}", - referenceAnswerLatex: "\\frac{2500}{s^2 + 100 s + 2500}", + promptLatex: String.raw`\text{Derive 2nd-Order Sallen-Key LPF with } R = 50\Omega, C = 400\mu\text{F}`, + referenceAnswerLatex: String.raw`\frac{2500}{s^2 + 100 s + 2500}`, solutionSteps: [ { title: "Step 1: Calculate Corner Frequency w_c", - latex: "\\omega_c = \\frac{1}{50 \\times 400 \\times 10^{-6}} = 50 \\text{ rad/s}", + latex: String.raw`\omega_c = \frac{1}{50 \times 400 \times 10^{-6}} = 50 \text{ rad/s}`, }, { title: "Step 2: Form Transfer Function", - latex: "\\omega_c^2 = 2500, \\quad 2\\omega_c = 100 \\implies H(s) = \\frac{2500}{s^2 + 100s + 2500}", + latex: String.raw`\omega_c^2 = 2500, \quad 2\omega_c = 100 \implies H(s) = \frac{2500}{s^2 + 100s + 2500}`, }, ], }, diff --git a/src/lib/problems/bank/fourier-transform-bank.ts b/src/lib/problems/bank/fourier-transform-bank.ts index f1366991..bab0fe87 100644 --- a/src/lib/problems/bank/fourier-transform-bank.ts +++ b/src/lib/problems/bank/fourier-transform-bank.ts @@ -10,58 +10,54 @@ import type { CtftProblem } from "$lib/math-engine/fourier-transform/index"; export const CTFT_EXAM_BANK: CtftProblem[] = [ { id: "ctft-bank-1", - promptLatex: - "\\text{Calculate the CTFT } X(\\omega) \\text{ of } x(t) = \\operatorname{rect}\\left(\\frac{t - 3}{4}\\right)", - referenceAnswerLatex: - "4 \\operatorname{sinc}\\left(\\frac{2 \\omega}{\\pi}\\right) e^{-j 3 \\omega}", + promptLatex: String.raw`\text{Calculate the CTFT } X(\omega) \text{ of } x(t) = \operatorname{rect}\left(\frac{t - 3}{4}\right)`, + referenceAnswerLatex: String.raw`4 \operatorname{sinc}\left(\frac{2 \omega}{\pi}\right) e^{-j 3 \omega}`, solutionSteps: [ { title: "Step 1: Identify Base Rectangular Transform Pair", - latex: "\\operatorname{rect}\\left(\\frac{t}{T}\\right) \\iff T \\operatorname{sinc}\\left(\\frac{T \\omega}{2 \\pi}\\right)", + latex: String.raw`\operatorname{rect}\left(\frac{t}{T}\right) \iff T \operatorname{sinc}\left(\frac{T \omega}{2 \pi}\right)`, }, { title: "Step 2: Substitute Parameter T = 4", - latex: "\\operatorname{rect}\\left(\\frac{t}{4}\\right) \\iff 4 \\operatorname{sinc}\\left(\\frac{4 \\omega}{2 \\pi}\\right) = 4 \\operatorname{sinc}\\left(\\frac{2 \\omega}{\\pi}\\right)", + latex: String.raw`\operatorname{rect}\left(\frac{t}{4}\right) \iff 4 \operatorname{sinc}\left(\frac{4 \omega}{2 \pi}\right) = 4 \operatorname{sinc}\left(\frac{2 \omega}{\pi}\right)`, }, { title: "Step 3: Apply Time Shift Property", - latex: "x(t - t_0) \\iff X(\\omega) e^{-j \\omega t_0} \\implies 4 \\operatorname{sinc}\\left(\\frac{2 \\omega}{\\pi}\\right) e^{-j 3 \\omega}", + latex: String.raw`x(t - t_0) \iff X(\omega) e^{-j \omega t_0} \implies 4 \operatorname{sinc}\left(\frac{2 \omega}{\pi}\right) e^{-j 3 \omega}`, }, ], }, { id: "ctft-bank-2", - promptLatex: - "\\text{Find the inverse CTFT } x(t) \\text{ of } X(\\omega) = \\frac{1}{4 + j\\omega} e^{-j 2 \\omega}", + promptLatex: String.raw`\text{Find the inverse CTFT } x(t) \text{ of } X(\omega) = \frac{1}{4 + j\omega} e^{-j 2 \omega}`, referenceAnswerLatex: "e^{-4 (t - 2)} u(t - 2)", solutionSteps: [ { title: "Step 1: Recall One-Sided Exponential Pair", - latex: "e^{-a t} u(t) \\iff \\frac{1}{a + j\\omega} \\implies a = 4", + latex: String.raw`e^{-a t} u(t) \iff \frac{1}{a + j\omega} \implies a = 4`, }, { title: "Step 2: Apply Time Shift Property in Reverse", - latex: "X(\\omega) e^{-j \\omega t_0} \\iff x(t - t_0) \\implies e^{-4 (t - 2)} u(t - 2)", + latex: String.raw`X(\omega) e^{-j \omega t_0} \iff x(t - t_0) \implies e^{-4 (t - 2)} u(t - 2)`, }, ], }, { id: "ctft-bank-3", - promptLatex: - "\\text{Compute the 3dB Energy Bandwidth } \\omega_{3dB} \\text{ for } x(t) = e^{-3 t} u(t)", - referenceAnswerLatex: "\\omega_{3dB} = 3 \\text{ rad/s}", + promptLatex: String.raw`\text{Compute the 3dB Energy Bandwidth } \omega_{3dB} \text{ for } x(t) = e^{-3 t} u(t)`, + referenceAnswerLatex: String.raw`\omega_{3dB} = 3 \text{ rad/s}`, solutionSteps: [ { title: "Step 1: Form Energy Spectrum |X(w)|^2", - latex: "|X(\\omega)|^2 = \\left| \\frac{1}{3 + j\\omega} \\right|^2 = \\frac{1}{9 + \\omega^2}", + latex: String.raw`|X(\omega)|^2 = \left| \frac{1}{3 + j\omega} \right|^2 = \frac{1}{9 + \omega^2}`, }, { title: "Step 2: Set Spectrum Equal to Half Peak Energy", - latex: "|X(0)|^2 = \\frac{1}{9} \\implies \\frac{1}{9 + \\omega_{3dB}^2} = \\frac{1}{2} \\cdot \\frac{1}{9} = \\frac{1}{18}", + latex: String.raw`|X(0)|^2 = \frac{1}{9} \implies \frac{1}{9 + \omega_{3dB}^2} = \frac{1}{2} \cdot \frac{1}{9} = \frac{1}{18}`, }, { title: "Step 3: Solve for Corner Frequency", - latex: "9 + \\omega_{3dB}^2 = 18 \\implies \\omega_{3dB}^2 = 9 \\implies \\omega_{3dB} = 3 \\text{ rad/s}", + latex: String.raw`9 + \omega_{3dB}^2 = 18 \implies \omega_{3dB}^2 = 9 \implies \omega_{3dB} = 3 \text{ rad/s}`, }, ], }, diff --git a/src/routes/+error.svelte b/src/routes/+error.svelte index f2671ad1..29c15f20 100644 --- a/src/routes/+error.svelte +++ b/src/routes/+error.svelte @@ -70,15 +70,15 @@ */ function getMathFormula(pathname: string): string { if (pathname.includes("fourier-transform")) { - return "X(\\omega) = \\int_{-\\infty}^{\\infty} x(t) e^{-j\\omega t} dt"; + return String.raw`X(\omega) = \int_{-\infty}^{\infty} x(t) e^{-j\omega t} dt`; } if (pathname.includes("laplace")) { - return "X(s) = \\int_{0^{-}}^{\\infty} x(t) e^{-st} dt"; + return String.raw`X(s) = \int_{0^{-}}^{\infty} x(t) e^{-st} dt`; } if (pathname.includes("circuits")) { - return "H(s) = \\frac{V_{\\text{out}}(s)}{V_{\\text{in}}(s)}"; + return String.raw`H(s) = \frac{V_{\text{out}}(s)}{V_{\text{in}}(s)}`; } - return "H(s) \\to 0 \\quad \\text{for } t \\to \\infty"; + return String.raw`H(s) \to 0 \quad \text{for } t \to \infty`; } diff --git a/tests/e2e/ctft-browser.ts b/tests/e2e/ctft-browser.ts index 147f190b..3febea21 100644 --- a/tests/e2e/ctft-browser.ts +++ b/tests/e2e/ctft-browser.ts @@ -78,7 +78,7 @@ export function ctftBaseAnswer( if (family === "rect") return `${params.T} sinc(${params.T} omega/(2 pi))`; if (family === "exponential") return `1/(${params.a}+j omega)`; if (family === "gaussian") - return `\\sqrt{\\pi/${params.a}} e^{-\\omega^2/${4 * params.a}}`; + return String.raw`\sqrt{\pi/${params.a}} e^{-\omega^2/${4 * params.a}}`; return "1"; } @@ -102,7 +102,7 @@ async function enterImpulses( await enterCtftAnswer( page, `Impulse ${row + 1} complex weight`, - `\\pi e^{-j(${location})(${shift})}`, + String.raw`\pi e^{-j(${location})(${shift})}`, ); } } @@ -168,7 +168,7 @@ export async function prepareCtftFinal( await enterCtftAnswer( page, "Phase multiplier", - params.t0 === 0 ? "1" : `e^{-j(${params.t0})\\omega}`, + params.t0 === 0 ? "1" : String.raw`e^{-j(${params.t0})\omega}`, ); } @@ -239,7 +239,7 @@ export async function finishCtft( await enterCtftAnswer( page, "Final spectrum", - `(${ctftBaseAnswer(family, params)})e^{-j(${params.t0})\\omega}`, + String.raw`(${ctftBaseAnswer(family, params)})e^{-j(${params.t0})\omega}`, ); await expect( page.getByRole("heading", { name: "CTFT solution verified" }), diff --git a/tests/e2e/ctft-module.spec.ts b/tests/e2e/ctft-module.spec.ts index d0f41c85..aff0eb41 100644 --- a/tests/e2e/ctft-module.spec.ts +++ b/tests/e2e/ctft-module.spec.ts @@ -326,7 +326,9 @@ for (const mode of ["derivation", "pairs-properties"] as const) { await expect(page.locator(".solution-breakdown")).not.toContainText( "3.14159265", ); - await expect(page.locator(".solution-breakdown")).toContainText("\\pi"); + await expect(page.locator(".solution-breakdown")).toContainText( + String.raw`\pi`, + ); const review = page.locator(".verified-fields").last(); await expect(review).toBeVisible(); await expect(review).toContainText("3.14159265"); diff --git a/tests/e2e/practice-correctness.spec.ts b/tests/e2e/practice-correctness.spec.ts index 2de8fc11..7b30094d 100644 --- a/tests/e2e/practice-correctness.spec.ts +++ b/tests/e2e/practice-correctness.spec.ts @@ -135,7 +135,9 @@ test("Laplace poles, causal grading, and explicit assistance follow the active p } await page .locator("#laplace-input") - .fill(`(${problem.response})u((3.14159265358979323843-\\pi)t)`); + .fill( + String.raw`(${problem.response})u((3.14159265358979323843-\pi)t)`, + ); await checkResponse.click(); await expect(responseFeedback).toHaveAttribute( "data-validation", @@ -145,7 +147,7 @@ test("Laplace poles, causal grading, and explicit assistance follow the active p await answerLaplaceTask( page, responseTask, - `x\\left(t\\right)=${problem.response}`, + String.raw`x\left(t\right)=${problem.response}`, ); await expect(page.locator('[data-task-id="roc"]')).toBeVisible(); await page.getByRole("button", { name: "Next Problem" }).click(); diff --git a/tests/unit/canonical-transform.test.ts b/tests/unit/canonical-transform.test.ts index 85aaab18..9ac45189 100644 --- a/tests/unit/canonical-transform.test.ts +++ b/tests/unit/canonical-transform.test.ts @@ -16,7 +16,10 @@ import { parseStrictLatex } from "$lib/math-engine/evaluator"; function form(expression: string, variable: "t" | "omega" = "omega") { return normalizeCanonicalTransform( parseStrictLatex( - expression.replace(/\\delta\b/g, "\\operatorname{DiracDelta}"), + expression.replace( + /\\delta\b/g, + String.raw`\operatorname{DiracDelta}`, + ), ), variable, ); @@ -107,7 +110,10 @@ describe("canonical transform contract", () => { true, ); expect( - canonicalTransformsMatch(form("1+10^{-400}\\omega"), form("1")), + canonicalTransformsMatch( + form(String.raw`1+10^{-400}\omega`), + form("1"), + ), ).toBe(false); expect( canonicalTransformsMatch( diff --git a/tests/unit/circuits.test.ts b/tests/unit/circuits.test.ts index 8b612125..238d65a7 100644 --- a/tests/unit/circuits.test.ts +++ b/tests/unit/circuits.test.ts @@ -105,7 +105,7 @@ describe("Circuit Analysis & Transfer Functions Math Engine (circuits.ts)", () = }); expect(tf.numCoeffs).toEqual([-1000]); expect(tf.denCoeffs).toEqual([1, 0]); - expect(tf.hLatex).toContain("-\\frac{1000}{s}"); + expect(tf.hLatex).toContain(String.raw`-\frac{1000}{s}`); }); }); diff --git a/tests/unit/components/ConvolutionStepSolver.test.ts b/tests/unit/components/ConvolutionStepSolver.test.ts index 3526a304..d9428f53 100644 --- a/tests/unit/components/ConvolutionStepSolver.test.ts +++ b/tests/unit/components/ConvolutionStepSolver.test.ts @@ -51,7 +51,7 @@ describe("ConvolutionStepSolver", () => { const recap = view.container.querySelector(".evaluated-summary-recap"); expect(recap).toBeTruthy(); expect(recap?.textContent).not.toContain("Infinity"); - expect(recap?.textContent).toContain("\\infty"); + expect(recap?.textContent).toContain(String.raw`\infty`); }); it("renders seven parent cards and advances each typed timing substep", async () => { diff --git a/tests/unit/components/CtftStepSolver.test.ts b/tests/unit/components/CtftStepSolver.test.ts index d88bd6aa..2e2bd575 100644 --- a/tests/unit/components/CtftStepSolver.test.ts +++ b/tests/unit/components/CtftStepSolver.test.ts @@ -44,7 +44,7 @@ async function complete( (task.id === "weight-0") !== approximateReversedRows ? -problem.params.w0 : problem.params.w0; - expected = `${approximateReversedRows ? "3.14159265" : "\\pi"} e^{-j(${location})(${stage.id === "base" ? 0 : problem.params.t0})}`; + expected = String.raw`${approximateReversedRows ? "3.14159265" : String.raw`\pi`} e^{-j(${location})(${stage.id === "base" ? 0 : problem.params.t0})}`; } if (approximateReversedRows && task.kind === "location") expected = `X(omega)=${String( @@ -85,7 +85,7 @@ describe("CTFT guided component", () => { await fireEvent.submit(view.container.querySelector("form")!); expect( view.container.querySelector(".step-card.active")?.textContent, - ).toContain("\\frac{1}{2}"); + ).toContain(String.raw`\frac{1}{2}`); expect( view.container.querySelector(".step-card.active")?.textContent, ).not.toContain("0.5"); @@ -110,7 +110,7 @@ describe("CTFT guided component", () => { expect( view.container.querySelector(".solution-breakdown") ?.textContent, - ).toContain("\\pi"); + ).toContain(String.raw`\pi`); expect( [ ...view.container.querySelectorAll(".verified-fields"), diff --git a/tests/unit/components/FourierCoefficientCard.test.ts b/tests/unit/components/FourierCoefficientCard.test.ts index d736626a..f73a43b1 100644 --- a/tests/unit/components/FourierCoefficientCard.test.ts +++ b/tests/unit/components/FourierCoefficientCard.test.ts @@ -22,7 +22,7 @@ describe("FourierCoefficientCard.svelte Component", () => { num: "2", den: "n pi", harmonic: "odd", - coeffLatex: "\\frac{2}{n \\pi} (1 - (-1)^n)", + coeffLatex: String.raw`\frac{2}{n \pi} (1 - (-1)^n)`, onUpdate, }, }); @@ -61,7 +61,7 @@ describe("FourierCoefficientCard.svelte Component", () => { expect(directInput).toBeTruthy(); await fireEvent.input(directInput, { - target: { value: "\\frac{4}{n}" }, + target: { value: String.raw`\frac{4}{n}` }, }); expect(onUpdate).toHaveBeenCalled(); }); @@ -75,8 +75,8 @@ describe("FourierCoefficientCard.svelte Component", () => { idPrefix: "bn", mode: "fraction", harmonic: "custom", - customHarmonic: "\\sin(n \\pi / 2)", - coeffLatex: "\\sin(n \\pi / 2)", + customHarmonic: String.raw`\sin(n \pi / 2)`, + coeffLatex: String.raw`\sin(n \pi / 2)`, onUpdate, }, }); @@ -85,10 +85,10 @@ describe("FourierCoefficientCard.svelte Component", () => { ".custom-mult-input", ) as HTMLInputElement; expect(customInput).toBeTruthy(); - expect(customInput.value).toBe("\\sin(n \\pi / 2)"); + expect(customInput.value).toBe(String.raw`\sin(n \pi / 2)`); await fireEvent.input(customInput, { - target: { value: "\\cos(n \\pi / 2)" }, + target: { value: String.raw`\cos(n \pi / 2)` }, }); expect(onUpdate).toHaveBeenCalled(); }); diff --git a/tests/unit/components/FourierSeriesCanvas.test.ts b/tests/unit/components/FourierSeriesCanvas.test.ts index 7bfdd489..7ce0c82b 100644 --- a/tests/unit/components/FourierSeriesCanvas.test.ts +++ b/tests/unit/components/FourierSeriesCanvas.test.ts @@ -116,7 +116,9 @@ describe("FourierSeriesCanvas", () => { (node) => node.textContent ?? "", ); expect( - annotations.some((latex) => latex.includes("\\times 10^{-300}")), + annotations.some((latex) => + latex.includes(String.raw`\times 10^{-300}`), + ), ).toBe(true); for (const latex of annotations) expect(latex).not.toMatch(/\de[+-]\d/); }); @@ -199,6 +201,9 @@ describe("FourierSeriesCanvas", () => { expect( thresholdSummary?.querySelector(":scope > .math-text"), ).toBeTruthy(); + expect(thresholdSummary?.querySelectorAll(".katex-error")).toHaveLength( + 0, + ); await fireEvent.input(view.getByLabelText("Harmonic Limit:"), { target: { value: "41" }, diff --git a/tests/unit/components/FourierSeriesInput.test.ts b/tests/unit/components/FourierSeriesInput.test.ts index 9eab5751..f79081e4 100644 --- a/tests/unit/components/FourierSeriesInput.test.ts +++ b/tests/unit/components/FourierSeriesInput.test.ts @@ -27,7 +27,7 @@ describe("FourierSeriesInput", () => { ); expect(onChange).toHaveBeenCalled(); const initialLatex = onChange.mock.calls[0]![0]; - expect(initialLatex).toContain("\\sin("); + expect(initialLatex).toContain(String.raw`\sin(`); }); /** @@ -74,8 +74,8 @@ describe("FourierSeriesInput", () => { await fireEvent.input(a0Input, { target: { value: "5/2" } }); const lastCall = onChange.mock.calls.at(-1)?.[0]; - expect(lastCall).toContain("5/2 + \\sum_{n=1}^{\\infty}"); - expect(lastCall).toContain("\\pi"); + expect(lastCall).toContain(String.raw`5/2 + \sum_{n=1}^{\infty}`); + expect(lastCall).toContain(String.raw`\pi`); } }); @@ -118,7 +118,7 @@ describe("FourierSeriesInput", () => { // Select none await fireEvent.change(anSelect, { target: { value: "none" } }); latex = onChange.mock.calls.at(-1)?.[0]; - expect(latex).toContain("\\frac{4}{n^2 \\pi^2}"); + expect(latex).toContain(String.raw`\frac{4}{n^2 \pi^2}`); // Select custom harmonic await fireEvent.change(anSelect, { target: { value: "custom" } }); @@ -126,10 +126,10 @@ describe("FourierSeriesInput", () => { expect(customInput).toBeTruthy(); if (customInput) { await fireEvent.input(customInput, { - target: { value: "\\sin(n \\pi / 2)" }, + target: { value: String.raw`\sin(n \pi / 2)` }, }); latex = onChange.mock.calls.at(-1)?.[0]; - expect(latex).toContain("\\sin(n \\pi / 2)"); + expect(latex).toContain(String.raw`\sin(n \pi / 2)`); } } @@ -141,14 +141,18 @@ describe("FourierSeriesInput", () => { expect(directInput).toBeTruthy(); if (directInput) { await fireEvent.input(directInput, { target: { value: "3/n" } }); - expect(onChange.mock.calls.at(-1)?.[0]).toContain("3/n \\cos("); + expect(onChange.mock.calls.at(-1)?.[0]).toContain( + String.raw`3/n \cos(`, + ); } // Zero mode for an const zeroBtn = anCard.querySelectorAll(".toggle-btn")[0]; if (!zeroBtn) throw new Error("Expected zeroBtn"); await fireEvent.click(zeroBtn); - expect(onChange.mock.calls.at(-1)?.[0]).not.toContain("\\cos("); + expect(onChange.mock.calls.at(-1)?.[0]).not.toContain( + String.raw`\cos(`, + ); }); /** @@ -173,8 +177,8 @@ describe("FourierSeriesInput", () => { await fireEvent.click(bnZeroBtn); const latex = onChange.mock.calls.at(-1)?.[0]; - expect(latex).toContain("\\cos("); - expect(latex).not.toContain("\\sin("); + expect(latex).toContain(String.raw`\cos(`); + expect(latex).not.toContain(String.raw`\sin(`); }); /** @@ -198,17 +202,17 @@ describe("FourierSeriesInput", () => { await fireEvent.change(bnSelect, { target: { value: "none" } }); expect(onChange.mock.calls.at(-1)?.[0]).toContain( - "\\frac{2}{n \\pi}", + String.raw`\frac{2}{n \pi}`, ); await fireEvent.change(bnSelect, { target: { value: "custom" } }); const customInput = bnCard.querySelector(".custom-mult-input"); if (customInput) { await fireEvent.input(customInput, { - target: { value: "\\cos(n pi)" }, + target: { value: String.raw`\cos(n pi)` }, }); expect(onChange.mock.calls.at(-1)?.[0]).toContain( - "\\cos(n \\pi)", + String.raw`\cos(n \pi)`, ); } } @@ -220,10 +224,10 @@ describe("FourierSeriesInput", () => { const bnDirectInput = view.container.querySelector("#bn-direct-input"); if (bnDirectInput) { await fireEvent.input(bnDirectInput, { - target: { value: "\\frac{8}{n^3 \\pi^3}" }, + target: { value: String.raw`\frac{8}{n^3 \pi^3}` }, }); expect(onChange.mock.calls.at(-1)?.[0]).toContain( - "\\frac{8}{n^3 \\pi^3}", + String.raw`\frac{8}{n^3 \pi^3}`, ); } @@ -238,7 +242,7 @@ describe("FourierSeriesInput", () => { const fractionBtn = bnCard.querySelectorAll(".toggle-btn")[1]; if (!fractionBtn) throw new Error("Expected fractionBtn"); await fireEvent.click(fractionBtn); - expect(onChange.mock.calls.at(-1)?.[0]).toContain("\\sin("); + expect(onChange.mock.calls.at(-1)?.[0]).toContain(String.raw`\sin(`); }); /** @@ -298,10 +302,10 @@ describe("FourierSeriesInput", () => { const fnDirect = view.container.querySelector("#Fn-direct-input"); if (fnDirect) { await fireEvent.input(fnDirect, { - target: { value: "\\frac{2}{j n \\pi}" }, + target: { value: String.raw`\frac{2}{j n \pi}` }, }); expect(onChange.mock.calls.at(-1)?.[0]).toContain( - "\\frac{2}{j n \\pi}", + String.raw`\frac{2}{j n \pi}`, ); } @@ -344,8 +348,8 @@ describe("FourierSeriesInput", () => { await fireEvent.change(bnSelect, { target: { value: "none" } }); const latex = onChange.mock.calls.at(-1)?.[0]; - expect(latex).toContain("3 \\sin("); - expect(latex).not.toContain("\\frac{3}{1}"); + expect(latex).toContain(String.raw`3 \sin(`); + expect(latex).not.toContain(String.raw`\frac{3}{1}`); } }); }); diff --git a/tests/unit/components/FourierSeriesReviewRegressions.test.ts b/tests/unit/components/FourierSeriesReviewRegressions.test.ts index 7dd3f6cc..520a8bec 100644 --- a/tests/unit/components/FourierSeriesReviewRegressions.test.ts +++ b/tests/unit/components/FourierSeriesReviewRegressions.test.ts @@ -58,7 +58,7 @@ describe("Fourier Series review UI regressions", () => { expect(solver.currentStep).toBe(1); const displayed = problem.periodLatex .split(" = ")[1]! - .split("\\text")[0]!; + .split(String.raw`\text`)[0]!; await fireEvent.input(period, { target: { value: displayed } }); await fireEvent.keyDown(period, { key: "Enter" }); expect(solver.currentStep).toBe(2); diff --git a/tests/unit/components/HintDisclosure.test.ts b/tests/unit/components/HintDisclosure.test.ts index 712af9ec..6fe29d64 100644 --- a/tests/unit/components/HintDisclosure.test.ts +++ b/tests/unit/components/HintDisclosure.test.ts @@ -11,8 +11,8 @@ describe("HintDisclosure.svelte Component", () => { cleanup(); }); const sampleHints = [ - "First find the characteristic roots $\\lambda_1, \\lambda_2$.", - "Set up the homogeneous solution form $y_h(t) = c_1 e^{\\lambda_1 t} + c_2 e^{\\lambda_2 t}$.", + String.raw`First find the characteristic roots $\lambda_1, \lambda_2$.`, + String.raw`Set up the homogeneous solution form $y_h(t) = c_1 e^{\lambda_1 t} + c_2 e^{\lambda_2 t}$.`, "Substitute initial conditions $y(0)$ and $y'(0)$ to solve for $c_1$ and $c_2$.", ]; diff --git a/tests/unit/components/MathBlock.test.ts b/tests/unit/components/MathBlock.test.ts index 4c8c0c7d..ad1fc267 100644 --- a/tests/unit/components/MathBlock.test.ts +++ b/tests/unit/components/MathBlock.test.ts @@ -17,7 +17,7 @@ describe("MathBlock.svelte Component", () => { it("renders display-mode KaTeX math expression inside a region container", () => { const { container } = render(MathBlock, { props: { - math: "y(t) = e^{-2t} \\cos(3t) u(t)", + math: String.raw`y(t) = e^{-2t} \cos(3t) u(t)`, }, }); @@ -49,7 +49,8 @@ describe("MathBlock.svelte Component", () => { it("wraps piecewise expressions in cases environment when cases prop is true", () => { const { container } = render(MathBlock, { props: { - math: "t & 0 \\le t < 1 \\\\\n2 - t & 1 \\le t \\le 2", + math: String.raw`t & 0 \le t < 1 \\ +2 - t & 1 \le t \le 2`, cases: true, }, }); @@ -61,7 +62,9 @@ describe("MathBlock.svelte Component", () => { it("does not doubly wrap environments if already wrapped", () => { const { container } = render(MathBlock, { props: { - math: "\\begin{aligned}\nx &= 1\n\\end{aligned}", + math: String.raw`\begin{aligned} +x &= 1 +\end{aligned}`, aligned: true, }, }); @@ -143,7 +146,7 @@ describe("MathBlock.svelte Component", () => { it("hides header bar when hideHeader is true", () => { const { container } = render(MathBlock, { props: { - math: "X(s) = \\frac{1}{s+2}", + math: String.raw`X(s) = \frac{1}{s+2}`, hideHeader: true, }, }); @@ -157,7 +160,7 @@ describe("MathBlock.svelte Component", () => { it("applies compact and custom class modifiers", () => { const { container } = render(MathBlock, { props: { - math: "H(s) = \\frac{s+1}{s^2+4}", + math: String.raw`H(s) = \frac{s+1}{s^2+4}`, compact: true, class: "custom-formula-class", }, diff --git a/tests/unit/components/MathInline.test.ts b/tests/unit/components/MathInline.test.ts index d62e30e0..6efe7b50 100644 --- a/tests/unit/components/MathInline.test.ts +++ b/tests/unit/components/MathInline.test.ts @@ -44,7 +44,7 @@ describe("MathInline.svelte Component", () => { it("renders rendered KaTeX HTML for inline math expressions", () => { const { container } = render(MathInline, { props: { - math: "\\omega_0 t + \\phi", + math: String.raw`\omega_0 t + \phi`, }, }); @@ -59,7 +59,7 @@ describe("MathInline.svelte Component", () => { it("supports displayStyle formatting option", () => { const { container } = render(MathInline, { props: { - math: "\\frac{1}{2}", + math: String.raw`\frac{1}{2}`, displayStyle: true, }, }); @@ -169,7 +169,7 @@ describe("MathInline.svelte Component", () => { it("applies optional custom class names and default copy accessibility attributes", () => { const { container } = render(MathInline, { props: { - math: "e^{-\\sigma t}", + math: String.raw`e^{-\sigma t}`, class: "custom-math-class", }, }); diff --git a/tests/unit/components/MathInputBar.test.ts b/tests/unit/components/MathInputBar.test.ts index 790a5ee3..721549ff 100644 --- a/tests/unit/components/MathInputBar.test.ts +++ b/tests/unit/components/MathInputBar.test.ts @@ -16,7 +16,7 @@ describe("MathInputBar.svelte Component", () => { props: { value: "", label: "Enter Particular Solution:", - placeholder: "e.g. 5\\cos(2t)", + placeholder: String.raw`e.g. 5\cos(2t)`, inputType: "generic", }, }); @@ -100,7 +100,7 @@ describe("MathInputBar.svelte Component", () => { expect(container.querySelector(".preview-empty")).toBeDefined(); // When value is provided, MathBlock is rendered - await rerender({ value: "5\\cos(2t)" }); + await rerender({ value: String.raw`5\cos(2t)` }); expect(container.querySelector(".math-block")).toBeTruthy(); }); @@ -140,10 +140,10 @@ describe("MathInputBar.svelte Component", () => { expect(textarea).toBeTruthy(); await fireEvent.input(textarea, { - target: { value: "\\cos(3t)" }, + target: { value: String.raw`\cos(3t)` }, }); - expect(handleChange).toHaveBeenCalledWith("\\cos(3t)"); + expect(handleChange).toHaveBeenCalledWith(String.raw`\cos(3t)`); }); it("appends math symbols when symbol shortcut buttons are clicked in freehand mode", async () => { diff --git a/tests/unit/components/MathText.test.ts b/tests/unit/components/MathText.test.ts index 3ce32b56..6a40aaa9 100644 --- a/tests/unit/components/MathText.test.ts +++ b/tests/unit/components/MathText.test.ts @@ -30,7 +30,7 @@ describe("MathText.svelte Component", () => { it("parses and renders inline $...$ LaTeX math with KaTeX", () => { const { container } = render(MathText, { props: { - text: "Given the differential equation with roots $\\lambda_1 = -1$ and $\\lambda_2 = -3$.", + text: String.raw`Given the differential equation with roots $\lambda_1 = -1$ and $\lambda_2 = -3$.`, }, }); @@ -92,13 +92,13 @@ describe("MathText.svelte Component", () => { const { container } = render(MathText, { props: { - text: "Macro \\omega_0 symbol", + text: String.raw`Macro \omega_0 symbol`, }, }); const errorSpan = container.querySelector(".katex-error"); expect(errorSpan).toBeTruthy(); - expect(errorSpan?.textContent).toBe("\\omega_0"); + expect(errorSpan?.textContent).toBe(String.raw`\omega_0`); }); /** All delimited and standalone fallback paths share the same escaping contract. */ @@ -110,7 +110,8 @@ describe("MathText.svelte Component", () => { throw new RangeError("Maximum call stack size exceeded"); }); const markup = '&\'text'; - const source = kind === "macro" ? `\\text{${markup}}` : markup; + const source = + kind === "macro" ? String.raw`\text{${markup}}` : markup; const text = kind === "inline" ? `$${source}$` @@ -155,7 +156,7 @@ describe("MathText.svelte Component", () => { it("defensively renders standalone un-enclosed LaTeX macros", () => { const { container } = render(MathText, { props: { - text: "The angular frequency is \\omega_0 rad/s.", + text: String.raw`The angular frequency is \omega_0 rad/s.`, }, }); @@ -178,7 +179,7 @@ describe("MathText.svelte Component", () => { it("applies optional custom class names to wrapper span", () => { const { container } = render(MathText, { props: { - text: "Sample text $t \\ge 0$", + text: String.raw`Sample text $t \ge 0$`, class: "custom-text-wrapper", }, }); diff --git a/tests/unit/components/OdeResponseInput.test.ts b/tests/unit/components/OdeResponseInput.test.ts index 239d0853..df189ac5 100644 --- a/tests/unit/components/OdeResponseInput.test.ts +++ b/tests/unit/components/OdeResponseInput.test.ts @@ -127,8 +127,8 @@ describe("OdeResponseInput.svelte Component", () => { expect(handleChange).toHaveBeenCalled(); const lastCall = handleChange.mock.calls.at(-1)?.[0]; expect(lastCall).toContain("e^{-2t}"); - expect(lastCall).toContain("\\cos(5t)"); - expect(lastCall).toContain("\\sin(5t)"); + expect(lastCall).toContain(String.raw`\cos(5t)`); + expect(lastCall).toContain(String.raw`\sin(5t)`); }); it("switches to first order mode and synthesizes single exponential response", async () => { diff --git a/tests/unit/configured-convolution.test.ts b/tests/unit/configured-convolution.test.ts index bd788b96..df0ffc6c 100644 --- a/tests/unit/configured-convolution.test.ts +++ b/tests/unit/configured-convolution.test.ts @@ -237,7 +237,7 @@ describe("independently configured convolution signals", () => { ); expect(triangle.parameter).toBe(2); expect(triangle.breakpoints).toEqual([-1, 0, 1]); - expect(triangle.latex).toBe("\\Delta\\left(t\\right)"); + expect(triangle.latex).toBe(String.raw`\Delta\left(t\right)`); expect(triangle.eval(-1)).toBe(0); expect(triangle.eval(0)).toBe(1); expect(triangle.eval(0.5)).toBe(0.5); diff --git a/tests/unit/constant-proofs.test.ts b/tests/unit/constant-proofs.test.ts index 41fad8cc..2b3df7dd 100644 --- a/tests/unit/constant-proofs.test.ts +++ b/tests/unit/constant-proofs.test.ts @@ -163,13 +163,13 @@ describe("constant proof boundaries", () => { /** Domain failures survive rewrites and boxed AST wrappers. */ it("refuses canceled or masked uncertain divisors and invalid domains", () => { for (const [decimal, multiple] of roundedPi) { - const c = `${decimal}-${multiple}\\pi`; + const c = String.raw`${decimal}-${multiple}\pi`; for (const expression of [ `0/(${c})`, `(${c})/(${c})`, `1/(1/(${c}))`, - `0\\ln(${c})`, - `0\\sqrt{${c}}`, + String.raw`0\ln(${c})`, + String.raw`0\sqrt{${c}}`, `|${c}|`, `(${c})^t`, ]) @@ -198,10 +198,10 @@ describe("constant proof boundaries", () => { } for (const expression of [ "0(1/0)", - "0\\ln(-1)", + String.raw`0\ln(-1)`, "0^0", "0^{-1}", - "\\sqrt[0]{2}", + String.raw`\sqrt[0]{2}`, ]) expect( () => @@ -234,7 +234,7 @@ describe("constant proof boundaries", () => { for (const [decimal, multiple] of roundedPi) expect( validateLaplacePfdAnswer( - `e^{-4t}u((${decimal}-${multiple}\\pi)t)`, + String.raw`e^{-4t}u((${decimal}-${multiple}\pi)t)`, problem, ).status, ).toBe("unsupported"); diff --git a/tests/unit/convolution-beginner-workflow.test.ts b/tests/unit/convolution-beginner-workflow.test.ts index 5522868c..00e2beee 100644 --- a/tests/unit/convolution-beginner-workflow.test.ts +++ b/tests/unit/convolution-beginner-workflow.test.ts @@ -555,10 +555,10 @@ describe("convolution beginner workflow metadata", () => { expect(parseConvolutionScalarInput("-inf")).toBe( Number.NEGATIVE_INFINITY, ); - expect(parseConvolutionScalarInput("\\infty")).toBe( + expect(parseConvolutionScalarInput(String.raw`\infty`)).toBe( Number.POSITIVE_INFINITY, ); - expect(parseConvolutionScalarInput("-\\infty")).toBe( + expect(parseConvolutionScalarInput(String.raw`-\infty`)).toBe( Number.NEGATIVE_INFINITY, ); expect(parseConvolutionScalarInput("∞")).toBe(Number.POSITIVE_INFINITY); diff --git a/tests/unit/convolution-expression-validation.test.ts b/tests/unit/convolution-expression-validation.test.ts index 227a0338..01cd4a6d 100644 --- a/tests/unit/convolution-expression-validation.test.ts +++ b/tests/unit/convolution-expression-validation.test.ts @@ -77,7 +77,10 @@ describe("convolution expression equivalence", () => { /** Ambiguous exact constant proofs retain their more specific explanation. */ it("preserves a constant-verification diagnostic", () => { expect( - verifyConvolutionExpression("u((3.141592653589793-\\pi)t)", "0"), + verifyConvolutionExpression( + String.raw`u((3.141592653589793-\pi)t)`, + "0", + ), ).toEqual({ status: "unsupported", message: @@ -142,7 +145,9 @@ describe("convolution expression equivalence", () => { expect(convolutionExpressionsMatch("t", "t", { min: 1, max: 1 })).toBe( false, ); - expect(convolutionExpressionsMatch("inf", "\\infty")).toBe(true); + expect(convolutionExpressionsMatch("inf", String.raw`\infty`)).toBe( + true, + ); }); /** Equivalent finite constants must use the same expression evaluator. */ it.each(["2+2", "(4)", "8/2", "4+t-t"])( @@ -217,7 +222,9 @@ describe("convolution expression equivalence", () => { }); /** Infinity is a scalar boundary sentinel rather than a finite expression. */ it("preserves infinity boundary matching and rejects invalid expressions", () => { - expect(convolutionExpressionsMatch("inf", "\\infty")).toBe(true); + expect(convolutionExpressionsMatch("inf", String.raw`\infty`)).toBe( + true, + ); expect(convolutionExpressionsMatch("-inf", "inf")).toBe(false); expect(convolutionExpressionsMatch("4", "5")).toBe(false); expect(convolutionExpressionsMatch("1/0", "0")).toBe(false); diff --git a/tests/unit/convolution-pulse-formatting.test.ts b/tests/unit/convolution-pulse-formatting.test.ts index 1f01dd9c..b2885fc5 100644 --- a/tests/unit/convolution-pulse-formatting.test.ts +++ b/tests/unit/convolution-pulse-formatting.test.ts @@ -24,13 +24,17 @@ describe("convolution pulse formatting", () => { }); it("simplifies unit and shifted-unit pulses while preserving general scaling", () => { - expect(formatRectPulseLatex(1)).toBe("\\operatorname{rect}(t)"); - expect(formatRectPulseLatex(1, 2)).toBe("\\operatorname{rect}(t - 2)"); + expect(formatRectPulseLatex(1)).toBe( + String.raw`\operatorname{rect}(t)`, + ); + expect(formatRectPulseLatex(1, 2)).toBe( + String.raw`\operatorname{rect}(t - 2)`, + ); expect(formatRectPulseLatex(1, -2, -1)).toBe( - "-\\operatorname{rect}(t + 2)", + String.raw`-\operatorname{rect}(t + 2)`, ); expect(formatRectPulseLatex(3, 1, 2)).toBe( - "2\\operatorname{rect}\\left(\\frac{t - 1}{3}\\right)", + String.raw`2\operatorname{rect}\left(\frac{t - 1}{3}\right)`, ); }); diff --git a/tests/unit/convolution-step-solver-lifecycle.test.ts b/tests/unit/convolution-step-solver-lifecycle.test.ts index 482aa576..26b1c9af 100644 --- a/tests/unit/convolution-step-solver-lifecycle.test.ts +++ b/tests/unit/convolution-step-solver-lifecycle.test.ts @@ -247,7 +247,7 @@ describe("ConvolutionStepSolverState lifecycle and regression tests", () => { expect(parseConvolutionScalarInput("+inf")).toBe( Number.POSITIVE_INFINITY, ); - expect(parseConvolutionScalarInput("-\\infty")).toBe( + expect(parseConvolutionScalarInput(String.raw`-\infty`)).toBe( Number.NEGATIVE_INFINITY, ); }); @@ -879,7 +879,7 @@ describe("ConvolutionStepSolverState lifecycle and regression tests", () => { }; const section = sections[0]; if (!section) throw new Error("Expected exponential section."); - expect(section.leftLatex).toContain("\\infty"); + expect(section.leftLatex).toContain(String.raw`\infty`); const input = solver.step3.edgeInputs[section.id]; if (!input) throw new Error("Expected infinite edge input."); for (const [answer, diagnostic] of [ diff --git a/tests/unit/convolution-symbolic-grading.test.ts b/tests/unit/convolution-symbolic-grading.test.ts index 7d2d086c..c1f1392f 100644 --- a/tests/unit/convolution-symbolic-grading.test.ts +++ b/tests/unit/convolution-symbolic-grading.test.ts @@ -25,7 +25,9 @@ import { * @returns Equivalent expression preserving infinity notation. */ function withZero(expression: string): string { - return expression.includes("\\infty") ? expression : `(${expression})+0`; + return expression.includes(String.raw`\infty`) + ? expression + : `(${expression})+0`; } /** @@ -170,7 +172,7 @@ function verifyBounds( ).toBe("valid"); } const first = field.boundInputs[0]; - if (first && !first.lower.includes("\\infty")) { + if (first && !first.lower.includes(String.raw`\infty`)) { field.stage = "bounds"; const original = first.lower; first.lower = `(${original})+1`; diff --git a/tests/unit/ctft-answer-validation.test.ts b/tests/unit/ctft-answer-validation.test.ts index e07e895a..7f9210a1 100644 --- a/tests/unit/ctft-answer-validation.test.ts +++ b/tests/unit/ctft-answer-validation.test.ts @@ -50,7 +50,7 @@ describe("CTFT answer validation", () => { validateCtftAnswer(`1+${product}`, problem).status, product, ).toBe("unsupported"); - for (const term of [`0${d}`, `${d}-${d}`, `0${d}\\omega`]) + for (const term of [`0${d}`, `${d}-${d}`, String.raw`0${d}\omega`]) expect( validateCtftAnswer(`1+(${term})`, problem).status, term, diff --git a/tests/unit/ctft-presentation.test.ts b/tests/unit/ctft-presentation.test.ts index 8df367d1..f4b87d6d 100644 --- a/tests/unit/ctft-presentation.test.ts +++ b/tests/unit/ctft-presentation.test.ts @@ -37,9 +37,9 @@ describe("exact CTFT solutions", () => { /** Odd generated widths retain reduced fractions in bounds, phases, identities, and hints. */ it("formats pulse half-widths exactly throughout the lesson", () => { for (const [T, half] of [ - [1, "\\frac{1}{2}"], + [1, String.raw`\frac{1}{2}`], [2, "1"], - [3, "\\frac{3}{2}"], + [3, String.raw`\frac{3}{2}`], [4, "2"], [6, "3"], ] as const) { @@ -100,10 +100,10 @@ describe("exact CTFT solutions", () => { if (task.kind === "location") expect(value).toBe(String(location)); else { - expect(value).toContain("\\pi"); + expect(value).toContain(String.raw`\pi`); if (stage.id === "final" && t0) expect(value).toContain(`(${location})(${t0})`); - else expect(value).toBe("\\pi"); + else expect(value).toBe(String.raw`\pi`); } } } diff --git a/tests/unit/ctft-tutor.test.ts b/tests/unit/ctft-tutor.test.ts index 80a79729..931e2351 100644 --- a/tests/unit/ctft-tutor.test.ts +++ b/tests/unit/ctft-tutor.test.ts @@ -78,7 +78,7 @@ function answerCurrent(solver: CtftStepSolverState, reverse = false): void { solver.stages[stage.id]!.parts[ task.id.replace("weight", "location") ]!.input; - state.input = `\\pi e^{-j(${location})(${stage.id === "base" ? 0 : solver.problem.params.t0})}`; + state.input = String.raw`\pi e^{-j(${location})(${stage.id === "base" ? 0 : solver.problem.params.t0})}`; } solver.check(stage.id, task.id); expect( @@ -283,7 +283,9 @@ describe("CTFT tutor", () => { expect(task.hints.join(" ")).not.toMatch( /verified endpoint|verified exponent|your sine expression|upper minus lower/, ); - expect(task.identityLatex ?? "").not.toContain("\\int"); + expect(task.identityLatex ?? "").not.toContain( + String.raw`\int`, + ); } } const derivation = buildCtftLesson( @@ -384,12 +386,12 @@ describe("CTFT tutor", () => { ).toBe("unsupported"); for (const [answer, status] of [ ["", "invalid"], - ["\\frac{", "invalid"], + [String.raw`\frac{`, "invalid"], ["omega-omega+pi", "invalid"], ["0/0", "invalid"], ["tan(omega)", "unsupported"], ["delta(omega)", "unsupported"], - ["\\delta(omega)", "invalid"], + [String.raw`\delta(omega)`, "invalid"], ] as const) expect( validateCtftImpulseRows(["-3", "3"], [answer, "pi"], problem) @@ -463,7 +465,9 @@ describe("CTFT tutor", () => { expect(validateCtftCalculation(answer, target).status).toBe( "incorrect", ); - expect(validateCtftCalculation("\\frac{", "1").status).toBe("invalid"); + expect(validateCtftCalculation(String.raw`\frac{`, "1").status).toBe( + "invalid", + ); expect(validateCtftCalculation("sin(omega^2)", "1").status).toBe( "unsupported", ); @@ -603,9 +607,11 @@ describe("CTFT tutor", () => { expect(validateCtftConstant("2+omega-omega", "2", true).status).toBe( "invalid", ); - expect(validateCtftConstant("\\pi", "\\pi").status).toBe("correct"); + expect( + validateCtftConstant(String.raw`\pi`, String.raw`\pi`).status, + ).toBe("correct"); expect(validateCtftConstant("1/0", "2").status).toBe("invalid"); - expect(validateCtftConstant("\\tan(omega)", "2").status).toBe( + expect(validateCtftConstant(String.raw`\tan(omega)`, "2").status).toBe( "unsupported", ); expect(validateCtftConstant("x".repeat(16385), "2").status).toBe( @@ -621,7 +627,7 @@ describe("CTFT tutor", () => { advance(solver, "base"); for (const [input, expected] of [ ["", "invalid"], - ["\\tan(omega)", "unsupported"], + [String.raw`\tan(omega)`, "unsupported"], ["sinc(2omega/pi)", "incorrect"], ]) { solver.currentStepState!.input = input!; diff --git a/tests/unit/evaluator.test.ts b/tests/unit/evaluator.test.ts index 29c1d196..e1e4f464 100644 --- a/tests/unit/evaluator.test.ts +++ b/tests/unit/evaluator.test.ts @@ -198,7 +198,7 @@ describe("Math Engine Evaluator (evaluator.ts)", () => { expect(shiftedVal).toBeCloseTo(3 * Math.exp(-2), 4); }); - it("evaluates fractions formatted with \\frac", () => { + it(String.raw`evaluates fractions formatted with \frac`, () => { const val = evaluateLatexAt( String.raw`\frac{3}{4} t + \frac{1}{2}`, 2, @@ -300,12 +300,15 @@ describe("Math Engine Evaluator (evaluator.ts)", () => { expect(evaluatePiecewiseLatexAt(piecewise, 3)).toBe(6); }); - it("evaluates piecewise interval expressions with \\text{for} syntax", () => { - const piecewise = String.raw`\begin{cases} 0 \quad \text{for} \quad t < 0 \\ 3t \quad \text{for} \quad 0 \le t < 2 \\ 6 \quad \text{for} \quad t \ge 2 \end{cases}`; - expect(evaluatePiecewiseLatexAt(piecewise, -1)).toBe(0); - expect(evaluatePiecewiseLatexAt(piecewise, 1)).toBe(3); - expect(evaluatePiecewiseLatexAt(piecewise, 4)).toBe(6); - }); + it( + String.raw`evaluates piecewise interval expressions with \text{for} syntax`, + () => { + const piecewise = String.raw`\begin{cases} 0 \quad \text{for} \quad t < 0 \\ 3t \quad \text{for} \quad 0 \le t < 2 \\ 6 \quad \text{for} \quad t \ge 2 \end{cases}`; + expect(evaluatePiecewiseLatexAt(piecewise, -1)).toBe(0); + expect(evaluatePiecewiseLatexAt(piecewise, 1)).toBe(3); + expect(evaluatePiecewiseLatexAt(piecewise, 4)).toBe(6); + }, + ); it("returns 0 when sample point does not match any piecewise interval condition", () => { const piecewise = String.raw`\begin{cases} 2t, & 1 \le t \le 2 \end{cases}`; diff --git a/tests/unit/formatting.test.ts b/tests/unit/formatting.test.ts index d4788b34..5b63524e 100644 --- a/tests/unit/formatting.test.ts +++ b/tests/unit/formatting.test.ts @@ -16,12 +16,12 @@ describe("formatCoefficientTerm", () => { it("omits unit coefficient 1 for non-empty symbols", () => { expect(formatCoefficientTerm(1, "y(t)", false)).toBe("+ y(t)"); expect(formatCoefficientTerm(1, "y(t)", true)).toBe("y(t)"); - expect(formatCoefficientTerm(1, "\\frac{dy}{dt}", false)).toBe( - "+ \\frac{dy}{dt}", - ); - expect(formatCoefficientTerm(1, "\\frac{d^2 y}{dt^2}", true)).toBe( - "\\frac{d^2 y}{dt^2}", + expect(formatCoefficientTerm(1, String.raw`\frac{dy}{dt}`, false)).toBe( + String.raw`+ \frac{dy}{dt}`, ); + expect( + formatCoefficientTerm(1, String.raw`\frac{d^2 y}{dt^2}`, true), + ).toBe(String.raw`\frac{d^2 y}{dt^2}`); expect(formatCoefficientTerm(1, "s", false)).toBe("+ s"); expect(formatCoefficientTerm(1, "s", true)).toBe("s"); }); @@ -29,9 +29,9 @@ describe("formatCoefficientTerm", () => { it("omits unit coefficient -1 for non-empty symbols with correct negative sign", () => { expect(formatCoefficientTerm(-1, "y(t)", false)).toBe("- y(t)"); expect(formatCoefficientTerm(-1, "y(t)", true)).toBe("-y(t)"); - expect(formatCoefficientTerm(-1, "\\frac{dy}{dt}", false)).toBe( - "- \\frac{dy}{dt}", - ); + expect( + formatCoefficientTerm(-1, String.raw`\frac{dy}{dt}`, false), + ).toBe(String.raw`- \frac{dy}{dt}`); expect(formatCoefficientTerm(-1, "s", false)).toBe("- s"); expect(formatCoefficientTerm(-1, "s", true)).toBe("-s"); }); @@ -39,11 +39,11 @@ describe("formatCoefficientTerm", () => { it("includes numerical coefficient for values not equal to +/- 1", () => { expect(formatCoefficientTerm(2, "y(t)", false)).toBe("+ 2 y(t)"); expect(formatCoefficientTerm(2, "y(t)", true)).toBe("2 y(t)"); - expect(formatCoefficientTerm(-3, "\\frac{dy}{dt}", false)).toBe( - "- 3 \\frac{dy}{dt}", - ); - expect(formatCoefficientTerm(-3, "\\frac{dy}{dt}", true)).toBe( - "-3 \\frac{dy}{dt}", + expect( + formatCoefficientTerm(-3, String.raw`\frac{dy}{dt}`, false), + ).toBe(String.raw`- 3 \frac{dy}{dt}`); + expect(formatCoefficientTerm(-3, String.raw`\frac{dy}{dt}`, true)).toBe( + String.raw`-3 \frac{dy}{dt}`, ); expect(formatCoefficientTerm(4, "s", false)).toBe("+ 4 s"); }); @@ -146,16 +146,16 @@ describe("formatQuadraticPolynomial", () => { describe("formatOdeLhs", () => { it("formats ODE left-hand side omitting unit 1 and -1 coefficients", () => { expect(formatOdeLhs(1, 2, 1)).toBe( - "\\frac{d^2 y}{dt^2} + 2 \\frac{dy}{dt} + y(t)", + String.raw`\frac{d^2 y}{dt^2} + 2 \frac{dy}{dt} + y(t)`, ); expect(formatOdeLhs(1, 1, 1)).toBe( - "\\frac{d^2 y}{dt^2} + \\frac{dy}{dt} + y(t)", + String.raw`\frac{d^2 y}{dt^2} + \frac{dy}{dt} + y(t)`, ); expect(formatOdeLhs(1, -1, -1)).toBe( - "\\frac{d^2 y}{dt^2} - \\frac{dy}{dt} - y(t)", + String.raw`\frac{d^2 y}{dt^2} - \frac{dy}{dt} - y(t)`, ); expect(formatOdeLhs(1, 3, 2)).toBe( - "\\frac{d^2 y}{dt^2} + 3 \\frac{dy}{dt} + 2 y(t)", + String.raw`\frac{d^2 y}{dt^2} + 3 \frac{dy}{dt} + 2 y(t)`, ); }); }); @@ -184,9 +184,9 @@ describe("formatRootFactor", () => { describe("sanitizeLatexMath", () => { it("replaces adjacent double operators (+ +, + -, - -, - +)", () => { - expect(sanitizeLatexMath("2e^{-t} + + \\frac{1}{2}\\sin(2t)")).toBe( - "2e^{-t} + \\frac{1}{2}\\sin(2t)", - ); + expect( + sanitizeLatexMath(String.raw`2e^{-t} + + \frac{1}{2}\sin(2t)`), + ).toBe(String.raw`2e^{-t} + \frac{1}{2}\sin(2t)`); expect(sanitizeLatexMath("C_1 e^{-t} + - 3 e^{-2t}")).toBe( "C_1 e^{-t} - 3 e^{-2t}", ); @@ -199,8 +199,8 @@ describe("sanitizeLatexMath", () => { it("cleans unit multipliers and leading positive signs inside brackets", () => { expect(sanitizeLatexMath("e^{(-1t)}")).toBe("e^{-t}"); expect(sanitizeLatexMath("e^{(1t)}")).toBe("e^{t}"); - expect(sanitizeLatexMath("[ + 2\\cos(t) - 3\\sin(t)]")).toBe( - "[2\\cos(t) - 3\\sin(t)]", + expect(sanitizeLatexMath(String.raw`[ + 2\cos(t) - 3\sin(t)]`)).toBe( + String.raw`[2\cos(t) - 3\sin(t)]`, ); }); }); @@ -276,9 +276,15 @@ describe("sanitizeUnitCoefficients", () => { expect(sanitizeUnitCoefficients("1e^{-1t}")).toBe("e^{-t}"); expect(sanitizeUnitCoefficients("-1e^{-1t}")).toBe("-e^{-t}"); expect(sanitizeUnitCoefficients("1e^{1t}")).toBe("e^{t}"); - expect(sanitizeUnitCoefficients("1\\cos(1t)")).toBe("\\cos(t)"); - expect(sanitizeUnitCoefficients("1\\sin(-1t)")).toBe("\\sin(-t)"); - expect(sanitizeUnitCoefficients("-1\\cos(2t)")).toBe("-\\cos(2t)"); + expect(sanitizeUnitCoefficients(String.raw`1\cos(1t)`)).toBe( + String.raw`\cos(t)`, + ); + expect(sanitizeUnitCoefficients(String.raw`1\sin(-1t)`)).toBe( + String.raw`\sin(-t)`, + ); + expect(sanitizeUnitCoefficients(String.raw`-1\cos(2t)`)).toBe( + String.raw`-\cos(2t)`, + ); }); it("handles Electrical Engineering imaginary unit j notation", () => { @@ -290,7 +296,9 @@ describe("sanitizeUnitCoefficients", () => { expect(sanitizeUnitCoefficients("-1j")).toBe("-j"); expect(sanitizeUnitCoefficients("j1e^{-j1t}")).toBe("je^{-jt}"); expect(sanitizeUnitCoefficients("1je^{-1jt}")).toBe("je^{-jt}"); - expect(sanitizeUnitCoefficients("\\pm j1")).toBe("\\pm j"); + expect(sanitizeUnitCoefficients(String.raw`\pm j1`)).toBe( + String.raw`\pm j`, + ); }); it("reduces nested double parentheses", () => { @@ -351,10 +359,18 @@ describe("sanitizeUnitCoefficients", () => { expect(sanitizeUnitCoefficients("s + 1 = 0")).toBe("s + 1 = 0"); expect(sanitizeUnitCoefficients("y(0) = 1")).toBe("y(0) = 1"); expect(sanitizeUnitCoefficients("5 + 1")).toBe("5 + 1"); - expect(sanitizeUnitCoefficients("\\frac{1}{2}")).toBe("\\frac{1}{2}"); - expect(sanitizeUnitCoefficients("\\frac{1}{10}")).toBe("\\frac{1}{10}"); - expect(sanitizeUnitCoefficients("\\cos(10t)")).toBe("\\cos(10t)"); - expect(sanitizeUnitCoefficients("\\sin(151t)")).toBe("\\sin(151t)"); + expect(sanitizeUnitCoefficients(String.raw`\frac{1}{2}`)).toBe( + String.raw`\frac{1}{2}`, + ); + expect(sanitizeUnitCoefficients(String.raw`\frac{1}{10}`)).toBe( + String.raw`\frac{1}{10}`, + ); + expect(sanitizeUnitCoefficients(String.raw`\cos(10t)`)).toBe( + String.raw`\cos(10t)`, + ); + expect(sanitizeUnitCoefficients(String.raw`\sin(151t)`)).toBe( + String.raw`\sin(151t)`, + ); expect(sanitizeUnitCoefficients("100")).toBe("100"); }); }); diff --git a/tests/unit/fourier-expression-oracle.ts b/tests/unit/fourier-expression-oracle.ts index b5ede860..f34628a4 100644 --- a/tests/unit/fourier-expression-oracle.ts +++ b/tests/unit/fourier-expression-oracle.ts @@ -207,8 +207,8 @@ export function sampleFourierExpression( sample: Sample, ): Complex { const normalized = latex - .replaceAll("\\left[", "\\left(") - .replaceAll("\\right]", "\\right)"); + .replaceAll(String.raw`\left[`, String.raw`\left(`) + .replaceAll(String.raw`\right]`, String.raw`\right)`); return evaluate(parseStrictLatex(normalized), sample); } @@ -222,11 +222,11 @@ export function sampleFourierDefinition( latex: string, sample: Sample, ): Complex { - if (!latex.startsWith("\\begin{cases}")) + if (!latex.startsWith(String.raw`\begin{cases}`)) return sampleFourierExpression(latex, sample); const rows = latex - .replace("\\begin{cases}", "") - .replace("\\end{cases}", "") + .replace(String.raw`\begin{cases}`, "") + .replace(String.raw`\end{cases}`, "") .split("\\\\"); for (const row of rows) { const [value, condition = ""] = row.split("&"); diff --git a/tests/unit/fourier-series-distractor-regressions.test.ts b/tests/unit/fourier-series-distractor-regressions.test.ts index 04a71c4f..f813bfca 100644 --- a/tests/unit/fourier-series-distractor-regressions.test.ts +++ b/tests/unit/fourier-series-distractor-regressions.test.ts @@ -123,8 +123,9 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)( const witnesses = options.map((option) => [0.13, 0.37, 0.81].map((fraction) => { const t = fraction * coeffs.T0; - const synthesis = - option.latex.split(",\\qquad")[0]!; + const synthesis = option.latex.split( + String.raw`,\qquad`, + )[0]!; const rhs = synthesis.slice( synthesis.indexOf("=") + 1, ); diff --git a/tests/unit/fourier-series-its-generator.test.ts b/tests/unit/fourier-series-its-generator.test.ts index 6e09adc9..b84548c4 100644 --- a/tests/unit/fourier-series-its-generator.test.ts +++ b/tests/unit/fourier-series-its-generator.test.ts @@ -20,15 +20,15 @@ describe("Fourier Series ITS Step Generator Engine", () => { ] as const; it.each([ - ["square", "4(1)", "\\sin"], - ["square_odd", "4(1)", "\\sin"], - ["square_even", "\\sin\\left(\\frac{n\\pi}{2}", "\\cos"], - ["triangle", "8(1)", "n^2\\pi^2"], - ["triangle_odd", "8(1)", "\\sin\\left(\\frac{n\\pi}{2}"], - ["triangle_even", "8(1)", "n^2\\pi^2"], + ["square", "4(1)", String.raw`\sin`], + ["square_odd", "4(1)", String.raw`\sin`], + ["square_even", String.raw`\sin\left(\frac{n\pi}{2}`, String.raw`\cos`], + ["triangle", "8(1)", String.raw`n^2\pi^2`], + ["triangle_odd", "8(1)", String.raw`\sin\left(\frac{n\pi}{2}`], + ["triangle_even", "8(1)", String.raw`n^2\pi^2`], ["sawtooth", "(-1)^{n+1}", "2(1)"], ["half_wave_sine", "F_n", "n=-1"], - ["full_wave_sine", "4n^2-1", "\\frac{2(1)}{\\pi}"], + ["full_wave_sine", "4n^2-1", String.raw`\frac{2(1)}{\pi}`], ] as const)( "builds the exact final series for %s", (waveform, expectedA, expectedB) => { @@ -197,7 +197,7 @@ describe("Fourier Series ITS Step Generator Engine", () => { } const compact = problem.conversionChallenge.parts[1].resultLatex; expect(compact).toContain("c_n"); - expect(compact).toContain("\\theta_n"); + expect(compact).toContain(String.raw`\theta_n`); expect(compact).not.toContain("A_n"); }, ); diff --git a/tests/unit/fourier-series-math-contracts.test.ts b/tests/unit/fourier-series-math-contracts.test.ts index 3dbb7fac..bb684ff2 100644 --- a/tests/unit/fourier-series-math-contracts.test.ts +++ b/tests/unit/fourier-series-math-contracts.test.ts @@ -36,7 +36,7 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)( }); const d = buildFourierSeriesSymbolicDerivation( coeffs, - "\\pi/2", + String.raw`\pi/2`, ); const latex = d.expEvaluationLatex!; /** Confirms scientific parameters also remain valid in the rendered worked evaluation. */ @@ -54,7 +54,9 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)( `${n === 1 ? "F_1" : "F_{-1}"}=`, )[1]! .split("\\\\")[0]! - : latex.split("F_n=")[1]!.split("\\quad")[0]!; + : latex + .split("F_n=")[1]! + .split(String.raw`\quad`)[0]!; const displayed = sampleFourierBoundaryExpression( row.split("=")[0]!, sample, @@ -79,7 +81,10 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)( A: 3, T0: 4, }); - const d = buildFourierSeriesSymbolicDerivation(coeffs, "\\pi/2"); + const d = buildFourierSeriesSymbolicDerivation( + coeffs, + String.raw`\pi/2`, + ); for (const n of [1, 2, 3]) { for (const [label, integral, expected] of [ ["a_0", d.a0IntegralLatex, coeffs.a0], @@ -103,7 +108,10 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)( A: 2, T0: 4, }); - const d = buildFourierSeriesSymbolicDerivation(coeffs, "\\pi/2"); + const d = buildFourierSeriesSymbolicDerivation( + coeffs, + String.raw`\pi/2`, + ); for (const n of [-5, -2, -1, 0, 1, 2, 5]) { let re = 0; let im = 0; @@ -141,7 +149,7 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)( A: 3, T0: 4, }); - const compact = buildCompactSeriesLatex(coeffs, "\\pi/2"); + const compact = buildCompactSeriesLatex(coeffs, String.raw`\pi/2`); for (const n of [1, 2, 3, 4, 5, 7]) { let amplitude: string; let phase: string; @@ -162,7 +170,7 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)( /c_n=(.*?),\\quad \\theta_n=/, )![1]!; phase = compact - .split("\\theta_n=")[1]! + .split(String.raw`\theta_n=`)[1]! .replace(/\\ \(n\\text\{ odd\}\)$/, ""); } const sample = { coeffs, n, t: 0 }; diff --git a/tests/unit/fourier-series-review-regressions.test.ts b/tests/unit/fourier-series-review-regressions.test.ts index ae5a33b2..490e31bd 100644 --- a/tests/unit/fourier-series-review-regressions.test.ts +++ b/tests/unit/fourier-series-review-regressions.test.ts @@ -99,9 +99,11 @@ describe("Fourier Series adversarial regressions", () => { ).toBeCloseTo(expected, 2); } if (T0 !== 2 && T0 !== 4) { - expect(problem.omega0Latex).toContain(`\\frac{2\\pi}{${T0}}`); + expect(problem.omega0Latex).toContain( + String.raw`\frac{2\pi}{${T0}}`, + ); expect(problem.itsData.step1.hints[2]).toContain( - `\\frac{2\\pi}{${T0}}`, + String.raw`\frac{2\pi}{${T0}}`, ); } }, diff --git a/tests/unit/fourier-series-step-solver.test.ts b/tests/unit/fourier-series-step-solver.test.ts index 285d577d..27ede942 100644 --- a/tests/unit/fourier-series-step-solver.test.ts +++ b/tests/unit/fourier-series-step-solver.test.ts @@ -79,14 +79,22 @@ describe("FourierSeriesStepSolverState Reactive Controller", () => { input: { period: "0.000104", periodUnit: "ms" }, accepted: true, }, - { T0: 1e21, input: { freq: "6.5\\times10^{-21}" }, accepted: true }, { T0: 1e21, - input: { freq: "1.04\\times10^{-21}", freqUnit: "Hz" }, + input: { freq: String.raw`6.5\times10^{-21}` }, + accepted: true, + }, + { + T0: 1e21, + input: { freq: String.raw`1.04\times10^{-21}`, freqUnit: "Hz" }, accepted: true, }, { T0: 1e-7, input: { period: "0.000000106" }, accepted: false }, - { T0: 1e21, input: { freq: "6.7\\times10^{-21}" }, accepted: false }, + { + T0: 1e21, + input: { freq: String.raw`6.7\times10^{-21}` }, + accepted: false, + }, { T0: 2, input: { period: "2.06" }, accepted: false }, { T0: 2, input: { freq: String(Math.PI + 0.06) }, accepted: false }, { T0: 2, input: { period: "2.04", freq: "3.18" }, accepted: true }, @@ -564,7 +572,7 @@ describe("FourierSeriesStepSolverState Reactive Controller", () => { expect(opt.latex.length).toBeGreaterThan(0); expect( opt.latex.includes("=") || - opt.latex.includes("\\int") || + opt.latex.includes(String.raw`\int`) || opt.latex.includes("0"), ).toBe(true); } diff --git a/tests/unit/fourier-series-symbolic-derivations.test.ts b/tests/unit/fourier-series-symbolic-derivations.test.ts index 0990ab05..8c03cca6 100644 --- a/tests/unit/fourier-series-symbolic-derivations.test.ts +++ b/tests/unit/fourier-series-symbolic-derivations.test.ts @@ -36,9 +36,12 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => { A: 3, T0: 4, }); - const latex = buildFinalSeriesLatex(coeffs, "\\frac{\\pi}{2}"); + const latex = buildFinalSeriesLatex( + coeffs, + String.raw`\frac{\pi}{2}`, + ); expect(latex).toContain("x(t) ="); - expect(latex).toContain("\\frac{\\pi}{2}"); + expect(latex).toContain(String.raw`\frac{\pi}{2}`); }, ); @@ -49,7 +52,7 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => { T0: 2, } as FourierSeriesCoefficients; expect(() => - buildFinalSeriesLatex(invalidCoeffs, "\\pi"), + buildFinalSeriesLatex(invalidCoeffs, String.raw`\pi`), ).toThrowError(/Unsupported waveform type/); }); }); @@ -62,8 +65,13 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => { A: 2, T0: 2, }); - const compactLatex = buildCompactSeriesLatex(coeffs, "\\pi"); - expect(compactLatex).toContain("x(t)=\\frac{c_0}{2}+\\sum"); + const compactLatex = buildCompactSeriesLatex( + coeffs, + String.raw`\pi`, + ); + expect(compactLatex).toContain( + String.raw`x(t)=\frac{c_0}{2}+\sum`, + ); expect(compactLatex).toContain("c_n="); }, ); @@ -75,7 +83,7 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => { T0: 2, } as FourierSeriesCoefficients; expect(() => - buildCompactSeriesLatex(invalidCoeffs, "\\pi"), + buildCompactSeriesLatex(invalidCoeffs, String.raw`\pi`), ).toThrowError(/Unsupported waveform type/); }); }); @@ -106,7 +114,7 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => { }); const derivation = buildFourierSeriesSymbolicDerivation( coeffs, - "\\pi", + String.raw`\pi`, ); expect(derivation.a0Latex).toBeDefined(); @@ -114,7 +122,9 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => { expect(derivation.bnLatex).toBeDefined(); expect(derivation.FnLatex).toBeDefined(); expect(derivation.finalTrigLatex).toContain("x(t) ="); - expect(derivation.finalExpLatex).toContain("x(t)=\\sum"); + expect(derivation.finalExpLatex).toContain( + String.raw`x(t)=\sum`, + ); expect(derivation.a0IntegralLatex).toContain("a_0="); expect(derivation.evaluationLatex).toBeDefined(); }, @@ -127,7 +137,10 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => { T0: 2, } as FourierSeriesCoefficients; expect(() => - buildFourierSeriesSymbolicDerivation(invalidCoeffs, "\\pi"), + buildFourierSeriesSymbolicDerivation( + invalidCoeffs, + String.raw`\pi`, + ), ).toThrowError(/Unsupported waveform type/); }); }); diff --git a/tests/unit/fourier-series-tutor-contracts.test.ts b/tests/unit/fourier-series-tutor-contracts.test.ts index 246fc18c..ddbea855 100644 --- a/tests/unit/fourier-series-tutor-contracts.test.ts +++ b/tests/unit/fourier-series-tutor-contracts.test.ts @@ -19,7 +19,7 @@ describe("Fourier tutor contracts", () => { }); const derivation = buildFourierSeriesSymbolicDerivation( problem.coeffs, - "\\pi", + String.raw`\pi`, ); delete derivation.expEvaluationLatex; const step = buildStep6Data("exp", "even", derivation, Math.random); @@ -49,6 +49,21 @@ describe("Fourier tutor contracts", () => { expect(p.itsData.step3.hints.join(" ")).toContain("a_{2k}"); }); + /** Ensures the no-parity explanation closes both LaTeX text groups. */ + it("renders the half-wave-sine symmetry explanation", () => { + const problem = generateFourierSeriesProblem("half_wave_sine", { + seed: 1, + }); + const latex = problem.solutionSteps[1]!.latex!; + + expect(latex).toContain( + String.raw`a_n\text{ and }b_n\text{ must both be evaluated}`, + ); + expect(() => + renderToString(latex, { throwOnError: true }), + ).not.toThrow(); + }); + /** Tests both explicit paths even when they differ from the symmetry recommendation. */ it.each(["trig", "exp"] as const)( "keeps assigned %s metadata and solution consistent", diff --git a/tests/unit/fourier-transform-bank.test.ts b/tests/unit/fourier-transform-bank.test.ts index ca65151c..7c9ba36a 100644 --- a/tests/unit/fourier-transform-bank.test.ts +++ b/tests/unit/fourier-transform-bank.test.ts @@ -6,14 +6,21 @@ describe("CTFT Problem Bank (fourier-transform-bank.ts)", () => { expect(CTFT_EXAM_BANK.length).toBeGreaterThan(0); }); - it("should enforce \\operatorname for all custom operators across all bank questions", () => { - for (const item of CTFT_EXAM_BANK) { - expect(item.promptLatex).not.toContain("\\text{sinc}"); - expect(item.promptLatex).not.toContain("\\text{rect}"); - expect(item.referenceAnswerLatex).not.toContain("\\text{sinc}"); - expect(item.referenceAnswerLatex).not.toContain("\\text{rect}"); - } - }); + it( + String.raw`should enforce \operatorname for all custom operators across all bank questions`, + () => { + for (const item of CTFT_EXAM_BANK) { + expect(item.promptLatex).not.toContain(String.raw`\text{sinc}`); + expect(item.promptLatex).not.toContain(String.raw`\text{rect}`); + expect(item.referenceAnswerLatex).not.toContain( + String.raw`\text{sinc}`, + ); + expect(item.referenceAnswerLatex).not.toContain( + String.raw`\text{rect}`, + ); + } + }, + ); it("should provide multi-step solution breakdowns for every bank problem", () => { for (const item of CTFT_EXAM_BANK) { diff --git a/tests/unit/fourier-transform.test.ts b/tests/unit/fourier-transform.test.ts index 55240acc..1fef49c6 100644 --- a/tests/unit/fourier-transform.test.ts +++ b/tests/unit/fourier-transform.test.ts @@ -34,17 +34,24 @@ describe("CTFT Math Engine (fourier-transform/index.ts)", () => { } }); describe("CTFT Transform Pairs & Custom Operator Formatting", () => { - it("should evaluate rectangular pulse transform to normalized sinc with \\operatorname{sinc}", () => { - const pair = getCtftPairLatex("rect", { T: 2 }); - expect(pair.timeLatex).toContain("\\operatorname{rect}"); - expect(pair.freqLatex).toContain("\\operatorname{sinc}"); - expect(pair.freqLatex).not.toContain("\\text{sinc}"); - }); + it( + String.raw`should evaluate rectangular pulse transform to normalized sinc with \operatorname{sinc}`, + () => { + const pair = getCtftPairLatex("rect", { T: 2 }); + expect(pair.timeLatex).toContain( + String.raw`\operatorname{rect}`, + ); + expect(pair.freqLatex).toContain( + String.raw`\operatorname{sinc}`, + ); + expect(pair.freqLatex).not.toContain(String.raw`\text{sinc}`); + }, + ); it("should format exponential decay e^{-a t} u(t) correctly", () => { const pair = getCtftPairLatex("exponential", { a: 3 }); expect(pair.timeLatex).toBe("e^{-3 t} u(t)"); - expect(pair.freqLatex).toBe("\\frac{1}{3 + j\\omega}"); + expect(pair.freqLatex).toBe(String.raw`\frac{1}{3 + j\omega}`); }); }); diff --git a/tests/unit/fraction.test.ts b/tests/unit/fraction.test.ts index eba1e476..053ee1af 100644 --- a/tests/unit/fraction.test.ts +++ b/tests/unit/fraction.test.ts @@ -9,23 +9,23 @@ describe("toFractionLatex", () => { }); it("formats standard repeating fractions correctly", () => { - expect(toFractionLatex(1 / 3)).toBe("\\frac{1}{3}"); - expect(toFractionLatex(-1 / 3)).toBe("-\\frac{1}{3}"); - expect(toFractionLatex(1 / 6)).toBe("\\frac{1}{6}"); - expect(toFractionLatex(-7 / 6)).toBe("-\\frac{7}{6}"); + expect(toFractionLatex(1 / 3)).toBe(String.raw`\frac{1}{3}`); + expect(toFractionLatex(-1 / 3)).toBe(String.raw`-\frac{1}{3}`); + expect(toFractionLatex(1 / 6)).toBe(String.raw`\frac{1}{6}`); + expect(toFractionLatex(-7 / 6)).toBe(String.raw`-\frac{7}{6}`); }); it("formats ninths fractions correctly (1/9, 3/9, 10/9)", () => { - expect(toFractionLatex(1 / 9)).toBe("\\frac{1}{9}"); - expect(toFractionLatex(3 / 9)).toBe("\\frac{1}{3}"); - expect(toFractionLatex(10 / 9)).toBe("\\frac{10}{9}"); - expect(toFractionLatex(-10 / 9)).toBe("-\\frac{10}{9}"); + expect(toFractionLatex(1 / 9)).toBe(String.raw`\frac{1}{9}`); + expect(toFractionLatex(3 / 9)).toBe(String.raw`\frac{1}{3}`); + expect(toFractionLatex(10 / 9)).toBe(String.raw`\frac{10}{9}`); + expect(toFractionLatex(-10 / 9)).toBe(String.raw`-\frac{10}{9}`); }); it("formats decimal fractions like 0.25, 0.75, -1.5", () => { - expect(toFractionLatex(0.25)).toBe("\\frac{1}{4}"); - expect(toFractionLatex(0.75)).toBe("\\frac{3}{4}"); - expect(toFractionLatex(-1.5)).toBe("-\\frac{3}{2}"); + expect(toFractionLatex(0.25)).toBe(String.raw`\frac{1}{4}`); + expect(toFractionLatex(0.75)).toBe(String.raw`\frac{3}{4}`); + expect(toFractionLatex(-1.5)).toBe(String.raw`-\frac{3}{2}`); }); }); @@ -68,11 +68,17 @@ describe("parseNumericInput", () => { }); it("parses LaTeX fraction notation", () => { - expect(parseNumericInput("\\frac{5}{3}")).toBeCloseTo(5 / 3); - expect(parseNumericInput("-\\frac{11}{3}")).toBeCloseTo(-11 / 3); - expect(parseNumericInput("\\frac{-11}{3}")).toBeCloseTo(-11 / 3); - expect(parseNumericInput("\\frac{11}{-3}")).toBeCloseTo(-11 / 3); - expect(parseNumericInput("\\frac{-5}{-9}")).toBeCloseTo(5 / 9); + expect(parseNumericInput(String.raw`\frac{5}{3}`)).toBeCloseTo(5 / 3); + expect(parseNumericInput(String.raw`-\frac{11}{3}`)).toBeCloseTo( + -11 / 3, + ); + expect(parseNumericInput(String.raw`\frac{-11}{3}`)).toBeCloseTo( + -11 / 3, + ); + expect(parseNumericInput(String.raw`\frac{11}{-3}`)).toBeCloseTo( + -11 / 3, + ); + expect(parseNumericInput(String.raw`\frac{-5}{-9}`)).toBeCloseTo(5 / 9); }); it("returns NaN for invalid or empty inputs", () => { diff --git a/tests/unit/input-builders.test.ts b/tests/unit/input-builders.test.ts index b66b4a72..927dbce1 100644 --- a/tests/unit/input-builders.test.ts +++ b/tests/unit/input-builders.test.ts @@ -22,7 +22,7 @@ describe("Guided Form Builder LaTeX Validation Integration", () => { */ it("validates synthesized Laplace rational transfer function H(s)", () => { // Synthesized from PoleZeroInput: \frac{2(s+1)}{(s+2)(s+3)} - const synthesizedLatex = "\\frac{2(s+1)}{(s+2)(s+3)}"; + const synthesizedLatex = String.raw`\frac{2(s+1)}{(s+2)(s+3)}`; const refEval = (s: number): number => { return (2 * (s + 1)) / ((s + 2) * (s + 3)); }; @@ -36,7 +36,7 @@ describe("Guided Form Builder LaTeX Validation Integration", () => { */ it("validates synthesized time-domain phasor sinusoid", () => { // Synthesized from PhasorInput: 10 \cos(2t) - const synthesizedLatex = "10 \\cos(2t)"; + const synthesizedLatex = String.raw`10 \cos(2t)`; const refEval = (t: number): number => 10 * Math.cos(2 * t); const result = validateLatexAnswer(synthesizedLatex, refEval); @@ -48,10 +48,9 @@ describe("Guided Form Builder LaTeX Validation Integration", () => { */ it("validates synthesized Fourier series coefficient expression", () => { // Synthesized from FourierSeriesInput: \sum_{n=1}^{\infty} \left[ \frac{2}{n\pi} (1 - (-1)^n) \sin(n \omega_0 t) \right] - const synthesizedLatex = - "\\sum_{n=1}^{\\infty} \\left[ \\frac{2}{n\\pi} (1 - (-1)^n) \\sin(n \\pi t) \\right]"; + const synthesizedLatex = String.raw`\sum_{n=1}^{\infty} \left[ \frac{2}{n\pi} (1 - (-1)^n) \sin(n \pi t) \right]`; - expect(synthesizedLatex).toContain("\\frac{2}{n\\pi}"); + expect(synthesizedLatex).toContain(String.raw`\frac{2}{n\pi}`); expect(synthesizedLatex).toContain("(1 - (-1)^n)"); }); }); diff --git a/tests/unit/laplace-algebra.test.ts b/tests/unit/laplace-algebra.test.ts index 0da136ea..56c4d6e3 100644 --- a/tests/unit/laplace-algebra.test.ts +++ b/tests/unit/laplace-algebra.test.ts @@ -34,7 +34,9 @@ describe("expanded exact Laplace mathematics", () => { expect(verifyLaplaceTime("1", [])).toMatchObject({ status: "incorrect", }); - expect(verifyLaplaceTime("\\delta(t)", []).status).toBe("incorrect"); + expect(verifyLaplaceTime(String.raw`\delta(t)`, []).status).toBe( + "incorrect", + ); }); it("preserves exact fractional support boundaries and ROC labels", () => { const input = spec({ poles: [f("-1/3")], delay: "1/3" }); @@ -43,7 +45,7 @@ describe("expanded exact Laplace mathematics", () => { "correct", ); expect(formatRoc(rocBounds(input.poles, -1), input.poles)).toBe( - "\\operatorname{Re}(s)>-\\frac{1}{3}", + String.raw`\operatorname{Re}(s)>-\frac{1}{3}`, ); expect(() => rocBounds([f("1"), f("1.00000000000000001")], 1)).toThrow( "too close", @@ -65,14 +67,17 @@ describe("expanded exact Laplace mathematics", () => { it("inverts repeated, conjugate, delayed, and constant-quotient terms", () => { for (const [input, expected] of [ [spec({ gain: "6", poles: [f("-4", 4)] }), "t^3e^{-4t}u(t)"], - [spec({ poles: [f("-3", 1, "5")] }), "e^{-3t}\\sin(5t)u(t)/5"], + [ + spec({ poles: [f("-3", 1, "5")] }), + String.raw`e^{-3t}\sin(5t)u(t)/5`, + ], [ spec({ gain: "4", poles: [f("-5")], delay: "2" }), "4e^{-5(t-2)}u(t-2)", ], [ spec({ zeros: [f("-6")], poles: [f("-2")] }), - "\\delta(t)+4e^{-2t}u(t)", + String.raw`\delta(t)+4e^{-2t}u(t)`, ], ] as [RationalSpec, string][]) { const data = decompose(input), @@ -106,8 +111,8 @@ describe("expanded exact Laplace mathematics", () => { for (const answer of [ "e^{-(t-2)}u(t)", "e^{-(t-2)}u(t-2)+u(t-100)", - "e^{-(t-2)}u(t-2)+\\delta(t-100)", - "e^{-(t-2)}u(t-2)+\\delta'(t)", + String.raw`e^{-(t-2)}u(t-2)+\delta(t-100)`, + String.raw`e^{-(t-2)}u(t-2)+\delta'(t)`, ]) expect(verifyLaplaceTime(answer, terms).status).not.toBe("correct"); expect(verifyLaplaceS("1/(s+1)+1/(s+100)", "1/(s+1)").status).toBe( diff --git a/tests/unit/laplace-answer-entry.test.ts b/tests/unit/laplace-answer-entry.test.ts index e20543f9..6d8aee83 100644 --- a/tests/unit/laplace-answer-entry.test.ts +++ b/tests/unit/laplace-answer-entry.test.ts @@ -68,7 +68,7 @@ describe("guided Laplace answer entry", () => { expect(fieldTasks).toHaveLength(2); for (const task of fieldTasks) { expect(renderLaplaceFields(task.frame, {})).toContain( - "\\square", + String.raw`\square`, ); expect( validateLaplaceTask(task, "", {}, problem.terms).result @@ -125,7 +125,7 @@ describe("guided Laplace answer entry", () => { verifyLaplaceTime(prefix + problem.response, problem.terms) .status, ).toBe("correct"); - const lhs = "y_{\\mathrm{ZI}}(t)"; + const lhs = String.raw`y_{\mathrm{ZI}}(t)`; expect( verifyLaplaceTime(`${lhs}=${problem.response}`, problem.terms, lhs) .status, diff --git a/tests/unit/laplace-choice-presentation.test.ts b/tests/unit/laplace-choice-presentation.test.ts index 675349ef..e5e0cf7e 100644 --- a/tests/unit/laplace-choice-presentation.test.ts +++ b/tests/unit/laplace-choice-presentation.test.ts @@ -14,7 +14,7 @@ describe("Laplace choice presentation", () => { expect(choices[kind]!.math).toContain( side === "left" ? "u(d-t)" : "u(t-d)", ); - expect(choices.impulse!.math).toBe("A\\delta(t-d)"); + expect(choices.impulse!.math).toBe(String.raw`A\delta(t-d)`); } }); /** Method descriptions explain the operation without disclosing applicability. */ diff --git a/tests/unit/laplace-constant-preview.test.ts b/tests/unit/laplace-constant-preview.test.ts index e21d268c..ee8e53aa 100644 --- a/tests/unit/laplace-constant-preview.test.ts +++ b/tests/unit/laplace-constant-preview.test.ts @@ -50,7 +50,7 @@ describe("Laplace constant preview eligibility", () => { gain: value, }), value, - ).not.toContain("\\square"); + ).not.toContain(String.raw`\square`); } }); /** Invalid, nonfinite, unsupported and canceled-variable drafts never become completed mathematical previews. */ @@ -76,7 +76,7 @@ describe("Laplace constant preview eligibility", () => { gain: value, }), value, - ).toContain("\\square"); + ).toContain(String.raw`\square`); } }); /** Preview validity never validates a wrong quotient or weakens exact comparisons. */ diff --git a/tests/unit/laplace-construction.test.ts b/tests/unit/laplace-construction.test.ts index ca8c919f..b9d68826 100644 --- a/tests/unit/laplace-construction.test.ts +++ b/tests/unit/laplace-construction.test.ts @@ -75,7 +75,7 @@ describe("exact learner-built Laplace mathematics", () => { ); expect( tasks.find((task) => task.id === "division")!.hints[2], - ).toContain("\\deg D=3"); + ).toContain(String.raw`\deg D=3`); expect(tasks.find((task) => task.id === "method")!.hints[2]).toContain( "s^{3}+21s^{2}+147s+343", ); diff --git a/tests/unit/laplace-elimination.test.ts b/tests/unit/laplace-elimination.test.ts index 6bc8fe6d..6fd588c3 100644 --- a/tests/unit/laplace-elimination.test.ts +++ b/tests/unit/laplace-elimination.test.ts @@ -47,17 +47,20 @@ describe("checked coefficient elimination", () => { ["A", "B"], ); expect(tasks).toHaveLength(4); + expect(tasks[0]!.hints[2]).toContain(String.raw`\frac{1}{2}`); expect(tasks[0]!.fields.map((field) => field.target)).toEqual([ "1", - "\\frac{1}{2}", - "\\frac{1}{2}", + String.raw`\frac{1}{2}`, + String.raw`\frac{1}{2}`, ]); - expect(tasks.at(-1)!.fields.at(-1)!.target).toBe("\\frac{1}{3}"); + expect(tasks.at(-1)!.fields.at(-1)!.target).toBe( + String.raw`\frac{1}{3}`, + ); const later = tasks.filter((task) => task.operation!.column > 0); expect(later.length).toBeGreaterThan(0); for (const task of later) { expect(task.hints[2]).toContain("This entry changes"); - expect(task.hints[2]).not.toContain("\\frac{0}"); + expect(task.hints[2]).not.toContain(String.raw`\frac{0}`); } for (const task of tasks) { expect(task.operation!.after).toEqual( diff --git a/tests/unit/laplace-fixtures.ts b/tests/unit/laplace-fixtures.ts index 52bd91c4..a5e573a2 100644 --- a/tests/unit/laplace-fixtures.ts +++ b/tests/unit/laplace-fixtures.ts @@ -8,11 +8,17 @@ export const inverseFixtures = [ /** Standard-pair fixtures include repeated, complex, delayed, and impulse terms. */ export const pairFixtures = [ - { transform: "(3s+8)/(s^2+16)", inverse: "(3\\cos(4t)+2\\sin(4t))u(t)" }, - { transform: "(s+3)/((s+3)^2+25)", inverse: "e^{-3t}\\cos(5t)u(t)" }, + { + transform: "(3s+8)/(s^2+16)", + inverse: String.raw`(3\cos(4t)+2\sin(4t))u(t)`, + }, + { + transform: "(s+3)/((s+3)^2+25)", + inverse: String.raw`e^{-3t}\cos(5t)u(t)`, + }, { transform: "4e^{-2s}/(s+5)", inverse: "4e^{-5(t-2)}u(t-2)" }, { transform: "6/(s+4)^4", inverse: "t^3e^{-4t}u(t)" }, - { transform: "5+6/(s+2)", inverse: "5\\delta(t)+6e^{-2t}u(t)" }, + { transform: "5+6/(s+2)", inverse: String.raw`5\delta(t)+6e^{-2t}u(t)` }, ] as const; /** Forward fixtures avoid the undefined product of an impulse with a discontinuous step. */ @@ -20,5 +26,5 @@ export const forwardFixtures = [ { transform: "(6s+26)/((s+3)(s+5))", inverse: "(4e^{-3t}+2e^{-5t})u(t)" }, { transform: "3/((s+1)(s+4))", inverse: "(e^{-t}-e^{-4t})u(t)" }, { transform: "(5s+6)/(s(s+2))", inverse: "(3+2e^{-2t})u(t)" }, - { transform: "(s+6)/(s+2)", inverse: "\\delta(t)+4e^{-2t}u(t)" }, + { transform: "(s+6)/(s+2)", inverse: String.raw`\delta(t)+4e^{-2t}u(t)` }, ] as const; diff --git a/tests/unit/laplace-formatting.test.ts b/tests/unit/laplace-formatting.test.ts index 82c5dce9..b7f2129f 100644 --- a/tests/unit/laplace-formatting.test.ts +++ b/tests/unit/laplace-formatting.test.ts @@ -39,7 +39,7 @@ describe("precedence-aware Laplace notation", () => { expect(signalLatex(term({ amplitude: "0" }))).toBe("0"); expect( signalLatex(term({ kind: "impulse", amplitude: "-1", delay: "1" })), - ).toBe("-\\delta(t-1)"); + ).toBe(String.raw`-\delta(t-1)`); expect(signalLatex(term({ rate: "-1", delay: "1" }))).toBe( "e^{-(t-1)}u(t-1)", ); @@ -48,7 +48,7 @@ describe("precedence-aware Laplace notation", () => { responseLatex([term(), term({ amplitude: "-1", delay: "1" })]), ).toBe("u(t)-u(t-1)"); expect(signalTransform(term({ amplitude: "-1", delay: "1" }))).toBe( - "-e^{-s}\\frac{1}{s}", + String.raw`-e^{-s}\frac{1}{s}`, ); expect( factorProductLatex([ @@ -63,7 +63,7 @@ describe("precedence-aware Laplace notation", () => { ).toBe("2(s+1)^{2}"); expect( rationalLatex({ n: [fraction(-1)], d: [fraction(0), fraction(1)] }), - ).toBe("-\\frac{1}{s}"); + ).toBe(String.raw`-\frac{1}{s}`); expect(scaledLatex(fraction(-1), "t-1", true)).toBe("-(t-1)"); }); /** Independently authored time and transform answers catch sign/grouping regressions in both support directions. */ diff --git a/tests/unit/laplace-input-entry.test.ts b/tests/unit/laplace-input-entry.test.ts index 112f4b35..8ce55c63 100644 --- a/tests/unit/laplace-input-entry.test.ts +++ b/tests/unit/laplace-input-entry.test.ts @@ -34,7 +34,14 @@ describe("declared Laplace input domains", () => { it("accepts exact literals while keeping incomplete numbers invalid", () => { for (const value of ["-3/2", "0.125", "-2", "1/.5"]) expect(entryIssue(value, { kind: "literal" }), value).toBeNull(); - for (const value of ["-", ".", "1/", "1/0", "1+2", "\\frac{1}{2}"]) + for (const value of [ + "-", + ".", + "1/", + "1/0", + "1+2", + String.raw`\frac{1}{2}`, + ]) expect(entryIssue(value, { kind: "literal" })?.status, value).toBe( "invalid", ); diff --git a/tests/unit/laplace-ode-tutor.test.ts b/tests/unit/laplace-ode-tutor.test.ts index 60fbc71f..aa07e627 100644 --- a/tests/unit/laplace-ode-tutor.test.ts +++ b/tests/unit/laplace-ode-tutor.test.ts @@ -42,7 +42,7 @@ describe("Laplace initial-value guidance", () => { .flatMap((stage) => stage.tasks) .filter((task) => task.id.startsWith("jump-")); expect(jumps).toHaveLength(1); - expect(jumps[0]!.answer).toBe("\\frac{5}{2}"); + expect(jumps[0]!.answer).toBe(String.raw`\frac{5}{2}`); expect( problem.stages .flatMap((stage) => stage.tasks) diff --git a/tests/unit/laplace-support.test.ts b/tests/unit/laplace-support.test.ts index 02180cb4..b0db1204 100644 --- a/tests/unit/laplace-support.test.ts +++ b/tests/unit/laplace-support.test.ts @@ -98,7 +98,7 @@ describe("checked support interval evidence", () => { validateLaplaceTask(task, "", values, []).result.status, ).toBe("invalid"); } - expect(tasks.at(-1)!.formula).toContain("\\begin{cases}"); + expect(tasks.at(-1)!.formula).toContain(String.raw`\begin{cases}`); }); /** Equivalent rational delays create one boundary and impulses stay separate. */ it("deduplicates exact boundaries and retains separate impulse metadata", () => { @@ -109,8 +109,8 @@ describe("checked support interval evidence", () => { ]; const tasks = supportTasks(original, original); expect(tasks.filter((task) => task.kind === "fields")).toHaveLength(2); - expect(tasks[0]!.formula).toContain("\\delta"); - expect(tasks.at(-1)!.hints[1]).toContain("\\delta"); + expect(tasks[0]!.formula).toContain(String.raw`\delta`); + expect(tasks.at(-1)!.hints[1]).toContain(String.raw`\delta`); }); /** Tests symbolic identities over the complete interval, not one numerical sample. */ it("accepts equivalent ordinary expressions and rejects support functions, impulses, and wrong sums", () => { @@ -121,7 +121,7 @@ describe("checked support interval evidence", () => { expect(verifyLaplaceInterval("2t", "2t-1", interval).status).toBe( "incorrect", ); - for (const expression of ["u(t)", "\\delta(t-1)"]) + for (const expression of ["u(t)", String.raw`\delta(t-1)`]) expect( verifyLaplaceInterval(expression, "1", interval).status, ).toBe("invalid"); diff --git a/tests/unit/laplace.test.ts b/tests/unit/laplace.test.ts index bd302ea9..53b60283 100644 --- a/tests/unit/laplace.test.ts +++ b/tests/unit/laplace.test.ts @@ -1,4 +1,5 @@ -import { describe, expect, it } from "vitest"; +import katex from "katex"; +import { describe, expect, it, vi } from "vitest"; import { determineStability, evaluatePfdResidues, @@ -31,7 +32,9 @@ describe("Laplace Transform Math Engine (laplace.ts)", () => { it("should identify causal system as BIBO stable if all poles are in LHP", () => { const stability = determineStability([-2, -3], "right-sided"); expect(stability.isBiboStable).toBe(true); - expect(stability.rocLatex).toBe("\\operatorname{Re}(s) > -2"); + expect(stability.rocLatex).toBe( + String.raw`\operatorname{Re}(s) > -2`, + ); }); it("should identify causal system as unstable if any pole is in RHP", () => { @@ -56,6 +59,24 @@ describe("Laplace Transform Math Engine (laplace.ts)", () => { expect(problem.solutionSteps.length).toBeGreaterThanOrEqual(2); }); + /** Confirms the trigonometric inverse pairs render with complete fraction groups. */ + it("renders the direct inverse trigonometric transform pairs", () => { + const random = vi.spyOn(Math, "random").mockReturnValue(0); + + try { + const problem = generateLaplaceProblem("inverse_direct"); + const latex = problem.solutionSteps[1]!.latex; + + expect(latex).toContain(String.raw`\frac{s}{s^2 + 2^2}`); + expect(latex).toContain(String.raw`\frac{2}{s^2 + 2^2}`); + expect(() => + katex.renderToString(latex, { throwOnError: true }), + ).not.toThrow(); + } finally { + random.mockRestore(); + } + }); + it("should generate valid forward Laplace transform practice problem", () => { const problem = generateLaplaceProblem("forward"); expect(problem.id).toBeDefined(); diff --git a/tests/unit/lint-escaped-latex.test.ts b/tests/unit/lint-escaped-latex.test.ts new file mode 100644 index 00000000..f80b4787 --- /dev/null +++ b/tests/unit/lint-escaped-latex.test.ts @@ -0,0 +1,190 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { expect, it } from "vitest"; +import { + findEscapedLatexViolations, + lintPaths, +} from "../../scripts/lint-escaped-latex.mjs"; + +const backslash = String.fromCharCode(92); +const escapedBackslash = backslash + backslash; +const tick = String.fromCharCode(96); + +/** + * Detects escaped LaTeX commands in quoted strings and interpolated templates. + */ +it("detects escaped commands in quoted strings and untagged templates", function detectsEscapedStrings() { + const templateSource = [ + "const interpolated = ", + tick, + escapedBackslash + "text{", + "${label}", + "}", + tick, + ";", + ].join(""); + const source = [ + 'const quoted = "' + escapedBackslash + "frac{x}{y}" + '";', + templateSource, + "", + ].join("\n"); + const violations = findEscapedLatexViolations(source, "fixture.ts"); + + expect(violations).toHaveLength(2); + expect(violations[0]?.line).toBe(1); + expect(violations[0]?.command).toBe(backslash + "frac"); + expect(violations[1]?.line).toBe(2); + expect(violations[1]?.command).toBe(backslash + "text"); +}); + +/** + * Detects escaped Greek LaTeX commands used in project math expressions. + */ +it("detects escaped Greek LaTeX commands", function detectsEscapedGreekCommands() { + const source = + 'const formula = "' + + escapedBackslash + + "beta " + + escapedBackslash + + "gamma " + + escapedBackslash + + 'lambda";'; + const violations = findEscapedLatexViolations(source, "fixture.ts"); + + expect(violations).toEqual([ + { line: 1, command: backslash + "beta", offset: expect.any(Number) }, + { line: 1, command: backslash + "gamma", offset: expect.any(Number) }, + { line: 1, command: backslash + "lambda", offset: expect.any(Number) }, + ]); +}); + +/** + * Detects escaped LaTeX in Svelte script and markup expressions. + */ +it("detects escaped commands in Svelte expressions", function detectsSvelteExpressions() { + const source = [ + '', + '', + ].join("\n"); + const violations = findEscapedLatexViolations(source, "fixture.svelte"); + + expect(violations).toHaveLength(2); + expect(violations[0]?.line).toBe(1); + expect(violations[0]?.command).toBe(backslash + "frac"); + expect(violations[1]?.line).toBe(2); + expect(violations[1]?.command).toBe(backslash + "text"); +}); + +/** + * Ignores raw templates, comments, regular expressions, ordinary escapes, and paths. + */ +it("ignores String.raw templates and non-LaTeX JavaScript strings", function ignoresSafeStrings() { + const rawTemplate = [ + "const formula = String.raw", + tick, + escapedBackslash + "frac{", + "${label}", + "}", + tick, + ";", + ].join(""); + const rawInterpolation = [ + "const formula = String.raw", + tick, + escapedBackslash + "frac{", + "${", + '"' + escapedBackslash + "text{x}" + '"', + "}", + "}", + tick, + ";", + ].join(""); + const source = [ + "// " + escapedBackslash + "frac appears only in this comment.", + "const regex = /" + escapedBackslash + "frac/;", + 'const newline = "' + backslash + 'n";', + 'const path = "C:' + escapedBackslash + 'Users\\\\student";', + rawTemplate, + rawInterpolation, + ].join("\n"); + + expect(findEscapedLatexViolations(source, "fixture.ts")).toEqual([ + { + line: 6, + command: backslash + "text", + offset: expect.any(Number), + }, + ]); + expect( + findEscapedLatexViolations( + "", + "fixture.svelte", + ), + ).toEqual([]); +}); + +/** + * Scans explicit staged paths and the default source, test, and script directories. + */ +it("supports explicit paths and default directory scans", async function scansRequestedPaths() { + const projectRoot = await mkdtemp( + path.join(tmpdir(), "escaped-latex-lint-"), + ); + + try { + await Promise.all([ + mkdir(path.join(projectRoot, "src"), { recursive: true }), + mkdir(path.join(projectRoot, "tests"), { recursive: true }), + mkdir(path.join(projectRoot, "scripts"), { recursive: true }), + ]); + await Promise.all([ + writeFile( + path.join(projectRoot, "src", "app.ts"), + 'const formula = "' + escapedBackslash + "omega" + '";', + ), + writeFile( + path.join(projectRoot, "tests", "fixture.ts"), + "const value = 1;", + ), + writeFile( + path.join(projectRoot, "scripts", "tool.mjs"), + "const value = 2;", + ), + writeFile( + path.join(projectRoot, "src", "notes.txt"), + escapedBackslash + "frac", + ), + ]); + + const staged = await lintPaths( + [path.join(projectRoot, "src", "app.ts")], + projectRoot, + ); + expect(staged.files).toEqual(["src/app.ts"]); + expect(staged.violations).toEqual([ + { + file: "src/app.ts", + line: 1, + command: backslash + "omega", + }, + ]); + + const fullScan = await lintPaths([], projectRoot); + expect(fullScan.files).toEqual([ + "scripts/tool.mjs", + "src/app.ts", + "tests/fixture.ts", + ]); + expect(fullScan.violations).toEqual(staged.violations); + } finally { + await rm(projectRoot, { recursive: true, force: true }); + } +}); diff --git a/tests/unit/mathblock.test.ts b/tests/unit/mathblock.test.ts index f322b3b2..e43bbfd8 100644 --- a/tests/unit/mathblock.test.ts +++ b/tests/unit/mathblock.test.ts @@ -15,20 +15,31 @@ function getFormattedMath( const trimmed = (rawMath || "").trim(); if (!trimmed) return ""; - if (opts.matrix && !trimmed.startsWith(`\\begin{${opts.matrix}}`)) { - return `\\begin{${opts.matrix}}\n${trimmed}\n\\end{${opts.matrix}}`; + if ( + opts.matrix && + !trimmed.startsWith(String.raw`\begin{${opts.matrix}}`) + ) { + return String.raw`\begin{${opts.matrix}} +${trimmed} +\end{${opts.matrix}}`; } - if (opts.cases && !trimmed.startsWith("\\begin{cases}")) { - return `\\begin{cases}\n${trimmed}\n\\end{cases}`; + if (opts.cases && !trimmed.startsWith(String.raw`\begin{cases}`)) { + return String.raw`\begin{cases} +${trimmed} +\end{cases}`; } - if (opts.aligned && !trimmed.startsWith("\\begin{aligned}")) { - return `\\begin{aligned}\n${trimmed}\n\\end{aligned}`; + if (opts.aligned && !trimmed.startsWith(String.raw`\begin{aligned}`)) { + return String.raw`\begin{aligned} +${trimmed} +\end{aligned}`; } - if (opts.gathered && !trimmed.startsWith("\\begin{gathered}")) { - return `\\begin{gathered}\n${trimmed}\n\\end{gathered}`; + if (opts.gathered && !trimmed.startsWith(String.raw`\begin{gathered}`)) { + return String.raw`\begin{gathered} +${trimmed} +\end{gathered}`; } return trimmed; @@ -36,29 +47,44 @@ function getFormattedMath( describe("MathBlock LaTeX Environment Wrappers", () => { it("wraps multi-line expression in aligned environment", () => { - const raw = "y_{ZI}(t) &= e^{-2t} \\\\\ny_{ZS}(t) &= e^{-3t}"; + const raw = String.raw`y_{ZI}(t) &= e^{-2t} \\ +y_{ZS}(t) &= e^{-3t}`; const res = getFormattedMath(raw, { aligned: true }); expect(res).toBe( - "\\begin{aligned}\ny_{ZI}(t) &= e^{-2t} \\\\\ny_{ZS}(t) &= e^{-3t}\n\\end{aligned}", + String.raw`\begin{aligned} +y_{ZI}(t) &= e^{-2t} \\ +y_{ZS}(t) &= e^{-3t} +\end{aligned}`, ); }); it("wraps piecewise expressions in cases environment", () => { - const raw = "e^{-at} & t \\ge 0 \\\\\n0 & t < 0"; + const raw = String.raw`e^{-at} & t \ge 0 \\ +0 & t < 0`; const res = getFormattedMath(raw, { cases: true }); expect(res).toBe( - "\\begin{cases}\ne^{-at} & t \\ge 0 \\\\\n0 & t < 0\n\\end{cases}", + String.raw`\begin{cases} +e^{-at} & t \ge 0 \\ +0 & t < 0 +\end{cases}`, ); }); it("wraps matrix expressions in bmatrix environment", () => { - const raw = "1 & 0 \\\\\n0 & 1"; + const raw = String.raw`1 & 0 \\ +0 & 1`; const res = getFormattedMath(raw, { matrix: "bmatrix" }); - expect(res).toBe("\\begin{bmatrix}\n1 & 0 \\\\\n0 & 1\n\\end{bmatrix}"); + expect(res).toBe(String.raw`\begin{bmatrix} +1 & 0 \\ +0 & 1 +\end{bmatrix}`); }); it("prevents duplicate environment wrapping if already wrapped", () => { - const raw = "\\begin{aligned}\na &= b \\\\\nc &= d\n\\end{aligned}"; + const raw = String.raw`\begin{aligned} +a &= b \\ +c &= d +\end{aligned}`; const res = getFormattedMath(raw, { aligned: true }); expect(res).toBe(raw); }); diff --git a/tests/unit/mathtext.test.ts b/tests/unit/mathtext.test.ts index 9f396c00..0e2d491c 100644 --- a/tests/unit/mathtext.test.ts +++ b/tests/unit/mathtext.test.ts @@ -188,16 +188,19 @@ describe("MathText Parser and KaTeX Compilation", () => { expect(rendered).toContain('class="katex"'); }); - it("defensively compiles standalone un-enclosed LaTeX macros like \\text{s} or \\text{rad/s}", () => { - const text = "Ensure units are \\text{s} and \\text{rad/s}."; - const rendered = renderFormattedMathText(text); - const matches = rendered.match(/class="katex"/g); - expect(matches?.length).toBe(2); - expect(rendered).toContain( - 's', - ); - expect(rendered).toContain( - 'rad/s', - ); - }); + it( + String.raw`defensively compiles standalone un-enclosed LaTeX macros like \text{s} or \text{rad/s}`, + () => { + const text = String.raw`Ensure units are \text{s} and \text{rad/s}.`; + const rendered = renderFormattedMathText(text); + const matches = rendered.match(/class="katex"/g); + expect(matches?.length).toBe(2); + expect(rendered).toContain( + 's', + ); + expect(rendered).toContain( + 'rad/s', + ); + }, + ); }); diff --git a/tests/unit/ode-choice-regressions.test.ts b/tests/unit/ode-choice-regressions.test.ts index e0515448..c726d2ba 100644 --- a/tests/unit/ode-choice-regressions.test.ts +++ b/tests/unit/ode-choice-regressions.test.ts @@ -269,7 +269,7 @@ describe("ODE teaching choice regressions", () => { type: "sinusoid" as const, K: 8, omega: 2, - latex: "8\\cos(2t)", + latex: String.raw`8\cos(2t)`, }, }, ]; diff --git a/tests/unit/ode-formatting-helpers.test.ts b/tests/unit/ode-formatting-helpers.test.ts index d9d98757..022bc5ef 100644 --- a/tests/unit/ode-formatting-helpers.test.ts +++ b/tests/unit/ode-formatting-helpers.test.ts @@ -67,7 +67,7 @@ describe("ODE Response Formatting & Root Matching Helpers", () => { roots: { r1: -2, im: 4 }, }; expect(formatHomogeneousResponse("C_1", "C_2", params)).toBe( - "e^{-2t} [C_1 \\cos(4t) + C_2 \\sin(4t)]", + String.raw`e^{-2t} [C_1 \cos(4t) + C_2 \sin(4t)]`, ); }); @@ -81,7 +81,7 @@ describe("ODE Response Formatting & Root Matching Helpers", () => { roots: { r1: 0, im: 3 }, }; expect(formatHomogeneousResponse("C_1", "C_2", params)).toBe( - "C_1 \\cos(3t) + C_2 \\sin(3t)", + String.raw`C_1 \cos(3t) + C_2 \sin(3t)`, ); }); diff --git a/tests/unit/ode-its-generator.test.ts b/tests/unit/ode-its-generator.test.ts index 794d9fa2..e81ba26d 100644 --- a/tests/unit/ode-its-generator.test.ts +++ b/tests/unit/ode-its-generator.test.ts @@ -117,8 +117,8 @@ describe("Linear ODE ITS Step Generator Engine", () => { const correctAnsatz = problem.itsData.step4.options.find( (o) => o.isCorrect, ); - expect(correctAnsatz?.latex).toContain("\\cos"); - expect(correctAnsatz?.latex).toContain("\\sin"); + expect(correctAnsatz?.latex).toContain(String.raw`\cos`); + expect(correctAnsatz?.latex).toContain(String.raw`\sin`); // Step 5 expect(problem.itsData.step5.expectedA).toBeDefined(); @@ -417,13 +417,15 @@ describe("Linear ODE ITS Step Generator Engine", () => { homogeneousComplete: { latex: "", C1: 2, eval: () => 0 }, homogeneousZI: { latex: "", C1: 2, eval: () => 0 }, homogeneousZS: { latex: "", C1: 0, eval: () => 0 }, - ziLatex: "2 e^{-t} \\cos(t)", + ziLatex: String.raw`2 e^{-t} \cos(t)`, zsLatex: "2", - y_tr_latex: "2 e^{-t} \\cos(t)", + y_tr_latex: String.raw`2 e^{-t} \cos(t)`, y_ss_latex: "2", random: () => 0.5, }); - expect(s7Complex.step7Data.expectedZI).toBe("2 e^{-t} \\cos(t)"); + expect(s7Complex.step7Data.expectedZI).toBe( + String.raw`2 e^{-t} \cos(t)`, + ); }); }); }); diff --git a/tests/unit/ode-solver-state.test.ts b/tests/unit/ode-solver-state.test.ts index 5c889011..fc81c6d4 100644 --- a/tests/unit/ode-solver-state.test.ts +++ b/tests/unit/ode-solver-state.test.ts @@ -65,25 +65,27 @@ describe("ODE Solver State Previews & Dev Helpers", () => { it("formats quadratic formula substitutions", () => { const setup = derivePreviewQuadSetup(1, 5, 6); expect(setup).toContain( - "s = \\frac{-(5) \\pm \\sqrt{(5)^2 - 4(1)(6)}}{2(1)}", + String.raw`s = \frac{-(5) \pm \sqrt{(5)^2 - 4(1)(6)}}{2(1)}`, ); - expect(setup).toContain("\\frac{-5 \\pm \\sqrt{1}}{2}"); + expect(setup).toContain(String.raw`\frac{-5 \pm \sqrt{1}}{2}`); }); it("handles negative coefficients with correct discriminant", () => { const setup = derivePreviewQuadSetup(1, -4, 13); - expect(setup).toContain("\\frac{4 \\pm \\sqrt{-36}}{2}"); + expect(setup).toContain(String.raw`\frac{4 \pm \sqrt{-36}}{2}`); }); }); describe("derivePreviewComplexRoots", () => { it("formats complex roots preview with given sigma and omegaD", () => { - expect(derivePreviewComplexRoots("-2", "3")).toBe("s = -2 \\pm j3"); + expect(derivePreviewComplexRoots("-2", "3")).toBe( + String.raw`s = -2 \pm j3`, + ); }); it("falls back to Greek symbols when empty", () => { expect(derivePreviewComplexRoots("", "")).toBe( - "s = \\sigma \\pm j\\omega_d", + String.raw`s = \sigma \pm j\omega_d`, ); }); }); diff --git a/tests/unit/ode-step-solver-validation.test.ts b/tests/unit/ode-step-solver-validation.test.ts index b61147d5..bdf56d3c 100644 --- a/tests/unit/ode-step-solver-validation.test.ts +++ b/tests/unit/ode-step-solver-validation.test.ts @@ -743,8 +743,8 @@ describe("OdeStepSolverState Input Validation & Misconceptions", () => { const ccSolver = new OdeStepSolverState(() => ccProblem); ccSolver.step7.ziC1 = "1"; ccSolver.step7.ziC2 = "2"; - expect(ccSolver.previewZI).toContain("\\cos"); - expect(ccSolver.previewZI).toContain("\\sin"); + expect(ccSolver.previewZI).toContain(String.raw`\cos`); + expect(ccSolver.previewZI).toContain(String.raw`\sin`); expect(ccSolver.previewZS).toBeDefined(); const distinctProblem = generateSecondOrderProblem( diff --git a/tests/unit/odes-solver.test.ts b/tests/unit/odes-solver.test.ts index b1796d22..eeb9e9a9 100644 --- a/tests/unit/odes-solver.test.ts +++ b/tests/unit/odes-solver.test.ts @@ -249,14 +249,14 @@ describe("LCC ODE Analytical Math Engine", () => { type: "sinusoid", K: 10, omega: 2, - latex: "10 \\cos(2t)", + latex: String.raw`10 \cos(2t)`, }); expect(particular.coeffs.A).toBe(-0.5); expect(particular.coeffs.B).toBe(1.5); expect(particular.eval(0)).toBe(-0.5); expect(particular.evalDeriv(0)).toBe(1.5 * 2); expect(particular.latex).toBe( - "-\\frac{1}{2} \\cos(2t) + \\frac{3}{2} \\sin(2t)", + String.raw`-\frac{1}{2} \cos(2t) + \frac{3}{2} \sin(2t)`, ); }); @@ -282,10 +282,12 @@ describe("LCC ODE Analytical Math Engine", () => { type: "sinusoid", K: 10, omega: 2, - latex: "10 \\cos(2t)", + latex: String.raw`10 \cos(2t)`, }); expect(particular.coeffs.B).toBe(-1.5); - expect(particular.latex).toContain("- \\frac{3}{2} \\sin(2t)"); + expect(particular.latex).toContain( + String.raw`- \frac{3}{2} \sin(2t)`, + ); }); /** @@ -306,13 +308,13 @@ describe("LCC ODE Analytical Math Engine", () => { type: "sinusoid", K: 8, omega: 2, - latex: "8 \\cos(2t)", + latex: String.raw`8 \cos(2t)`, }); expect(particular.resonanceMultiplicity).toBe(1); expect(particular.coeffs.B).toBe(2); expect(particular.eval(0)).toBe(0); expect(particular.evalDeriv(0)).toBe(0); - expect(particular.latex).toBe("2 t \\sin(2t)"); + expect(particular.latex).toBe(String.raw`2 t \sin(2t)`); }); /** @@ -332,7 +334,7 @@ describe("LCC ODE Analytical Math Engine", () => { type: "sinusoid", K: 5, omega: 1, - latex: "5 \\cos(t)", + latex: String.raw`5 \cos(t)`, }), ).toThrow("First-order leading coefficient a1 must be non-zero"); }); @@ -447,7 +449,9 @@ describe("LCC ODE Analytical Math Engine", () => { expect(sol.eval(1)).toBeCloseTo( Math.exp(-1) * (2 * Math.cos(2) + 3 * Math.sin(2)), ); - expect(sol.latex).toBe("e^{-t} [2 \\cos(2t) + 3 \\sin(2t)]"); + expect(sol.latex).toBe( + String.raw`e^{-t} [2 \cos(2t) + 3 \sin(2t)]`, + ); }); }); }); diff --git a/tests/unit/transform-notation.test.ts b/tests/unit/transform-notation.test.ts index f37d832c..f74b061c 100644 --- a/tests/unit/transform-notation.test.ts +++ b/tests/unit/transform-notation.test.ts @@ -47,7 +47,7 @@ function prefix( const name = variable === "t" ? "x" : "X"; const left = square ? "[" : "(", right = square ? "]" : ")"; - return `${name}${space}${sized ? "\\left" : ""}${left}${space}${variable}${space}${sized ? "\\right" : ""}${right}${space}=${space}`; + return String.raw`${name}${space}${sized ? String.raw`\left` : ""}${left}${space}${variable}${space}${sized ? String.raw`\right` : ""}${right}${space}=${space}`; } /** @@ -212,13 +212,13 @@ describe("transform notation properties", () => { fc.property( fc.constantFrom("t" as const, "omega" as const), fc.constantFrom( - "X\\left(omega)=1", - "X\\left(omega\\right]=1", + String.raw`X\left(omega)=1`, + String.raw`X\left(omega\right]=1`, "x(t)=1=1", "1+(2]", - "\\frac{1}{", + String.raw`\frac{1}{`, "X\\leftarrow(omega)=1", - "\\left.1\\right)", + String.raw`\left.1\right)`, "(1,1)", "X(garbage)=1", String.raw`\leftpi/pi`, diff --git a/tests/unit/ui-components.test.ts b/tests/unit/ui-components.test.ts index c83ad8a1..7aabdea2 100644 --- a/tests/unit/ui-components.test.ts +++ b/tests/unit/ui-components.test.ts @@ -280,7 +280,7 @@ describe("HintDisclosure — disabled/allRevealed state derivation", () => { describe("HintDisclosure — hints slice derivation", () => { const hints = [ "Identify the symmetry of $x(t)$.", - "Apply the Fourier integral formula $a_n = \\frac{2}{T_0}\\int$.", + String.raw`Apply the Fourier integral formula $a_n = \frac{2}{T_0}\int$.`, "Substitute and evaluate at boundary values.", ];