rapier-math 2.0.0 → 2.1.0
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.
- package/README.md +15 -5
- package/dist/accessible.css +6 -0
- package/dist/accessible.d.ts +10 -0
- package/dist/accessible.mjs +18 -0
- package/dist/classic.d.ts +8 -2
- package/dist/combined.d.ts +4 -0
- package/dist/combined.mjs +2 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.mjs +6 -2980
- package/dist/integration.d.ts +3 -1
- package/dist/integration.mjs +13 -19
- package/dist/markdown-it.mjs +7 -4
- package/dist/mathml.d.ts +5 -0
- package/dist/mathml.mjs +3 -0
- package/dist/rapier-math.js +595 -143
- package/dist/rehype.mjs +13 -3
- package/docs/api.md +38 -2
- package/docs/math-components.json +6 -5
- package/docs/math-resources.json +150 -54
- package/docs/semantics.md +228 -0
- package/examples/README.md +10 -0
- package/examples/accessible.html +27 -0
- package/examples/accessible.mjs +42 -0
- package/examples/semantic.mjs +11 -0
- package/package.json +16 -2
- package/src/math/api.js +16 -55
- package/src/math/browser.js +4 -0
- package/src/math/classic.js +7 -0
- package/src/math/combined.js +13 -0
- package/src/math/fallbacks.js +5 -0
- package/src/math/font.js +3 -0
- package/src/math/layout.js +6 -37
- package/src/math/mathml.js +406 -0
- package/src/math/package-build.mjs +24 -11
- package/src/math/package-layout.mjs +3 -0
- package/src/math/package-readme.mjs +14 -4
- package/src/math/parser.js +14 -11
- package/src/math/responsive.js +4 -0
- package/src/math/semantic-api.js +12 -0
- package/src/math/source.js +67 -0
- package/src/math/symbols.js +3 -0
- package/src/math/variants.js +41 -0
- package/src/tools/build-math.mjs +19 -10
- package/tests/adoption.mjs +34 -0
- package/tests/check.mjs +13 -5
- package/tests/semantics.mjs +340 -0
- package/tests/verify.mjs +3 -3
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// One bounded walk of the admitted TeX tree. This is Presentation MathML, not a
|
|
3
|
+
// second grammar, a content-math inference engine or a public AST input API.
|
|
4
|
+
const MATH_ML_OPAQUE_COLOR = /^(?:aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen)$/i;
|
|
5
|
+
const MATH_ML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
|
|
6
|
+
const MATH_ML_INVALID_XML = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\ud800-\udfff\ufffe\uffff]/u;
|
|
7
|
+
function mathMLXML(value) {
|
|
8
|
+
const text = String(value);
|
|
9
|
+
if (MATH_ML_INVALID_XML.test(text))
|
|
10
|
+
throw {code: 'invalid-semantic-character', offset: 0, message: 'A generated mathematical character is not valid XML.'};
|
|
11
|
+
return text.replace(/[&<>"'\t\n\r]/g, character => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '\t': '	', '\n': ' ', '\r': ' '}[character]));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function mathML(tree, source, safeSource, options = {}) {
|
|
15
|
+
const metrics = {nodes: 0, depth: 0, outputCodeUnits: 0, links: 0};
|
|
16
|
+
const diagnostics = [], codes = new Set(), active = new WeakSet();
|
|
17
|
+
const sourceOmitted = source.length > 1000000 || !!safeSource?.error?.sourceOmitted;
|
|
18
|
+
// HAST stringifiers can emit decoded CR literally; a subsequent HTML parse
|
|
19
|
+
// normalizes it. ASCII custody survives that real host pipeline unchanged.
|
|
20
|
+
const utf16 = sourceOmitted ? null : (safeSource?.utf16 ?? null);
|
|
21
|
+
const encoding = sourceOmitted ? null : utf16 === null ? 'application/x-tex' : 'application/x-rapier-tex-utf16';
|
|
22
|
+
const sourceInfo = {encoding, ...(sourceOmitted ? {omitted: true} : {})};
|
|
23
|
+
let parts = [], length = 0, content = 0;
|
|
24
|
+
const fail = (code, message) => { throw {code, message, offset: 0}; };
|
|
25
|
+
const write = value => {
|
|
26
|
+
length += value.length;
|
|
27
|
+
if (length > 8 * 1024 * 1024) fail('resource-limit', 'MathML presentation exceeds its output budget.');
|
|
28
|
+
parts.push(value);
|
|
29
|
+
};
|
|
30
|
+
const open = (name, attributes = {}) => {
|
|
31
|
+
let value = '<' + name;
|
|
32
|
+
for (const [key, item] of Object.entries(attributes)) if (item !== undefined)
|
|
33
|
+
value += ' ' + key + '="' + mathMLXML(item) + '"';
|
|
34
|
+
write(value + '>');
|
|
35
|
+
};
|
|
36
|
+
const close = name => write('</' + name + '>');
|
|
37
|
+
const token = (name, value, attributes, context) => {
|
|
38
|
+
open(name, attributes); write(mathMLXML(value)); close(name);
|
|
39
|
+
if (!context?.phantom && !context?.transparent && /[^\p{White_Space}\p{Default_Ignorable_Code_Point}]/u.test(value)) content++;
|
|
40
|
+
};
|
|
41
|
+
const decimal = value => {
|
|
42
|
+
if (!Number.isFinite(value)) fail('invalid-semantic-value', 'A mathematical dimension is not finite.');
|
|
43
|
+
return String(Math.round(value * 1e6) / 1e6 || 0);
|
|
44
|
+
};
|
|
45
|
+
const em = value => decimal(value) + 'em';
|
|
46
|
+
const warn = (code, message) => {
|
|
47
|
+
if (!codes.has(code)) { codes.add(code); diagnostics.push({code, message, offset: 0}); }
|
|
48
|
+
};
|
|
49
|
+
const visit = (node, depth) => {
|
|
50
|
+
if (++metrics.nodes > 100000) fail('resource-limit', 'MathML traversal exceeds its work budget.');
|
|
51
|
+
metrics.depth = Math.max(metrics.depth, depth);
|
|
52
|
+
if (depth > 512) fail('resource-limit', 'MathML is nested too deeply.');
|
|
53
|
+
if (!node || typeof node !== 'object') fail('unsupported-semantic-node', 'A mathematical part is missing.');
|
|
54
|
+
};
|
|
55
|
+
const family = node => {
|
|
56
|
+
const role = node.semanticRole;
|
|
57
|
+
if (role === 'chemistry') warn('semantic-chemistry-presentation', 'Chemical notation retains presentation structure; chemical element, bond, charge and reaction meanings are not inferred.');
|
|
58
|
+
else if (role === 'physics') warn('semantic-physics-presentation', 'Physics notation retains its parsed mathematical relationships; physical and specialized operator meanings are not inferred.');
|
|
59
|
+
else if (role === 'units') warn('semantic-units-presentation', 'Unit notation retains the parser-expanded mathematical structure; quantities and unit identities are not inferred.');
|
|
60
|
+
else if (role === 'tag') warn('semantic-tag-presentation', 'An authored tag remains following content; no equation identity, numbering or cross-reference semantics are assigned.');
|
|
61
|
+
};
|
|
62
|
+
const scriptContext = context => ({...context, display: false, level: Math.min(2, context.level + 1)});
|
|
63
|
+
const styledContext = (context, node) => {
|
|
64
|
+
const next = {...context};
|
|
65
|
+
if (node.variant) next.variant = node.variant;
|
|
66
|
+
// Invalid names inherit the current color; they cannot prove visibility.
|
|
67
|
+
if (/^(?:transparent|#[\da-f]{3}0|#[\da-f]{6}00)$/i.test(node.color || '')) next.transparent = true;
|
|
68
|
+
else if (node.color && (/^#/.test(node.color) || MATH_ML_OPAQUE_COLOR.test(node.color))) next.transparent = false;
|
|
69
|
+
if (node.absoluteSize !== undefined) next.size = node.absoluteSize;
|
|
70
|
+
if (node.size !== undefined) next.size *= node.size;
|
|
71
|
+
if (node.mathStyle) { next.display = node.mathStyle === 'display'; next.level = {display: 0, text: 0, script: 1, scriptscript: 2}[node.mathStyle]; }
|
|
72
|
+
return next;
|
|
73
|
+
};
|
|
74
|
+
const variant = (node, context) => node.variant || (context.variant === 'normal' ? node.defaultVariant || (node.type === 'text' ? 'roman' : 'normal') : context.variant);
|
|
75
|
+
const styledText = (value, face) => {
|
|
76
|
+
// Native Core supports only mi mathvariant=normal. The shared pure Unicode
|
|
77
|
+
// mapping keeps mathematical alphabets meaningful without loading the font.
|
|
78
|
+
if (face === 'roman') return value;
|
|
79
|
+
let result = '';
|
|
80
|
+
for (const character of value) result += String.fromCodePoint(mathStyledCodePoint(character.codePointAt(0), face));
|
|
81
|
+
return result;
|
|
82
|
+
};
|
|
83
|
+
const atom = (node, value, kind, context, attributes = {}) => {
|
|
84
|
+
const face = variant(node, context);
|
|
85
|
+
if (kind === 'mtext') {
|
|
86
|
+
let css = '';
|
|
87
|
+
if (face.includes('bold')) css += 'font-weight:700;';
|
|
88
|
+
if (face.includes('italic')) css += 'font-style:italic;';
|
|
89
|
+
if (face.includes('sans-serif')) css += 'font-family:sans-serif;';
|
|
90
|
+
else if (face === 'monospace') css += 'font-family:monospace;';
|
|
91
|
+
if (/script|fraktur|double-struck/.test(face)) {
|
|
92
|
+
attributes.mathvariant = face;
|
|
93
|
+
warn('semantic-text-variant', 'This text alphabet uses the MathML 3 mathvariant extension; a Core host may show ordinary text while preserving the text content.');
|
|
94
|
+
}
|
|
95
|
+
if (css) attributes.style = css;
|
|
96
|
+
token(kind, value, attributes, context); return;
|
|
97
|
+
}
|
|
98
|
+
const styled = styledText(value, face);
|
|
99
|
+
if (kind === 'mo' && context.movableLimits !== undefined) attributes.movablelimits = String(context.movableLimits);
|
|
100
|
+
if (kind === 'mi' && face !== 'normal' && face !== 'italic') attributes.mathvariant = 'normal';
|
|
101
|
+
token(kind, styled, attributes, context);
|
|
102
|
+
};
|
|
103
|
+
const kind = node => node.tokenKind || (/^\p{Decimal_Number}+$/u.test(node.value) ? 'mn' : /^[∞∅ℵℶℷℸ]$/.test(node.value) ? 'mi' :
|
|
104
|
+
['op', 'bin', 'rel', 'open', 'close', 'punct', 'inner'].includes(node.class) ||
|
|
105
|
+
/^[\p{Sm}\p{P}\p{Sc}\p{So}\p{Sk}\u2061-\u2064]$/u.test(node.value) ? 'mo' : 'mi');
|
|
106
|
+
const classOf = node => {
|
|
107
|
+
if (!node) return undefined;
|
|
108
|
+
if (node.class) return node.class;
|
|
109
|
+
if (node.type === 'scripts' || node.type === 'accent') return classOf(node.base);
|
|
110
|
+
if (node.type === 'style' || node.type === 'link') return classOf(node.body);
|
|
111
|
+
if (node.type === 'row' && node.children.length === 1) return classOf(node.children[0]);
|
|
112
|
+
return 'ord';
|
|
113
|
+
};
|
|
114
|
+
const limitsOf = node => {
|
|
115
|
+
if (!node) return undefined;
|
|
116
|
+
if (node.limits) return node.limits;
|
|
117
|
+
if (node.type === 'style' || node.type === 'link') return limitsOf(node.body);
|
|
118
|
+
if (node.type === 'row' && node.children.length === 1) return limitsOf(node.children[0]);
|
|
119
|
+
if (node.type === 'accent') return limitsOf(node.base);
|
|
120
|
+
return undefined;
|
|
121
|
+
};
|
|
122
|
+
const plain = (node, depth, strict = false) => {
|
|
123
|
+
visit(node, depth); family(node);
|
|
124
|
+
if (strict && node.variant && node.variant !== 'roman') return null;
|
|
125
|
+
if (node.type === 'text' || !strict && node.type === 'glyph') return node.value;
|
|
126
|
+
if (node.type !== 'row') return null;
|
|
127
|
+
const values = [];
|
|
128
|
+
for (const child of node.children) {
|
|
129
|
+
const value = plain(child, depth + 1, strict);
|
|
130
|
+
if (value === null) return null;
|
|
131
|
+
values.push(value);
|
|
132
|
+
}
|
|
133
|
+
return values.join('');
|
|
134
|
+
};
|
|
135
|
+
const fence = (value, form, context, size) => {
|
|
136
|
+
if (value) token('mo', value, {fence: 'true', form, stretchy: 'true', symmetric: 'true', ...(size ? {minsize: em(size), maxsize: em(size)} : {})}, context);
|
|
137
|
+
};
|
|
138
|
+
const numberPart = node => node?.type === 'glyph' && !node.semanticRole && !node.tokenKind && !node.large && !node.delimiter &&
|
|
139
|
+
!node.delimiterSize && (!node.class || node.class === 'ord') && /^[\p{Decimal_Number}.]$/u.test(node.value);
|
|
140
|
+
const sameNumberStyle = (left, right) => left.variant === right.variant && left.defaultVariant === right.defaultVariant;
|
|
141
|
+
const singleToken = node => {
|
|
142
|
+
while (node?.type === 'row' && !node.semanticRole && node.children.length === 1) node = node.children[0];
|
|
143
|
+
return node?.type === 'glyph' || node?.type === 'text' ? node : null;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
function scripts(node, context, depth, base) {
|
|
147
|
+
const limits = node.limits || limitsOf(node.base), stacked = limits === 'always' || limits === 'display' && context.display && context.level === 0;
|
|
148
|
+
const name = stacked ? node.sub && node.sup ? 'munderover' : node.sub ? 'munder' : 'mover' : node.sub && node.sup ? 'msubsup' : node.sub ? 'msub' : 'msup';
|
|
149
|
+
open(name, stacked ? {accent: node.sup ? 'false' : undefined, accentunder: node.sub ? 'false' : undefined} : {});
|
|
150
|
+
if (base) base(); else emit(node.base, {...context, form: undefined, movableLimits: stacked ? false : undefined}, depth + 1);
|
|
151
|
+
if (node.sub) emit(node.sub, scriptContext(context), depth + 1);
|
|
152
|
+
if (node.sup) emit(node.sup, scriptContext(context), depth + 1);
|
|
153
|
+
close(name);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function row(children, context, depth) {
|
|
157
|
+
open('mrow');
|
|
158
|
+
let previous;
|
|
159
|
+
for (let index = 0; index < children.length; index++) {
|
|
160
|
+
const node = children[index];
|
|
161
|
+
if (numberPart(node)) {
|
|
162
|
+
let end = index + 1;
|
|
163
|
+
while (end < children.length && numberPart(children[end]) && sameNumberStyle(node, children[end])) end++;
|
|
164
|
+
const scripted = children[end]?.type === 'scripts' && !children[end].semanticRole && numberPart(children[end].base) && sameNumberStyle(node, children[end].base) ? children[end] : null;
|
|
165
|
+
const values = children.slice(index, end).map(child => child.value).join('') + (scripted ? scripted.base.value : '');
|
|
166
|
+
// A malformed multi-dot run is not silently split into apparent decimal
|
|
167
|
+
// numbers. Groups, explicit spaces, styles and scripts are hard borders.
|
|
168
|
+
if (/^(?:\p{Decimal_Number}+(?:\.\p{Decimal_Number}*)?|\.\p{Decimal_Number}+)$/u.test(values)) {
|
|
169
|
+
for (let at = index; at < end; at++) visit(children[at], depth + 1);
|
|
170
|
+
if (scripted) {
|
|
171
|
+
visit(scripted, depth + 1); visit(scripted.base, depth + 2);
|
|
172
|
+
scripts(scripted, context, depth + 1, () => atom(node, values, 'mn', context)); end++;
|
|
173
|
+
} else atom(node, values, 'mn', context);
|
|
174
|
+
previous = 'ord'; index = end - 1; continue;
|
|
175
|
+
}
|
|
176
|
+
// Consume an invalid run in one pass. Reconsidering each suffix both
|
|
177
|
+
// invents decimals (6.7.8 -> 6 . 7.8) and makes dot-only input quadratic.
|
|
178
|
+
for (let at = index; at < end; at++) emit(children[at], context, depth + 1);
|
|
179
|
+
if (scripted) { emit(scripted, context, depth + 1); end++; }
|
|
180
|
+
previous = 'ord'; index = end - 1; continue;
|
|
181
|
+
}
|
|
182
|
+
let form;
|
|
183
|
+
if (node.type === 'glyph' && node.class === 'bin')
|
|
184
|
+
form = !previous || ['bin', 'op', 'rel', 'open', 'punct'].includes(previous) ? 'prefix' : 'infix';
|
|
185
|
+
emit(node, {...context, form}, depth + 1);
|
|
186
|
+
if (node.type !== 'space') previous = classOf(node);
|
|
187
|
+
}
|
|
188
|
+
close('mrow');
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function table(node, context, depth) {
|
|
192
|
+
const rows = node.rows, columns = Math.max(node.align?.length || 0, node.pairs ? node.pairs * 2 : 0, ...rows.map(cells => cells.length));
|
|
193
|
+
const insertions = node.columnInsertions || [], rules = (node.columnRules?.length || 0) + (node.rowRules?.length || 0);
|
|
194
|
+
if (columns > 256 || rows.length > 2048 || rows.length * (columns + insertions.length) + rules > 100000)
|
|
195
|
+
fail('resource-limit', 'MathML table composition exceeds its work budget.');
|
|
196
|
+
for (const boundary of node.columnRules || []) if (!Number.isInteger(boundary) || boundary < 0 || boundary > columns)
|
|
197
|
+
fail('invalid-rule', 'An array rule exceeds its columns.');
|
|
198
|
+
for (const rule of node.rowRules || []) {
|
|
199
|
+
const from = rule.from ?? 0, to = rule.to ?? columns;
|
|
200
|
+
if (!Number.isInteger(rule.before) || rule.before < 0 || rule.before > rows.length || !Number.isInteger(from) ||
|
|
201
|
+
!Number.isInteger(to) || from < 0 || from > to || to > columns)
|
|
202
|
+
fail('invalid-rule', 'An array rule exceeds its cells.');
|
|
203
|
+
}
|
|
204
|
+
if (insertions.length || rules) warn('semantic-array-presentation', 'Array insertion content is preserved in adjacent cells; decorative row and column rules have no additional mathematical meaning and are omitted.');
|
|
205
|
+
const before = Array.from({length: columns + 1}, () => []);
|
|
206
|
+
for (const insertion of insertions) {
|
|
207
|
+
if (!Number.isInteger(insertion.before) || insertion.before < 0 || insertion.before > columns)
|
|
208
|
+
fail('invalid-alignment', 'A MathML array insertion exceeds its columns.');
|
|
209
|
+
before[insertion.before].push(insertion.body);
|
|
210
|
+
}
|
|
211
|
+
const small = /smallmatrix$/.test(node.env) || node.env === 'subarray' || node.env === 'substack';
|
|
212
|
+
const display = /^(align(?:ed)?(?:at)?|flalign|split|gather(?:ed)?|eqnarray|multline|equation|drcases|dcases)$/.test(node.env);
|
|
213
|
+
const cellContext = {...context, display: small ? false : display, level: small ? Math.max(1, context.level) : context.level};
|
|
214
|
+
const delimiters = {pmatrix: ['(', ')'], bmatrix: ['[', ']'], Bmatrix: ['{', '}'], vmatrix: ['|', '|'], Vmatrix: ['‖', '‖'],
|
|
215
|
+
psmallmatrix: ['(', ')'], bsmallmatrix: ['[', ']'], Bsmallmatrix: ['{', '}'], vsmallmatrix: ['|', '|'], Vsmallmatrix: ['‖', '‖'],
|
|
216
|
+
cases: ['{', ''], dcases: ['{', ''], rcases: ['', '}'], drcases: ['', '}']}[node.env];
|
|
217
|
+
if (delimiters) { open('mrow'); fence(delimiters[0], 'prefix', context); }
|
|
218
|
+
open('mtable', {displaystyle: String(cellContext.display), scriptlevel: String(cellContext.level), 'data-math-environment': node.env});
|
|
219
|
+
for (let at = 0; at < rows.length; at++) {
|
|
220
|
+
open('mtr');
|
|
221
|
+
for (let column = 0; column < columns; column++) {
|
|
222
|
+
if (++metrics.nodes > 100000) fail('resource-limit', 'MathML table cells exceed its work budget.');
|
|
223
|
+
let align = node.env === 'eqnarray' ? ['r', 'c', 'l'][column % 3] : node.align?.[column] || 'c';
|
|
224
|
+
if (node.env === 'multline' && columns === 1) align = at === 0 ? 'l' : at === rows.length - 1 ? 'r' : 'c';
|
|
225
|
+
open('mtd', {style: 'text-align:' + ({l: 'left', r: 'right', c: 'center'}[align] || 'center')});
|
|
226
|
+
open('mrow');
|
|
227
|
+
for (const body of before[column]) emit(body, cellContext, depth + 1);
|
|
228
|
+
if (rows[at][column]) emit(rows[at][column], cellContext, depth + 1);
|
|
229
|
+
if (column === columns - 1) for (const body of before[columns]) emit(body, cellContext, depth + 1);
|
|
230
|
+
close('mrow'); close('mtd');
|
|
231
|
+
}
|
|
232
|
+
close('mtr');
|
|
233
|
+
}
|
|
234
|
+
close('mtable');
|
|
235
|
+
if (delimiters) { fence(delimiters[1], 'postfix', context); close('mrow'); }
|
|
236
|
+
if (node.position || node.rowGaps?.some(value => value))
|
|
237
|
+
warn('semantic-table-spacing', 'Table row and cell relationships are preserved; custom baseline placement and row gaps are not reproduced.');
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function emit(node, context, depth = 0) {
|
|
241
|
+
visit(node, depth); family(node);
|
|
242
|
+
if (active.has(node)) fail('unsupported-semantic-node', 'A mathematical tree contains a cycle.');
|
|
243
|
+
active.add(node);
|
|
244
|
+
try {
|
|
245
|
+
switch (node.type) {
|
|
246
|
+
case 'row': row(node.children, context, depth); break;
|
|
247
|
+
case 'glyph': {
|
|
248
|
+
const name = kind(node), attributes = {};
|
|
249
|
+
if (name === 'mo') {
|
|
250
|
+
if (node.class === 'open' || node.class === 'close') { attributes.fence = 'true'; attributes.form = node.class === 'open' ? 'prefix' : 'postfix'; }
|
|
251
|
+
else if (node.class === 'punct') attributes.separator = 'true';
|
|
252
|
+
else if (context.form) attributes.form = context.form;
|
|
253
|
+
if (node.large !== undefined) attributes.largeop = String(!!node.large);
|
|
254
|
+
if (node.limits) attributes.movablelimits = String(node.limits === 'display');
|
|
255
|
+
if (node.delimiter || node.delimiterSize || node.stretch) attributes.stretchy = 'true';
|
|
256
|
+
else attributes.stretchy = 'false';
|
|
257
|
+
if (node.delimiterSize) attributes.minsize = attributes.maxsize = em(node.delimiterSize);
|
|
258
|
+
}
|
|
259
|
+
atom(node, node.value, name, context, attributes); break;
|
|
260
|
+
}
|
|
261
|
+
case 'text': atom(node, node.value, ['op', 'bin', 'rel'].includes(node.class) ? 'mo' : 'mtext', context,
|
|
262
|
+
node.class === 'op' ? {form: 'prefix', movablelimits: String(node.limits === 'display')} : {}); break;
|
|
263
|
+
case 'space': open('mspace', {width: em(Math.max(0, node.width)), style: node.width < 0 ? 'margin-left:' + em(node.width) : undefined}); close('mspace'); break;
|
|
264
|
+
case 'scripts': scripts(node, context, depth); break;
|
|
265
|
+
case 'frac': {
|
|
266
|
+
const local = node.style ? styledContext(context, {mathStyle: node.style}) : context;
|
|
267
|
+
if (node.style) open('mstyle', {displaystyle: String(local.display), scriptlevel: String(local.level)});
|
|
268
|
+
if (node.left || node.right) { open('mrow'); fence(node.left, 'prefix', local); }
|
|
269
|
+
open('mfrac', {linethickness: node.bar === false ? '0' : node.barThickness === undefined ? undefined : em(node.barThickness)});
|
|
270
|
+
const child = local.display && local.level === 0 ? {...local, display: false} : scriptContext(local);
|
|
271
|
+
emit(node.num, child, depth + 1); emit(node.den, child, depth + 1); close('mfrac');
|
|
272
|
+
if (node.left || node.right) { fence(node.right, 'postfix', local); close('mrow'); }
|
|
273
|
+
if (node.style) close('mstyle');
|
|
274
|
+
if (node.align) warn('semantic-fraction-alignment', 'The fraction relationship is preserved; continued-fraction numerator alignment is left to the MathML host.');
|
|
275
|
+
break;
|
|
276
|
+
}
|
|
277
|
+
case 'root':
|
|
278
|
+
open(node.index ? 'mroot' : 'msqrt'); emit(node.body, context, depth + 1);
|
|
279
|
+
if (node.index) emit(node.index, {...context, display: false, level: 2}, depth + 1);
|
|
280
|
+
close(node.index ? 'mroot' : 'msqrt'); break;
|
|
281
|
+
case 'fence':
|
|
282
|
+
open('mrow'); fence(node.left, 'prefix', context, node.size); emit(node.body, context, depth + 1); fence(node.right, 'postfix', context, node.size); close('mrow'); break;
|
|
283
|
+
case 'accent': {
|
|
284
|
+
if (node.overlay) {
|
|
285
|
+
warn('semantic-overlay', 'An overlay uses the MathML 3 menclose extension; hosts implementing only Core may omit the cancellation or negation mark.');
|
|
286
|
+
const notation = node.value === '╲' ? 'downdiagonalstrike' : node.value === '╳' ? 'updiagonalstrike downdiagonalstrike' : node.value === '↗' ? 'updiagonalarrow' : 'updiagonalstrike';
|
|
287
|
+
open('menclose', {notation}); emit(node.base, context, depth + 1); close('menclose'); break;
|
|
288
|
+
}
|
|
289
|
+
const under = node.position === 'under', name = under ? 'munder' : 'mover';
|
|
290
|
+
open(name, {[under ? 'accentunder' : 'accent']: 'true'}); emit(node.base, {...context, movableLimits: false}, depth + 1);
|
|
291
|
+
token('mo', node.value, {stretchy: String(!!node.stretch)}, context); close(name); break;
|
|
292
|
+
}
|
|
293
|
+
case 'overunder': {
|
|
294
|
+
const name = node.over && node.under ? 'munderover' : node.under ? 'munder' : 'mover';
|
|
295
|
+
open(name, {accent: node.over ? 'false' : undefined, accentunder: node.under ? 'false' : undefined}); emit(node.base, {...context, movableLimits: false}, depth + 1);
|
|
296
|
+
if (node.under) emit(node.under, scriptContext(context), depth + 1);
|
|
297
|
+
if (node.over) emit(node.over, scriptContext(context), depth + 1);
|
|
298
|
+
close(name); break;
|
|
299
|
+
}
|
|
300
|
+
case 'table': table(node, context, depth); break;
|
|
301
|
+
case 'style': {
|
|
302
|
+
const local = styledContext(context, node), attributes = {'data-math-class': node.class};
|
|
303
|
+
if (node.mathStyle) { attributes.displaystyle = String(local.display); attributes.scriptlevel = String(local.level); }
|
|
304
|
+
let css = '';
|
|
305
|
+
if (node.absoluteSize !== undefined || node.size !== undefined) css += 'font-size:' + decimal(local.size / context.size) + 'em;';
|
|
306
|
+
if (node.color) css += 'color:' + node.color + ';';
|
|
307
|
+
if (node.background) css += 'background-color:' + node.background + ';';
|
|
308
|
+
if (node.border) css += 'border:0.04em solid ' + node.border + ';padding:' + em(node.padding ?? .2) + ';';
|
|
309
|
+
if (css) attributes.style = css;
|
|
310
|
+
open('mstyle', attributes);
|
|
311
|
+
if (node.tokenKind) {
|
|
312
|
+
atom({variant: local.variant}, node.tokenText, node.tokenKind, local);
|
|
313
|
+
} else if (node.operatorName) {
|
|
314
|
+
const value = plain(node.body, depth + 1, true);
|
|
315
|
+
if (value === null) {
|
|
316
|
+
warn('semantic-rich-operator', 'A styled or mixed-math operator name retains its nested structure instead of becoming one plain operator token.');
|
|
317
|
+
emit(node.body, local, depth + 1);
|
|
318
|
+
} else atom({variant: 'roman'}, value, 'mo', local, {form: 'prefix', movablelimits: String(node.limits === 'display')});
|
|
319
|
+
} else if (node.width !== undefined) {
|
|
320
|
+
warn('semantic-layout-adjustment', 'A TeX layout adjustment retains its mathematical content with a bounded presentation approximation.');
|
|
321
|
+
open('mpadded', {width: em(node.width)}); emit(node.body, local, depth + 1); close('mpadded');
|
|
322
|
+
} else if (node.class) {
|
|
323
|
+
const leaf = singleToken(node.body);
|
|
324
|
+
if (leaf) emit({...leaf, class: node.class}, local, depth + 1);
|
|
325
|
+
else {
|
|
326
|
+
warn('semantic-atom-class', 'A compound expression retains its mathematical children; its TeX atom class does not create a single MathML operator.');
|
|
327
|
+
emit(node.body, local, depth + 1);
|
|
328
|
+
}
|
|
329
|
+
} else emit(node.body, local, depth + 1);
|
|
330
|
+
close('mstyle'); break;
|
|
331
|
+
}
|
|
332
|
+
case 'phantom': {
|
|
333
|
+
const before = content;
|
|
334
|
+
if (node.mode === 'h' || node.mode === 'v') open('mpadded', node.mode === 'h' ? {height: '0', depth: '0'} : {width: '0'});
|
|
335
|
+
open('mphantom'); emit(node.body, {...context, phantom: true}, depth + 1); close('mphantom');
|
|
336
|
+
if (node.mode === 'h' || node.mode === 'v') close('mpadded');
|
|
337
|
+
content = before; break;
|
|
338
|
+
}
|
|
339
|
+
case 'smash':
|
|
340
|
+
open('mpadded', {height: node.mode === 'b' ? undefined : '0', depth: node.mode === 't' ? undefined : '0'});
|
|
341
|
+
emit(node.body, context, depth + 1); close('mpadded'); break;
|
|
342
|
+
case 'raise':
|
|
343
|
+
open('mpadded', {voffset: em(node.amount), height: node.height === undefined ? undefined : em(node.height), depth: node.depth === undefined ? undefined : em(node.depth)});
|
|
344
|
+
emit(node.body, context, depth + 1); close('mpadded'); break;
|
|
345
|
+
case 'rule':
|
|
346
|
+
warn('semantic-rule-presentation', 'A rule is represented as a decorative mathematical space; no additional mathematical relationship is inferred.');
|
|
347
|
+
open('mspace', {width: em(node.width), height: em(node.height), depth: em(node.depth), style: 'background-color:currentColor'}); close('mspace');
|
|
348
|
+
if (!context.phantom && !context.transparent && node.width > 0 && node.height + node.depth > 0) content++; break;
|
|
349
|
+
case 'link': {
|
|
350
|
+
if (context.inLink) fail('semantic-nested-link', 'Nested authored mathematical links cannot be represented as valid native HTML links.');
|
|
351
|
+
if (context.phantom) fail('semantic-hidden-link', 'An authored link inside phantom content cannot become an invisible native focus target.');
|
|
352
|
+
let url;
|
|
353
|
+
try { url = new URL(node.href); } catch { fail('unsafe-link', 'A mathematical link has an invalid address.'); }
|
|
354
|
+
if (!['http:', 'https:'].includes(url.protocol) || !/^https?:\/\/[^\s<>"'\\]+$/i.test(node.href))
|
|
355
|
+
fail('unsafe-link', 'A mathematical link must use an HTTP or HTTPS address.');
|
|
356
|
+
warn('semantic-link-embedding', 'The authored link uses native HTML inside MathML text, with a nested MathML expression; assistive-technology interaction depends on the host.');
|
|
357
|
+
metrics.links++;
|
|
358
|
+
open('mtext'); open('a', {xmlns: 'http://www.w3.org/1999/xhtml', href: node.href, title: node.href, target: '_blank', rel: 'noopener noreferrer'});
|
|
359
|
+
const before = content;
|
|
360
|
+
open('math', {xmlns: MATH_ML_NAMESPACE, display: 'inline'}); emit(node.body, {...context, inLink: true, display: false}, depth + 1);
|
|
361
|
+
if (content === before) fail('semantic-empty-link', 'An authored mathematical link has no visible content for native focus.');
|
|
362
|
+
close('math'); close('a'); close('mtext'); break;
|
|
363
|
+
}
|
|
364
|
+
default: fail('unsupported-semantic-node', 'Unsupported mathematical node for MathML.');
|
|
365
|
+
}
|
|
366
|
+
} finally { active.delete(node); }
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
let status;
|
|
370
|
+
try {
|
|
371
|
+
if (sourceOmitted) fail('resource-limit', 'This formula is too long for MathML. Its source was not embedded; retain the original input.');
|
|
372
|
+
if (options.error || safeSource?.error) throw options.error || safeSource.error;
|
|
373
|
+
if (!tree) fail('unsupported-semantic-node', 'A parsed mathematical expression is required.');
|
|
374
|
+
emit(tree, {display: !!options.displayMode, level: 0, size: 1, variant: 'normal', inLink: false});
|
|
375
|
+
status = diagnostics.length ? 'presentation-fallback' : 'complete';
|
|
376
|
+
} catch (cause) {
|
|
377
|
+
const error = mathDiagnostic(cause);
|
|
378
|
+
if (sourceOmitted) error.sourceOmitted = true;
|
|
379
|
+
diagnostics.length = 0; diagnostics.push(error);
|
|
380
|
+
status = 'refused'; metrics.links = 0;
|
|
381
|
+
parts = ['<merror><mtext>Formula could not be represented as MathML.</mtext></merror>'];
|
|
382
|
+
}
|
|
383
|
+
const presentation = parts.join('');
|
|
384
|
+
const annotation = sourceOmitted ? '' : encoding === 'application/x-tex' ?
|
|
385
|
+
'<annotation encoding="application/x-tex">' + mathMLXML(source) + '</annotation>' :
|
|
386
|
+
'<annotation encoding="text/plain">' + mathMLXML(safeSource.alternative) + '</annotation>' +
|
|
387
|
+
'<annotation encoding="application/x-rapier-tex-utf16">' + utf16 + '</annotation>';
|
|
388
|
+
const wrap = body => '<math xmlns="' + MATH_ML_NAMESPACE + '" display="' + (options.displayMode ? 'block' : 'inline') +
|
|
389
|
+
'" data-rapier-mathml-status="' + status + '"' + (sourceOmitted ? ' data-math-source-omitted="true"' : '') +
|
|
390
|
+
'><semantics>' + body + annotation + '</semantics></math>';
|
|
391
|
+
// Source admission bounds escaping independently of the presentation budget:
|
|
392
|
+
// at most 6M XML-escaped source, or 6M alternative plus 4M UTF-16 carrier.
|
|
393
|
+
let mathml = wrap(presentation);
|
|
394
|
+
if (mathml.length > 16 * 1024 * 1024) {
|
|
395
|
+
status = 'refused'; metrics.links = 0;
|
|
396
|
+
diagnostics.length = 0;
|
|
397
|
+
diagnostics.push({code: 'resource-limit', offset: 0, message: 'Complete MathML exceeds its output budget.'});
|
|
398
|
+
mathml = wrap('<merror><mtext>Formula could not be represented as MathML.</mtext></merror>');
|
|
399
|
+
}
|
|
400
|
+
metrics.outputCodeUnits = mathml.length;
|
|
401
|
+
return {mathml, status, errors: diagnostics, metrics, source: sourceInfo};
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
import {mathDiagnostic} from './source.js';
|
|
405
|
+
import {mathStyledCodePoint} from './variants.js';
|
|
406
|
+
export {mathML};
|
|
@@ -1,14 +1,27 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
|
-
//
|
|
2
|
+
// Native entries execute the carried source modules directly. The complete
|
|
3
|
+
// classic distribution concatenates these same owners without module syntax.
|
|
4
|
+
export function mathClassicSource(text) {
|
|
5
|
+
return text.replace(/^import \{[^\n]+\} from '\.\/[\w-]+\.js';\n/gm, '')
|
|
6
|
+
.replace(/^export \{[^\n]+\};\n/gm, '').trimEnd();
|
|
7
|
+
}
|
|
3
8
|
|
|
4
|
-
export function
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
9
|
+
export function mathModules(version) {
|
|
10
|
+
return new Map([
|
|
11
|
+
['dist/index.mjs', `// SPDX-License-Identifier: MIT
|
|
12
|
+
import {parseMathTex as parse} from '../src/math/parser.js';
|
|
13
|
+
import {renderMath as render, mathRenderToString as renderToString} from '../src/math/api.js';
|
|
14
|
+
import {mathFit as fit, mathObserve as observe} from '../src/math/browser.js';
|
|
15
|
+
const version = ${JSON.stringify(version)};
|
|
16
|
+
export {version, parse, render, renderToString, fit, observe};
|
|
17
|
+
export default Object.freeze({version, parse, render, renderToString, fit, observe});
|
|
18
|
+
`],
|
|
19
|
+
['dist/mathml.mjs', `// SPDX-License-Identifier: MIT
|
|
20
|
+
export {parseMathTex as parse} from '../src/math/parser.js';
|
|
21
|
+
export {mathToMathML as toMathML} from '../src/math/semantic-api.js';
|
|
22
|
+
`],
|
|
23
|
+
['dist/combined.mjs', `// SPDX-License-Identifier: MIT
|
|
24
|
+
export {mathRenderWithMathML as renderWithMathML} from '../src/math/combined.js';
|
|
25
|
+
`],
|
|
26
|
+
]);
|
|
14
27
|
}
|
|
@@ -5,6 +5,9 @@ export const MATH_CLASSIC = 'dist/rapier-math.js';
|
|
|
5
5
|
export function mathPackagePath(file) {
|
|
6
6
|
const owners = {
|
|
7
7
|
'math/README.md': 'docs/api.md',
|
|
8
|
+
'math/SEMANTICS.md': 'docs/semantics.md',
|
|
9
|
+
'math/semantic-verify.mjs': 'tests/semantics.mjs',
|
|
10
|
+
'math/accessible.css': 'dist/accessible.css',
|
|
8
11
|
'math/FONT-SOURCE.md': 'docs/font-source.md',
|
|
9
12
|
'math/package-check.mjs': 'tests/check.mjs',
|
|
10
13
|
'math/package-verify.mjs': 'tests/verify.mjs',
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
export function mathReadme(resources) {
|
|
3
3
|
return `# Rapier Math
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Offline TeX formulas as SVG or structured MathML. Embedded Latin Modern outlines for SVG; font-free native MathML. Synchronous, with no runtime downloads.
|
|
6
6
|
|
|
7
7
|
## Use
|
|
8
8
|
|
|
@@ -17,16 +17,26 @@ const svg = renderToString(String.raw\`\\frac{a}{b}\`);
|
|
|
17
17
|
|
|
18
18
|
For a browser script, load [${resources.packageBundle}](${resources.packageBundle}) and use
|
|
19
19
|
\`globalThis.RapierMath\`. The native ESM entry is [dist/index.mjs](dist/index.mjs).
|
|
20
|
-
|
|
20
|
+
For one-file copying or inline-script embedding, use the classic file above. The native
|
|
21
|
+
ESM entry imports relative \`src/math/\` modules: install/serve the whole package or bundle
|
|
22
|
+
that import; copying only \`dist/index.mjs\` is insufficient. A CDN must retain that graph
|
|
23
|
+
or bundle it. Formula rendering stays synchronous and offline after its chosen script
|
|
24
|
+
or module graph has loaded.
|
|
25
|
+
|
|
26
|
+
The SVG entry and classic script include the font. Use \`rapier-math/mathml\` for font-free MathML,
|
|
27
|
+
\`rapier-math/combined\` for one-parse SVG and MathML, or \`rapier-math/accessible\` with its stylesheet
|
|
28
|
+
for host composition. All return synchronously. Type declarations accompany the runtime files.
|
|
21
29
|
|
|
22
30
|
- [API and integration guide](docs/api.md)
|
|
31
|
+
- [MathML, accessibility and source contracts](docs/semantics.md)
|
|
23
32
|
- [Runnable examples](examples/README.md)
|
|
24
33
|
- [Font source and regeneration](docs/font-source.md)
|
|
25
34
|
|
|
26
35
|
## Develop
|
|
27
36
|
|
|
28
|
-
The
|
|
29
|
-
\`src
|
|
37
|
+
The classic script and native entry points live in \`dist/\`. Native entries import the editable
|
|
38
|
+
modules in \`src/math/\` directly, sharing one parser without a duplicate generated renderer. Build
|
|
39
|
+
tools live in \`src/tools/\`. Optional adapters have one source copy in \`dist/\`. Examples, documentation and tests each
|
|
30
40
|
have their own directory. Only the current release is kept in this checkout.
|
|
31
41
|
|
|
32
42
|
From a repository checkout, run \`node tests/check.mjs\` and \`node tests/verify.mjs\` to check the package and rebuild its exact bytes.
|
package/src/math/parser.js
CHANGED
|
@@ -175,7 +175,7 @@ class MathTexParser {
|
|
|
175
175
|
for (;;) {
|
|
176
176
|
const token = this.peek();
|
|
177
177
|
if (token.kind === 'eof' || stop(token)) break;
|
|
178
|
-
if (token.kind === 'command' && (MATH_TEX_DECLARATIONS
|
|
178
|
+
if (token.kind === 'command' && (Object.hasOwn(MATH_TEX_DECLARATIONS, token.value) || token.value === 'color')) {
|
|
179
179
|
this.take();
|
|
180
180
|
const fields = token.value === 'color' ? {color: this.readColor()} : MATH_TEX_DECLARATIONS[token.value];
|
|
181
181
|
children.push(this.node('style', {...fields, body: this.nested(() => this.parseRow(stop, allowFraction))}));
|
|
@@ -326,7 +326,7 @@ class MathTexParser {
|
|
|
326
326
|
if (token.kind === 'command') {
|
|
327
327
|
if (token.value === '{' || token.value === '}') return token.value;
|
|
328
328
|
if (token.value === '|') return '‖';
|
|
329
|
-
const symbol = MATH_SYMBOLS[token.value];
|
|
329
|
+
const symbol = Object.hasOwn(MATH_SYMBOLS, token.value) ? MATH_SYMBOLS[token.value] : null;
|
|
330
330
|
if (symbol && (['open', 'close'].includes(symbol.class) || /^(vert|Vert|backslash|slash|[uUdD].*arrow)$/.test(token.value))) return symbol.value;
|
|
331
331
|
}
|
|
332
332
|
if (token.kind === 'char' && '.()[]{}|/<>‖⌈⌉⌊⌋⟨⟩↑↓↕⇑⇓⇕'.includes(token.value))
|
|
@@ -340,7 +340,7 @@ class MathTexParser {
|
|
|
340
340
|
if (Object.hasOwn(MATH_TEX_LONG_ARROWS, name)) return this.node('style', {class: 'rel', body: this.row([this.node('space', {width: 5 / 18}), this.node('glyph', MATH_SYMBOLS[MATH_TEX_LONG_ARROWS[name]]), this.node('space', {width: 5 / 18})])});
|
|
341
341
|
// amsmath \dots: centred dots before a binary operator, a relation or an integral, low dots otherwise.
|
|
342
342
|
if (name === 'dots') {
|
|
343
|
-
const next = this.rawPeek(), after = next.kind === 'command' ? MATH_SYMBOLS[next.value] : null;
|
|
343
|
+
const next = this.rawPeek(), after = next.kind === 'command' && Object.hasOwn(MATH_SYMBOLS, next.value) ? MATH_SYMBOLS[next.value] : null;
|
|
344
344
|
const centred = next.kind === 'char' ? '+-=<>*:'.includes(next.value) : !!after && (['bin', 'rel'].includes(after.class) || /^(?:int|iint|iiint|oint)$/.test(next.value));
|
|
345
345
|
if (centred) return this.node('glyph', MATH_SYMBOLS.cdots);
|
|
346
346
|
}
|
|
@@ -406,7 +406,7 @@ class MathTexParser {
|
|
|
406
406
|
if (name === 'operatorname') {
|
|
407
407
|
const starred = this.is('*'); if (starred) this.take();
|
|
408
408
|
const body = this.subparse(this.rawArgument(), true, 'roman');
|
|
409
|
-
return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never'});
|
|
409
|
+
return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never', operatorName: true});
|
|
410
410
|
}
|
|
411
411
|
if (/^math(ord|op|bin|rel|open|close|punct|inner)$/.test(name)) return this.node('style', {body: this.argument(), class: name.slice(4), ...(name === 'mathop' ? {limits: 'display'} : {})});
|
|
412
412
|
if (name === 'overset' || name === 'underset' || name === 'stackrel' || name === 'stackbin') {
|
|
@@ -479,14 +479,14 @@ class MathTexParser {
|
|
|
479
479
|
if (name === 'tag') {
|
|
480
480
|
const starred = this.is('*'); if (starred) this.take();
|
|
481
481
|
const body = this.subparse(this.rawArgument(), true);
|
|
482
|
-
return this.row([this.node('space', {width: 2}), starred ? body : this.node('fence', {left: '(', right: ')', body})]);
|
|
482
|
+
return {...this.row([this.node('space', {width: 2}), starred ? body : this.node('fence', {left: '(', right: ')', body})]), semanticRole: 'tag'};
|
|
483
483
|
}
|
|
484
484
|
if (name === 'mod' || name === 'bmod') return this.row([this.node('space', {width: name === 'bmod' ? 5 / 18 : 1}), this.node('text', {value: 'mod', variant: 'roman', class: name === 'bmod' ? 'bin' : 'op'}), this.node('space', {width: name === 'bmod' ? 5 / 18 : 1 / 3})]);
|
|
485
485
|
if (name === 'pmod' || name === 'pod') return this.row([this.node('space', {width: 1}), this.node('fence', {left: '(', right: ')', body: this.row([...(name === 'pmod' ? [this.node('text', {value: 'mod', variant: 'roman'}), this.node('space', {width: 1 / 3})] : []), this.argument()])})]);
|
|
486
486
|
if (name === 'bmod') return this.node('text', {value: 'mod', variant: 'roman', class: 'bin'});
|
|
487
|
-
if (name === 'ce') return this.chemistry(this.rawArgument());
|
|
488
|
-
if (name === 'pu') return this.units(this.rawArgument());
|
|
489
|
-
if (this.physicsCommand(name)) return this.physics(name, token);
|
|
487
|
+
if (name === 'ce') return {...this.chemistry(this.rawArgument()), semanticRole: 'chemistry'};
|
|
488
|
+
if (name === 'pu') return {...this.units(this.rawArgument()), semanticRole: 'units'};
|
|
489
|
+
if (this.physicsCommand(name)) return {...this.physics(name, token), semanticRole: 'physics'};
|
|
490
490
|
if (name === 'mmlToken') return this.mathmlToken(token);
|
|
491
491
|
if (name === 'unicode' || name === 'char') return this.character(name, token);
|
|
492
492
|
if (name === 'TeX' || name === 'LaTeX') return this.node('text', {value: name, variant: 'roman'});
|
|
@@ -711,7 +711,7 @@ class MathTexParser {
|
|
|
711
711
|
if (!next || next.kind !== 'char' || !(next.value === '#' || (/^[1-9]$/.test(next.value) && Number(next.value) <= params.length)))
|
|
712
712
|
this.error('invalid-macro', 'A replacement refers to a missing macro parameter.', body[i - 1]);
|
|
713
713
|
}
|
|
714
|
-
const existing = this.macro(macroName) || MATH_SYMBOLS
|
|
714
|
+
const existing = this.macro(macroName) || Object.hasOwn(MATH_SYMBOLS, macroName) || Object.hasOwn(MATH_TEX_VARIANTS, macroName) || MATH_NAMED_OPERATORS.has(macroName) || MATH_LIMIT_OPERATORS.has(macroName);
|
|
715
715
|
if (name === 'providecommand' && existing) return;
|
|
716
716
|
if (name === 'newcommand' && existing) this.error('duplicate-macro', '\\' + macroName + ' is already defined.', token);
|
|
717
717
|
this.scopes[name === 'gdef' ? 0 : this.scopes.length - 1][macroName] = {params, prefix, body, optional};
|
|
@@ -844,7 +844,7 @@ class MathTexParser {
|
|
|
844
844
|
if ([...letters].length !== 1) this.error('invalid-accent', 'A text accent needs one character.', token);
|
|
845
845
|
value += (letters + marks[name]).normalize('NFC'); continue;
|
|
846
846
|
}
|
|
847
|
-
if (MATH_SYMBOLS
|
|
847
|
+
if (Object.hasOwn(MATH_SYMBOLS, name) && !MATH_SYMBOLS[name].large) { value += MATH_SYMBOLS[name].value; continue; }
|
|
848
848
|
flush();
|
|
849
849
|
const body = this.command(token);
|
|
850
850
|
if (body) children.push(body);
|
|
@@ -1035,7 +1035,7 @@ class MathTexParser {
|
|
|
1035
1035
|
if (!match || !variants.has(match[1])) this.error('unsupported-attribute', 'Only a mathematical font variant is supported on a token.', token);
|
|
1036
1036
|
variant = match[1] === 'normal' ? 'roman' : match[1] === 'bold-sans-serif' ? 'sans-serif-bold' : match[1];
|
|
1037
1037
|
}
|
|
1038
|
-
return this.node('style', {variant, body: kind === 'mtext' ? this.node('text', {value: text, variant}) : this.row([...text].map(value => this.literal(value, {variant})))});
|
|
1038
|
+
return this.node('style', {variant, tokenKind: kind, tokenText: text, body: kind === 'mtext' ? this.node('text', {value: text, variant}) : this.row([...text].map(value => this.literal(value, {variant})))});
|
|
1039
1039
|
}
|
|
1040
1040
|
character(name, token) {
|
|
1041
1041
|
let raw;
|
|
@@ -1062,3 +1062,6 @@ function parseMathTex(source) {
|
|
|
1062
1062
|
if (source.length > 1000000) throw new MathTexError('resource-limit', 'This formula is too long to render safely.');
|
|
1063
1063
|
return new MathTexParser(source).parse();
|
|
1064
1064
|
}
|
|
1065
|
+
|
|
1066
|
+
import {MATH_SYMBOLS, MATH_NAMED_OPERATORS, MATH_LIMIT_OPERATORS} from './symbols.js';
|
|
1067
|
+
export {parseMathTex};
|
package/src/math/responsive.js
CHANGED
|
@@ -249,3 +249,7 @@ function mathResponsiveLayout(n,c,width,natural=mathLayout(n,c)) {
|
|
|
249
249
|
}
|
|
250
250
|
return mathFitBox(natural,width,c);
|
|
251
251
|
}
|
|
252
|
+
|
|
253
|
+
import {MATH_FONT} from './font.js';
|
|
254
|
+
import {mathNumber, mathEscape, mathScale, mathScreenStroke, mathConstant, mathScreenRelayout, mathCompose, mathSpace, mathRow, mathFraction, mathFenceBoxes, mathLayout} from './layout.js';
|
|
255
|
+
export {mathResponsiveLayout, mathInkWidth};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
function mathSemanticPrepared(prepared, options = {}) {
|
|
3
|
+
const {text, safe, tree, error} = prepared;
|
|
4
|
+
return mathML(tree, text, safe, {displayMode: !!options?.displayMode, error});
|
|
5
|
+
}
|
|
6
|
+
function mathToMathML(source, options = {}) {
|
|
7
|
+
return mathSemanticPrepared(mathPrepare(source), options);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
import {mathPrepare} from './source.js';
|
|
11
|
+
import {mathML} from './mathml.js';
|
|
12
|
+
export {mathSemanticPrepared, mathToMathML};
|