rapier-math 2.3.0 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,172 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Typesetting faults, each with its reproducer. Where the TeXbook's Appendix G decides, the expected
3
+ // value is LuaTeX's own output for the same formula (unicode-math, Latin Modern Math 1.959), in ems.
4
+ // Replay: node tests/typeset.mjs [package-root]. Ink is measured from the font's own contour strips.
5
+ import assert from 'node:assert/strict';
6
+ import {dirname, resolve} from 'node:path';
7
+ import {fileURLToPath, pathToFileURL} from 'node:url';
8
+
9
+ const root = resolve(process.argv[2] || resolve(dirname(fileURLToPath(import.meta.url)), '..'));
10
+ const load = file => import(pathToFileURL(resolve(root, 'src/math', file)).href);
11
+ const {MATH_FONT} = await load('font.js'), L = await load('layout.js');
12
+ const {mathPrepare} = await load('source.js'), {mathToMathML} = await load('semantic-api.js'), {renderMath} = await load('api.js');
13
+ const context = (display = false) => ({size: 1, level: 0, variant: 'normal', cramped: false, display, cache: new WeakMap(), budget: {nodes: 0, outlineBytes: 0}});
14
+ function layout(tex, display = false) {
15
+ const {tree, error} = mathPrepare(tex);
16
+ assert(!error, tex + ': ' + error?.message);
17
+ return L.mathLayout(tree, context(display));
18
+ }
19
+ const mathml = tex => mathToMathML(tex).mathml;
20
+
21
+ // Every outline in an SVG fragment: its glyph, origin and scale, from the transforms that place it.
22
+ const paths = new Map();
23
+ function glyphOf(d) {
24
+ if (!paths.size) for (let id = 0, g; (g = MATH_FONT.glyph(id)); id++) { if (g?.[7] && !paths.has(g[7])) paths.set(g[7], id); }
25
+ return paths.get(d);
26
+ }
27
+ function glyphs(svg) {
28
+ const found = [], stack = [[0, 0, 1, 1]];
29
+ for (const [tag] of svg.matchAll(/<\/?g\b[^>]*>|<path\b[^>]*>/g)) {
30
+ if (tag === '</g>') { stack.pop(); continue; }
31
+ const [x, y, sx, sy] = stack.at(-1), t = /translate\(([-\d.e]+) ([-\d.e]+)\)/.exec(tag), s = /scale\(([-\d.e]+) ([-\d.e]+)\)/.exec(tag);
32
+ let next = [x, y, sx, sy];
33
+ if (tag.startsWith('<g')) {
34
+ if (t) next = [x + sx * +t[1], y + sy * +t[2], sx, sy];
35
+ if (s) next = [next[0], next[1], sx * +s[1], sy * +s[2]];
36
+ stack.push(next);
37
+ } else {
38
+ const d = /\bd="([^"]+)"/.exec(tag)?.[1], id = d && glyphOf(d);
39
+ if (id !== undefined && s) found.push({id, x, y, sx: sx * +s[1], sy: sy * -s[2]});
40
+ }
41
+ }
42
+ return found;
43
+ }
44
+ // Horizontal ink strips of a placed glyph (its contour profile; its bounds when unprofiled).
45
+ function strips({id, x, y, sx, sy}) {
46
+ const g = MATH_FONT.glyph(id), p = MATH_FONT.profile(id), out = [];
47
+ if (!p) return [{top: y - g[4] * sy, bottom: y - g[2] * sy, left: x + g[1] * sx, right: x + g[3] * sx}];
48
+ for (let i = 1; i < p.length; i++) if (p[i])
49
+ out.push({top: y - (p[0] + i * MATH_FONT.edgeStep) * sy, bottom: y - (p[0] + (i - 1) * MATH_FONT.edgeStep) * sy, left: x + p[i][0] * sx, right: x + p[i][1] * sx});
50
+ return out;
51
+ }
52
+ // Smallest horizontal gap between two glyphs' ink where they share a height; negative when the ink overlaps.
53
+ function inkGap(a, b) {
54
+ let gap = Infinity;
55
+ for (const s of strips(a)) for (const t of strips(b))
56
+ if (s.top < t.bottom && t.top < s.bottom) gap = Math.min(gap, Math.max(t.left - s.right, s.left - t.right) <= 0 ? -Math.min(s.right - t.left, t.right - s.left) : Math.max(t.left - s.right, s.left - t.right));
57
+ return gap;
58
+ }
59
+ const ink = item => strips(item).reduce((r, s) => ({left: Math.min(r.left, s.left), right: Math.max(r.right, s.right), top: Math.min(r.top, s.top), bottom: Math.max(r.bottom, s.bottom)}), {left: Infinity, right: -Infinity, top: Infinity, bottom: -Infinity});
60
+ const near = (actual, expected, message, tolerance = 0.01) => assert(Math.abs(actual - expected) <= tolerance, message + ': ' + actual.toFixed(3) + ' (TeX ' + expected + ')');
61
+
62
+ const cells = [];
63
+ const cell = (id, claim, check) => cells.push({id, claim, check});
64
+
65
+ cell('F1', 'a superscript clears an over-accent', () => {
66
+ for (const tex of [String.raw`\hat{i}^2`, String.raw`\vec{x}^2`, String.raw`\tilde{\jmath}^2`, String.raw`\dot{x}^n`]) {
67
+ const [, accent, script] = glyphs(layout(tex).svg);
68
+ assert(inkGap(accent, script) > 0, tex + ': superscript ink meets the accent');
69
+ }
70
+ // TeX's rule 18a keeps \hat{x}^2 where x^2 is.
71
+ near(glyphs(layout(String.raw`\hat{x}^2`).svg)[2].x, glyphs(layout('x^2').svg)[1].x, String.raw`\hat{x}^2 script`, 0.08);
72
+ });
73
+ cell('F2', 'a subscript keeps the slanted letter clear of the next', () => {
74
+ for (const tex of ['V_i H', 'V_i T', 'W_i Y']) {
75
+ const items = glyphs(layout(tex).svg);
76
+ assert(inkGap(items[0], items.at(-1)) >= 0, tex + ': the next letter meets the slanted letter');
77
+ }
78
+ });
79
+ cell('F3', 'an under-accent adds only its own depth', () => {
80
+ assert(layout(String.raw`\utilde{x}`).d <= 0.492, String.raw`\utilde{x} depth exceeds TeX's 0.492`);
81
+ assert(layout(String.raw`\underaccent{\bar}{x}`).d <= 0.439, String.raw`\underaccent{\bar}{x} depth exceeds TeX's 0.439`);
82
+ });
83
+ cell('F4', 'braces centre on slanted letters', () => {
84
+ const over = glyphs(layout(String.raw`\overbrace{f}`, true).svg), f = over.find(item => item.id === MATH_FONT.chars[0x1d453]);
85
+ const middle = item => (ink(item).left + ink(item).right) / 2;
86
+ near(middle(over.find(item => item !== f)) - f.x, layout('f', true).w / 2, String.raw`\overbrace{f} brace centre`, 0.01);
87
+ const v = layout(String.raw`\underbrace{V}_n`, true), items = glyphs(v.svg), n = items.at(-1), nW = MATH_FONT.glyph(n.id)[0] * n.sx;
88
+ const vItem = items.find(item => item.id === MATH_FONT.chars[0x1d449]);
89
+ near(n.x + nW / 2 - vItem.x, layout('V', true).w / 2, String.raw`\underbrace{V}_n label centre`, 0.01);
90
+ });
91
+ cell('F5', 'a radical degree kerns into the sign', () => {
92
+ const sign = glyphs(layout(String.raw`\sqrt[3]{x}`).svg).find(item => item.id === MATH_FONT.chars[0x221a]);
93
+ near(sign.x, 0.062, String.raw`\sqrt[3]{x} sign x`, 0.003);
94
+ });
95
+ cell('F6', 'corner delimiters sit where TeX puts them', () => {
96
+ const items = glyphs(layout(String.raw`\left\ulcorner\frac{a}{b}\right\urcorner`, true).svg);
97
+ near(items[0].y, 0.135, String.raw`\ulcorner origin y`);
98
+ const low = glyphs(layout(String.raw`\left\llcorner\frac{a}{b}\right\lrcorner`, true).svg);
99
+ near(low[0].y, -0.380, String.raw`\llcorner origin y`);
100
+ });
101
+ cell('F7', 'starred cases set conditions as text', () => {
102
+ const {tree, error} = mathPrepare(String.raw`\begin{cases*} x & if $x > 0$ \\ 0 & otherwise \end{cases*}`);
103
+ assert(!error, 'cases*: ' + error?.message);
104
+ const condition = JSON.stringify(tree.children[0].body ?? tree.children[0]);
105
+ assert(/"type":"text","value":"if/.test(condition) && /"value":"otherwise"/.test(condition), 'cases* condition is text');
106
+ });
107
+ cell('F8', 'mhchem isotopes', () => {
108
+ const {tree, error} = mathPrepare(String.raw`\ce{^{235}_{92}U + ^1_0n}`);
109
+ assert(!error);
110
+ assert(!/"base":\{"type":"glyph","value":"\+"/.test(JSON.stringify(tree)), String.raw`\ce: the scripts before n stay on n, not on +`);
111
+ const items = glyphs(layout(String.raw`\ce{^{235}_{92}U}`).svg), right = item => item.x + MATH_FONT.glyph(item.id)[0] * item.sx;
112
+ near(right(items[2]), right(items[4]), String.raw`\ce isotope scripts end together (TeX)`, 0.002);
113
+ });
114
+ cell('F9', 'bold digits and bold dotless letters', () => {
115
+ assert.equal(layout(String.raw`\boldsymbol{0}`).glyph, MATH_FONT.chars[0x1d7ce], String.raw`\boldsymbol{0} is a bold digit`);
116
+ assert.equal(layout(String.raw`\bm{1}`).glyph, MATH_FONT.chars[0x1d7cf], String.raw`\bm{1} is a bold digit`);
117
+ assert.equal(layout(String.raw`\boldsymbol{\imath}`).glyph, MATH_FONT.dotless[MATH_FONT.chars[0x1d48a]], String.raw`\boldsymbol{\imath} is bold dotless`);
118
+ assert.equal(layout(String.raw`\mathbf{\jmath}`).glyph, MATH_FONT.dotless[MATH_FONT.chars[0x1d423]], String.raw`\mathbf{\jmath} is bold dotless`);
119
+ });
120
+ cell('F10', 'binary and fraction spacing, matrix cells', () => {
121
+ near(layout(String.raw`a\boldsymbol{+}b`).w, 2.180, String.raw`a\boldsymbol{+}b width`, 0.002);
122
+ near(layout(String.raw`a\textcolor{red}{+}b`).w, 1.736, String.raw`a\textcolor{red}{+}b width (a braced group is ordinary)`, 0.002);
123
+ const f = layout(String.raw`\frac{1}{2},`);
124
+ near(f.rowItems[1][1] - f.rowItems[0][0].w, 0, String.raw`\frac{1}{2}, space before the comma`, 0.002);
125
+ const cramped = layout(String.raw`\frac{1}{\begin{matrix}x^2\end{matrix}}`, true), plain = layout(String.raw`\begin{matrix}x^2\end{matrix}`);
126
+ near(glyphs(cramped.svg).at(-1).y - glyphs(cramped.svg).at(-2).y, glyphs(plain.svg).at(-1).y - glyphs(plain.svg).at(-2).y, 'matrix cell superscript rise inside a denominator', 0.001);
127
+ });
128
+ cell('F11', 'MathML Core attributes', () => {
129
+ assert(!/movablelimits="false">max/.test(mathml(String.raw`\overline{A_{\max}}`)), String.raw`\max in a script keeps its own limits`);
130
+ assert(/<mtable displaystyle="true"[^>]*data-math-environment="darray"/.test(mathml(String.raw`\begin{darray}{c}x\end{darray}`)), 'darray is display style');
131
+ assert(/<mi[^>]*>℧<\/mi><mi[^>]*>⅁<\/mi>/.test(mathml(String.raw`\mho\Game`)), String.raw`\mho and \Game are identifiers`);
132
+ assert(!/form="infix"[^>]*>\+/.test(mathml('(a+)')), 'a trailing plus is not infix');
133
+ });
134
+ cell('F12', 'colour paints once; a fence without \\middle lays out once', () => {
135
+ const svg = renderMath(String.raw`\color{red}a+b+c=1+2+3`, {maxWidth: 3}).svg;
136
+ assert(!/<g fill="red"[^>]*><g fill="red"/.test(svg), 'colour is painted twice');
137
+ const {tree} = mathPrepare(String.raw`\left(a+b\right)`), c = context();
138
+ L.mathLayout(tree, c);
139
+ const {tree: body} = mathPrepare('(a+b)'), d = context();
140
+ L.mathLayout(body, d);
141
+ assert(c.budget.nodes <= d.budget.nodes, 'fence body laid out twice: ' + c.budget.nodes + ' visits for ' + d.budget.nodes);
142
+ });
143
+ cell('F13', 'what people write most', () => {
144
+ const inputs = [String.raw`\SI{9.81}{m.s^{-2}}`, String.raw`\SI{3}{\kilo\gram\metre\per\second\squared}`, String.raw`\num{12345.678}`, String.raw`\si{\ohm}`, String.raw`\unit{\micro\metre}`, String.raw`\ang{30;15;10}`,
145
+ String.raw`\mel{n}{H}{m}`, String.raw`\ev{x}`, String.raw`\ip{a}{b}`, String.raw`\op{a}{b}`, String.raw`\pb{f}{g}`, String.raw`\qq{if}`, String.raw`\qc`, String.raw`\Res`,
146
+ String.raw`\idotsint`, String.raw`\smashoperator{\sum_{i=1}^n}`, String.raw`\begin{multlined}a\\b\end{multlined}`, String.raw`\begin{lgathered}a\\b\end{lgathered}`, String.raw`\begin{rgathered}a\\b\end{rgathered}`,
147
+ String.raw`\mathmakebox[2em][l]{x}`, String.raw`\not\in`, String.raw`\not\subset`];
148
+ const rejected = inputs.filter(tex => mathPrepare(tex).error);
149
+ assert.deepEqual(rejected, [], 'rejected');
150
+ });
151
+
152
+ cell('P1', 'a formula being typed previews without an error', () => {
153
+ for (const tex of [String.raw`\frac{-b\pm\sqrt{b^2-4ac}}{2a}`, String.raw`\begin{pmatrix}1 & 2\\3 & 4\end{pmatrix}`, String.raw`\left(x+1\right)^{\sqrt[3]{y}}`])
154
+ for (let i = 1; i <= tex.length; i++) {
155
+ const prefix = tex.slice(0, i), result = renderMath(prefix, {preview: true});
156
+ assert.deepEqual(result.errors, [], 'preview of ' + prefix);
157
+ assert(result.svg.includes('<title>' + prefix.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</title>'), 'exact source of ' + prefix);
158
+ }
159
+ for (const [tex, caret] of [[String.raw`\sqrt{x^}`, 8], [String.raw`\sqrt{x+\}`, 9], [String.raw`a+\fra{}`, 6]])
160
+ assert.deepEqual(renderMath(tex, {preview: true, caret}).errors, [], 'preview at the caret of ' + tex);
161
+ assert.equal(renderMath(String.raw`\frac{1}{`).errors.length, 1, 'strict rendering is unchanged');
162
+ assert.equal(renderMath(String.raw`\frac{a}{b} \farc + 1`, {preview: true}).errors[0]?.suggestion, String.raw`\frac`, 'a fault before the end stays, with a suggestion');
163
+ });
164
+
165
+ const results = [];
166
+ for (const {id, claim, check} of cells) {
167
+ try { check(); results.push([id, 'green', claim]); }
168
+ catch (error) { results.push([id, 'red', claim + ': ' + error.message]); }
169
+ }
170
+ for (const row of results) console.log(row.join('\t'));
171
+ assert(results.every(row => row[1] === 'green'), 'red cells');
172
+ console.log(JSON.stringify({cells: results.length, typesetting: 'TeX where Appendix G decides'}));