1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
import katex from 'katex';
import 'katex/dist/katex.min.css';
const options = { output: 'htmlAndMathml', throwOnError: false, strict: 'error', trust: false } as const;
/** Render authored TeX with bundled fonts and a MathML equivalent for assistive technology. */
export function renderEquation(element: HTMLElement, tex: string) {
element.classList.add('math-display');
element.tabIndex = 0; // Long equations can be scrolled with the keyboard on narrow screens.
katex.render(tex, element, { ...options, displayMode: true });
}
/** Plain prose with explicit $...$ inline math; everything outside delimiters stays text. */
export function renderProse(element: HTMLElement, text: string) {
element.replaceChildren();
let offset = 0;
for (const match of text.matchAll(/\$([^$\n]+)\$/g)) {
element.append(document.createTextNode(text.slice(offset, match.index)));
const math = document.createElement('span');
katex.render(match[1], math, { ...options, displayMode: false });
element.append(math);
offset = match.index + match[0].length;
}
element.append(document.createTextNode(text.slice(offset)));
}
// Short UI labels retain their plain accessible names while sharing the lesson notation.
const notation: Record<string, string> = {
'log₁₀(N / m⁻³)': String.raw`\log_{10}(N/\mathrm m^{-3})`,
'EF − Ei': 'E_F-E_i', 'U₁₂₃': 'U_{123}', 'ΔU₀': String.raw`\Delta U_0`,
'K + U': 'K+U', 'q₀': 'q_0', 'q₁': 'q_1', 'q₂': 'q_2', 'q₃': 'q_3',
'Uₐ': 'U_a', 'Uᵦ': 'U_b', 'Kₐ': 'K_a', 'rₐ': 'r_a', 'rᵦ': 'r_b',
'θₐ': String.raw`\theta_a`, 'θᵦ': String.raw`\theta_b`, 'τz': String.raw`\tau_z`,
'|Q|': '|Q|', '|P|': '|P|', '|E|': String.raw`|\vec E|`, 'Ex': 'E_x',
'Δx': String.raw`\Delta x`, 'θ': String.raw`\theta`, 'α': String.raw`\alpha`,
'κ': String.raw`\kappa`, 'σ': String.raw`\sigma`, '90°': String.raw`90^\circ`,
};
const notationPattern = new RegExp(Object.keys(notation).sort((a, b) => b.length - a.length).map(key => key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|') + '|\\b[EqdnpUVK]\\b', 'g');
export function renderNotation(element: HTMLElement, text: string) {
renderProse(element, text.replace(notationPattern, token => `$${notation[token] ?? token}$`));
}
|