rapier-math 2.4.0 → 2.6.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.
- package/CHANGELOG.md +10 -0
- package/LICENSE +10 -3
- package/README.md +4 -5
- package/dist/index.mjs +1 -1
- package/dist/markdown-rules.mjs +47 -0
- package/dist/rapier-math.js +678 -229
- package/docs/api.md +6 -2
- package/docs/font-source.md +37 -29
- package/docs/math-components.json +51 -7
- package/docs/math-resources.json +59 -64
- package/package.json +3 -3
- package/src/math/FONT-LICENSE.txt +9 -2
- package/src/math/build-font.py +61 -65
- package/src/math/classic.js +1 -1
- package/src/math/font.js +23 -487
- package/src/math/layout.js +302 -112
- package/src/math/mathml.js +26 -7
- package/src/math/package-layout.mjs +1 -0
- package/src/math/package-readme.mjs +3 -4
- package/src/math/parser.js +306 -67
- package/src/tools/build-math.mjs +22 -7
- package/tests/adoption.mjs +0 -252
- package/tests/check.mjs +0 -133
- package/tests/semantics.mjs +0 -340
- package/tests/typeset.mjs +0 -172
- package/tests/verify.mjs +0 -49
package/src/math/layout.js
CHANGED
|
@@ -54,21 +54,34 @@ function mathGlyphIndex(id, c, extra = {}) {
|
|
|
54
54
|
c.budget.outlineBytes=(c.budget.outlineBytes || 0)+g[7].length+96;
|
|
55
55
|
if(c.budget.outlineBytes>4*1024*1024)throw Object.assign(new Error('Mathematical outlines exceed the rendering budget'),{code:'resource-limit'});
|
|
56
56
|
}
|
|
57
|
-
|
|
57
|
+
// A synthetic bold strokes the outline 0.03 em wide and adds 0.06 em of advance; a synthetic italic slants 14 degrees.
|
|
58
|
+
const bold = extra.embolden ? 0.03 * scale : 0, slope = extra.slant ? 0.25 : 0, pen = stroke + bold;
|
|
59
|
+
let svg = g[7] ? '<path d="' + g[7] + '" transform="scale(' + mathNumber(s) + ' ' + mathNumber(-s) + ')"'+
|
|
58
60
|
(c.screen ? ' data-math-ink="' + mathNumber(scale) + '"' : '') +
|
|
59
|
-
(
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
61
|
+
(pen ? ' stroke="currentColor" stroke-width="' + mathNumber(pen / s) + '" stroke-linejoin="round" paint-order="stroke fill"' : '') + '/>' : '';
|
|
62
|
+
if (svg && (bold || slope)) svg = '<g transform="translate(' + mathNumber(bold) + ' 0)' + (slope ? ' skewX(-14.04)' : '') + '">' + svg + '</g>';
|
|
63
|
+
const {embolden, slant, ...rest} = extra, r = pen / 2;
|
|
64
|
+
return mathBox(g[0] * s + 2 * bold, Math.max(0, g[4] * s + r), Math.max(0, -g[2] * s + r), svg,
|
|
65
|
+
{left: Math.min(0,g[1]*s-r+bold+slope*g[2]*s), right: Math.max(g[0]*s+2*bold,g[3]*s+r+bold+slope*g[4]*s), inkTop:-g[4]*s-r, inkBottom:-g[2]*s+r, italic: g[5]*s+slope*g[4]*s*0.5, stroke: pen || undefined,
|
|
66
|
+
accent: (g[6] == null ? g[0]*s/2 : g[6]*s)+bold+slope*g[4]*s*0.5,glyph:bold || slope?undefined:id,unitScale:s,glyphX:0,glyphY:0,extended:!!MATH_FONT.extendedShapes[id],...rest});
|
|
63
67
|
}
|
|
64
68
|
|
|
65
69
|
function mathGlyph(value, c, extra = {}) {
|
|
66
70
|
const cp = value.codePointAt(0);
|
|
67
71
|
if (value.length !== (cp > 0xffff ? 2 : 1)) return mathText(value, c, extra);
|
|
68
72
|
const variant = extra.variant || c.variant, mapped = mathStyledCodePoint(cp, variant);
|
|
73
|
+
const styled = MATH_FONT.styledGlyphs[variant]?.[cp];
|
|
74
|
+
if (styled !== undefined) return mathGlyphIndex(styled, c, extra);
|
|
69
75
|
// A styled dotless i or j is the styled letter's dotless form (Unicode has italic ones only).
|
|
70
76
|
const dotless = (cp === 0x1d6a4 || cp === 0x1d6a5) && !/^(normal|italic|roman)$/.test(variant) ? MATH_FONT.dotless[MATH_FONT.chars[mathStyledCodePoint(cp - 0x1d6a4 + 105, variant)]] : undefined;
|
|
77
|
+
if (mapped === cp && !dotless && !/^(normal|roman)$/.test(variant)) {
|
|
78
|
+
const composed = mathStyledLetter(value, c, extra, variant);
|
|
79
|
+
if (composed) return composed;
|
|
80
|
+
}
|
|
71
81
|
const id = dotless ?? MATH_FONT.chars[mapped] ?? MATH_FONT.chars[cp];
|
|
82
|
+
// A letter Unicode gives no bold or italic form (ø, ß, æ, þ) is the font's letter emboldened or slanted.
|
|
83
|
+
if (id !== undefined && mapped === cp && !dotless && /bold|italic/.test(variant || '') && !/script|fraktur|double/.test(variant) && /\p{L}/u.test(value))
|
|
84
|
+
return mathGlyphIndex(id, c, {...extra, embolden: /bold/.test(variant), slant: /italic/.test(variant)});
|
|
72
85
|
if (id === undefined) {
|
|
73
86
|
const composed = mathFallbackGlyph(value, c, extra);
|
|
74
87
|
if (composed) return composed;
|
|
@@ -79,6 +92,24 @@ function mathGlyph(value, c, extra = {}) {
|
|
|
79
92
|
return mathGlyphIndex(id, c, extra);
|
|
80
93
|
}
|
|
81
94
|
|
|
95
|
+
// A styled accented letter (bold é) has no styled code point: draw its styled base letter with the font's
|
|
96
|
+
// combining marks, as an accent sits on a letter; a mark below hangs from the baseline.
|
|
97
|
+
function mathStyledLetter(value, c, extra, variant) {
|
|
98
|
+
// The font has no combining cedilla or ogonek; their spacing forms hang from the baseline the same way.
|
|
99
|
+
const [base, ...marks] = [...value.normalize('NFD')].map(m => MATH_FONT.chars[m.codePointAt(0)] === undefined ? {'\u0327': '¸', '\u0328': '˛'}[m] || m : m);
|
|
100
|
+
const cp = base.codePointAt(0);
|
|
101
|
+
if (!marks.length || mathStyledCodePoint(cp, variant) === cp || !marks.every(m => (/\p{M}/u.test(m) || '¸˛'.includes(m)) && MATH_FONT.chars[m.codePointAt(0)] !== undefined)) return null;
|
|
102
|
+
const glyphs = marks.map(m => mathGlyph(m, c, {variant: 'roman'})), above = glyphs.some(a => a.inkBottom <= 0);
|
|
103
|
+
const b = mathGlyph(base, {...c, dotless: above && /^[ij]$/.test(base)}, extra), items = [[b,0,0]];
|
|
104
|
+
let top = -Math.max(0, b.h - mathConstant('AccentBaseHeight', c, 0.45));
|
|
105
|
+
for (const a of glyphs) {
|
|
106
|
+
const over = a.inkBottom <= 0, x = (over ? b.accent ?? b.w/2 : b.w/2) - (a.accent ?? a.w/2);
|
|
107
|
+
items.push([a, x, over ? top : 0]);
|
|
108
|
+
if (over) top -= a.inkBottom - a.inkTop;
|
|
109
|
+
}
|
|
110
|
+
return mathCompose(items, b.w, {...extra, italic: b.italic, accent: b.accent, glyph: undefined});
|
|
111
|
+
}
|
|
112
|
+
|
|
82
113
|
// Letters, digits, marks and symbols outside the embedded font (CJK, Cyrillic, emoji...) use the reader's
|
|
83
114
|
// own serif font. Their advance is estimated, and textLength fits the drawn run to that box exactly.
|
|
84
115
|
const MATH_HOST_TEXT = /^[\p{L}\p{N}\p{M}\p{S}\p{P}]+$/u;
|
|
@@ -94,18 +125,54 @@ function mathHostText(value, c, extra = {}) {
|
|
|
94
125
|
'" lengthAdjust="spacingAndGlyphs">' + mathEscape(value) + '</text>', {inkTop: -0.8 * s, inkBottom: 0.2 * s, ...extra});
|
|
95
126
|
}
|
|
96
127
|
|
|
97
|
-
|
|
98
|
-
|
|
128
|
+
// One word of text: a run of host-font characters stays one text element, keeping its shaping and joining.
|
|
129
|
+
function mathTextWord(value, text) {
|
|
130
|
+
const items = []; let x = 0, run = '';
|
|
99
131
|
const flush = () => { if (run) { const b = mathHostText(run, text); items.push([b,x,0]); x += b.w; run = ''; } };
|
|
100
|
-
for (const ch of
|
|
101
|
-
if (/\s/u.test(ch)) { flush(); x += mathScale(c)*0.25; continue; }
|
|
102
|
-
// A run of host-font characters stays one text element, keeping its shaping and joining.
|
|
132
|
+
for (const ch of value) {
|
|
103
133
|
if (run && /\p{M}/u.test(ch)) { run += ch; continue; }
|
|
104
134
|
const b = mathGlyph(ch, text);
|
|
105
135
|
if (b.host) { run += ch; continue; }
|
|
106
136
|
flush(); items.push([b,x,0]); x += b.w;
|
|
107
137
|
}
|
|
108
138
|
flush();
|
|
139
|
+
return mathCompose(items,x);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// A word's direction from its first strong letter; a word without letters is a number or neutral.
|
|
143
|
+
const MATH_RTL = /[\p{sc=Hebrew}\p{sc=Arabic}\p{sc=Syriac}\p{sc=Thaana}\p{sc=Nko}\p{sc=Samaritan}\p{sc=Mandaic}\p{sc=Adlam}\p{sc=Hanifi_Rohingya}]/u;
|
|
144
|
+
const mathWordDirection = word => {
|
|
145
|
+
for (const ch of word) if (/\p{L}/u.test(ch)) return MATH_RTL.test(ch) ? 'R' : 'L';
|
|
146
|
+
return /\p{Nd}/u.test(word) ? 'N' : null;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
function mathText(value, c, extra = {}) {
|
|
150
|
+
// Latin Modern Roman's word space is 1/3 em, and TeX sets a run of spaces as one.
|
|
151
|
+
const text = {...c, variant: extra.variant || 'roman'}, space = mathScale(c)/3, words = [];
|
|
152
|
+
// Letters (with their marks and joiners), numbers and punctuation are separate pieces of a word.
|
|
153
|
+
for (const part of String(value).match(/\s+|[\p{L}\p{M}\p{Cf}]+|\p{Nd}+(?:[.,]\p{Nd}+)*|[^\s\p{L}\p{M}\p{Cf}\p{Nd}]+/gu) || [])
|
|
154
|
+
words.push(/^\s+$/u.test(part) ? {w: part === '\u2009' ? mathScale(c)/6 : space, dir: null} : {box: mathTextWord(part, text), dir: mathWordDirection(part)});
|
|
155
|
+
// The Unicode bidirectional algorithm in a left-to-right line: a number after right-to-left words joins them,
|
|
156
|
+
// as does a neutral between two of them; each right-to-left run reads from the right.
|
|
157
|
+
let strong = 'L';
|
|
158
|
+
for (const word of words) {
|
|
159
|
+
if (word.dir === 'R' || word.dir === 'L') strong = word.level = word.dir;
|
|
160
|
+
else if (word.dir === 'N') word.level = strong;
|
|
161
|
+
}
|
|
162
|
+
for (let i = 0; i < words.length; i++) if (!words[i].level) {
|
|
163
|
+
let j = i; while (j < words.length && !words[j].level) j++;
|
|
164
|
+
const level = words[i - 1]?.level === 'R' && words[j]?.level === 'R' ? 'R' : 'L';
|
|
165
|
+
for (; i < j; i++) words[i].level = level;
|
|
166
|
+
i--;
|
|
167
|
+
}
|
|
168
|
+
const order = [];
|
|
169
|
+
for (let i = 0; i < words.length;) {
|
|
170
|
+
let j = i; while (j < words.length && words[j].level === words[i].level) j++;
|
|
171
|
+
const run = words.slice(i, j);
|
|
172
|
+
order.push(...(words[i].level === 'R' ? run.reverse() : run)); i = j;
|
|
173
|
+
}
|
|
174
|
+
const items = []; let x = 0;
|
|
175
|
+
for (const word of order) { if (word.box) items.push([word.box,x,0]); x += word.box ? word.box.w : word.w; }
|
|
109
176
|
return mathCompose(items,x,{...extra,class:extra.class || 'ord'});
|
|
110
177
|
}
|
|
111
178
|
|
|
@@ -114,7 +181,7 @@ function mathRule(w, thickness, y = 0) {
|
|
|
114
181
|
'<path data-math-rule="" d="M0 ' + mathNumber(y) + 'H' + mathNumber(w) + 'v' + mathNumber(thickness) + 'H0Z"/>',{inkTop:y,inkBottom:y+thickness});
|
|
115
182
|
}
|
|
116
183
|
|
|
117
|
-
function mathStretch(value, target, c, horizontal = false) {
|
|
184
|
+
function mathStretch(value, target, c, horizontal = false, accent = false, exact = false) {
|
|
118
185
|
if (!value || value === '.') return mathBox();
|
|
119
186
|
const cp = value.codePointAt(0), id = MATH_FONT.chars[cp];
|
|
120
187
|
if (id === undefined) return mathFallbackGlyph(value,c,{variant:'roman',stretchTarget:target,
|
|
@@ -161,9 +228,13 @@ function mathStretch(value, target, c, horizontal = false) {
|
|
|
161
228
|
svg:'<g transform="scale('+mathNumber(ratio)+' 1)">'+natural.svg+'</g>',glyph:undefined};
|
|
162
229
|
}
|
|
163
230
|
let last = natural;
|
|
164
|
-
|
|
231
|
+
// An extensible arrow over a label is built to the label's width, as TeX's arrow fill is, not to the next designed size.
|
|
232
|
+
for (const [glyph,advance] of exact && construction.assembly?.parts?.some(p=>p[4]) ? [] : construction.variants || []) {
|
|
233
|
+
const wide = advance * mathScale(c) / MATH_FONT.units >= target;
|
|
234
|
+
// TeX sets an accent in the widest variant no wider than its base.
|
|
235
|
+
if (accent && wide && advance * mathScale(c) / MATH_FONT.units > target) return last;
|
|
165
236
|
last = shape(glyph,advance);
|
|
166
|
-
if (
|
|
237
|
+
if (wide) return last;
|
|
167
238
|
}
|
|
168
239
|
const a = construction.assembly;
|
|
169
240
|
if (!a?.parts?.length || !a.parts.some(p=>p[4])) {
|
|
@@ -231,6 +302,19 @@ function mathSpace(left, right, c) {
|
|
|
231
302
|
return s*({a:3,b:4,c:5})[code]/18;
|
|
232
303
|
}
|
|
233
304
|
|
|
305
|
+
// A character noad: a plain symbol, with or without scripts; TeX reduces a group of one ordinary symbol to that symbol.
|
|
306
|
+
function mathCharacterNode(n) {
|
|
307
|
+
if (n?.type==='scripts') return mathCharacterNode(n.base);
|
|
308
|
+
if (n?.type==='row' && n.group && n.children.length===1 && (n.children[0].class || 'ord')==='ord') return mathCharacterNode(n.children[0]);
|
|
309
|
+
// A colour or font declaration styles the symbol itself. unicode-math maps \mathbb, \mathcal, \mathfrak and \mathbfit
|
|
310
|
+
// to characters; \mathrm, \mathit, \mathbf, \mathsf, \mathtt and \textcolor make a group.
|
|
311
|
+
if (n?.type==='style' && !n.declaration && Object.keys(n).every(key=>['type','body','color','variant'].includes(key))) {
|
|
312
|
+
if (n.body?.type!=='row') return mathCharacterNode(n.body);
|
|
313
|
+
if (!n.color && n.variant && !['roman','italic','bold','sans-serif','monospace'].includes(n.variant)) return mathCharacterNode(n.body.children[0]);
|
|
314
|
+
}
|
|
315
|
+
return n?.type==='glyph' && !n.delimiterSize;
|
|
316
|
+
}
|
|
317
|
+
|
|
234
318
|
function mathRow(children,c) {
|
|
235
319
|
const boxes=children.map(n=>{
|
|
236
320
|
const box=mathLayout(n,c);
|
|
@@ -243,18 +327,19 @@ function mathRow(children,c) {
|
|
|
243
327
|
for (let k=0;k<significant.length;k++) {
|
|
244
328
|
const i=significant[k], b=boxes[i];
|
|
245
329
|
if (b.class!=='bin') continue;
|
|
246
|
-
const before=boxes[significant[k-1]]?.class, after=boxes[significant[k+1]]?.class;
|
|
330
|
+
const before=boxes[significant[k-1]]?.middle?'open':boxes[significant[k-1]]?.class, after=boxes[significant[k+1]]?.class;
|
|
247
331
|
if (!before || ['bin','op','rel','open','punct'].includes(before) || !after || ['rel','close','punct'].includes(after)) b.class='ord';
|
|
248
332
|
}
|
|
249
|
-
const items=[];let x=0,previous=null;
|
|
250
|
-
for (const b of boxes) {
|
|
333
|
+
const items=[];let x=0,previous=null,adjacent=false;
|
|
334
|
+
for (const [i,b] of boxes.entries()) {
|
|
251
335
|
if (!b.space) {
|
|
252
|
-
//
|
|
253
|
-
if(previous?.italic && previous.class!=='op')x+=previous.italic;
|
|
336
|
+
// Appendix G rule 17 as LuaTeX applies it: a character's italic correction is kept only before another character.
|
|
337
|
+
if(previous?.italic && previous.class!=='op' && adjacent && mathCharacterNode(children[i]))x+=previous.italic;
|
|
254
338
|
x+=mathSpace(previous?.class,b.class,c);
|
|
255
339
|
}
|
|
256
340
|
items.push([b,x,0]);x+=b.w;
|
|
257
341
|
if (!b.space) previous=b;
|
|
342
|
+
adjacent=!b.space;
|
|
258
343
|
}
|
|
259
344
|
const last=boxes.at(-1);
|
|
260
345
|
return mathCompose(items,x,{class:boxes.length===1?boxes[0].class:'ord',italic:boxes.length!==1 && last?.class==='op'?0:last?.italic || 0,rowItems:items,
|
|
@@ -269,37 +354,7 @@ function mathKern(b,corner,height) {
|
|
|
269
354
|
return (values[i] || 0)*b.unitScale;
|
|
270
355
|
}
|
|
271
356
|
|
|
272
|
-
function mathContourBands(box, dy = 0) {
|
|
273
|
-
if (!box.unitScale || box.extended) return null;
|
|
274
|
-
const profile = MATH_FONT.profile(box.glyph);
|
|
275
|
-
if (!profile) return null;
|
|
276
|
-
const bands = [], step = MATH_FONT.edgeStep, unit = box.unitScale;
|
|
277
|
-
const x = box.glyphX || 0, y = (box.glyphY || 0) + dy, radius = (box.stroke || 0) / 2;
|
|
278
|
-
for (let i = profile.length - 1; i > 0; i--) if (profile[i]) {
|
|
279
|
-
bands.push({top: y - (profile[0] + i * step) * unit - radius,
|
|
280
|
-
bottom: y - (profile[0] + (i - 1) * step) * unit + radius,
|
|
281
|
-
left: x + profile[i][0] * unit - radius, right: x + profile[i][1] * unit + radius});
|
|
282
|
-
}
|
|
283
|
-
return bands;
|
|
284
|
-
}
|
|
285
|
-
|
|
286
357
|
const mathScriptGap = c => c.screen ? Math.max(.035 * mathScale(c), .9 / (c.screen.fontSize * c.screen.pixelRatio)) : .025 * mathScale(c);
|
|
287
|
-
function mathContourScript(base, script, dy, nominal, c) {
|
|
288
|
-
const a = mathContourBands(base);
|
|
289
|
-
if (!a) return nominal;
|
|
290
|
-
const b = mathContourBands(script, dy) || [{top: script.inkTop + dy, bottom: script.inkBottom + dy,
|
|
291
|
-
left: script.left, right: script.right}];
|
|
292
|
-
const gap = mathScriptGap(c);
|
|
293
|
-
let j = 0, edge = -Infinity;
|
|
294
|
-
for (const left of a) {
|
|
295
|
-
while (j < b.length && b[j].bottom + gap < left.top) j++;
|
|
296
|
-
for (let k = j; k < b.length && b[k].top <= left.bottom + gap; k++) {
|
|
297
|
-
if (b[k].bottom + gap >= left.top) edge = Math.max(edge, left.right - b[k].left);
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
return Number.isFinite(edge) ? Math.max(base.glyphX || 0, edge + gap) : nominal;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
358
|
function mathScripts(n,c) {
|
|
304
359
|
const b=mathLayout(n.base,c), up=n.sup?mathLayout(n.sup,mathScriptStyle(c)):null,
|
|
305
360
|
down=n.sub?mathLayout(n.sub,mathScriptStyle(c,true)):null;
|
|
@@ -316,8 +371,8 @@ function mathScripts(n,c) {
|
|
|
316
371
|
}
|
|
317
372
|
return mathCompose(items,w,{class:b.class});
|
|
318
373
|
}
|
|
319
|
-
const base=b.scriptBase || b,baseAscent
|
|
320
|
-
upDescent=up?.inkBottom || 0,downAscent=-(down?.inkTop || 0)
|
|
374
|
+
const base=b.scriptBase || b,boxed=base.glyph===undefined || base.extended,baseAscent=boxed?base.h:-base.inkTop,baseDescent=boxed?base.d:base.inkBottom,
|
|
375
|
+
upDescent=up?.inkBottom || 0,downAscent=-(down?.inkTop || 0);
|
|
321
376
|
let rise=up?Math.max(mathConstant(c.cramped?'SuperscriptShiftUpCramped':'SuperscriptShiftUp',c,0.36),
|
|
322
377
|
upDescent+mathConstant('SuperscriptBottomMin',c,0.1),boxed?baseAscent-mathConstant('SuperscriptBaselineDropMax',c,0.25):0):0;
|
|
323
378
|
let drop=down?Math.max(mathConstant('SubscriptShiftDown',c,0.2),
|
|
@@ -334,7 +389,7 @@ function mathScripts(n,c) {
|
|
|
334
389
|
const kern=Math.min(mathKern(base,0,rise-upDescent)+mathKern(up,3,-upDescent),mathKern(base,0,baseAscent)+mathKern(up,3,baseAscent-rise));
|
|
335
390
|
// A large operator's italic correction moves its subscript left, not its superscript right.
|
|
336
391
|
const nominal=b.w+(b.large?0:b.italic || 0)+kern;
|
|
337
|
-
let x=
|
|
392
|
+
let x=nominal;
|
|
338
393
|
// A superscript beside an over-accent clears the accent's ink as well as the letter's.
|
|
339
394
|
const a=b.accentInk,gap=mathScriptGap(c);
|
|
340
395
|
if(a && up.inkTop-rise<a.bottom+gap && up.inkBottom-rise+gap>a.top)x=Math.max(x,a.right+gap-up.left);
|
|
@@ -343,8 +398,7 @@ function mathScripts(n,c) {
|
|
|
343
398
|
if (down) {
|
|
344
399
|
const kern=Math.min(mathKern(base,2,downAscent-drop)+mathKern(down,1,downAscent),mathKern(base,2,-baseDescent)+mathKern(down,1,drop-baseDescent));
|
|
345
400
|
const nominal=b.w-(b.large?b.italic || 0:0)+kern;
|
|
346
|
-
|
|
347
|
-
items.push([down,x,drop]);w=Math.max(w,x+down.w);
|
|
401
|
+
items.push([down,nominal,drop]);w=Math.max(w,nominal+down.w);
|
|
348
402
|
}
|
|
349
403
|
// \prescript's scripts end together at its base.
|
|
350
404
|
if (n.pre) for (const item of items.slice(1)) item[1]=w-item[0].w;
|
|
@@ -370,16 +424,17 @@ function mathFraction(n,c,width) {
|
|
|
370
424
|
const min=mathConstant(display?'StackDisplayStyleGapMin':'StackGapMin',c,display?0.4:0.15),gap=rise+drop-top.d-bottom.h;
|
|
371
425
|
if (gap<min) {rise+=(min-gap)/2;drop+=(min-gap)/2;}
|
|
372
426
|
}
|
|
373
|
-
//
|
|
374
|
-
|
|
375
|
-
const
|
|
376
|
-
const
|
|
377
|
-
|
|
427
|
+
// TeX's \nulldelimiterspace (1.2 pt, unscaled in scripts) flanks only an unfenced fraction, outside its rule;
|
|
428
|
+
// a fence's own glyphs bound \binom, and amsmath's \cfrac kerns its right one away.
|
|
429
|
+
const pad=n.left || n.right?0:c.size*0.12,inner=Math.max(top.w,bottom.w),w=inner+pad+(n.strut?0:pad);
|
|
430
|
+
const numeratorX=pad+(n.align==='l'?0:n.align==='r'?inner-top.w:(inner-top.w)/2);
|
|
431
|
+
const items=[[top,numeratorX,-rise],[bottom,pad+(inner-bottom.w)/2,drop]];
|
|
432
|
+
if (line) items.push([mathRule(inner,line,-axis-line/2),pad,0]);
|
|
378
433
|
// LaTeX's \frac, \binom and \genfrac brace their fraction: an ordinary atom, not TeX's bare inner.
|
|
379
434
|
const b=mathCompose(items,w,{class:'ord',innerLines:top.lines || 1,fitted:!!top.fitted});
|
|
380
435
|
if(width!==undefined && c.screen)b.refit=ratio=>mathFraction(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()},width);
|
|
381
|
-
// TeX's generalized fractions fence at least
|
|
382
|
-
if (n.left || n.right) return {...mathFenceBoxes(n.left || '',n.right || '',b,c,undefined,display?2.
|
|
436
|
+
// TeX's generalized fractions fence at least LuaTeX's \Umathfractiondelsize: 24 pt in display, 10.1 pt in text.
|
|
437
|
+
if (n.left || n.right) return {...mathFenceBoxes(n.left || '',n.right || '',b,c,undefined,display?2.4:1.01),class:'ord'};
|
|
383
438
|
return b;
|
|
384
439
|
}
|
|
385
440
|
|
|
@@ -399,18 +454,57 @@ function mathRoot(n,c) {
|
|
|
399
454
|
const b=mathCompose(items,w);b.h+=extra;return b;
|
|
400
455
|
}
|
|
401
456
|
|
|
402
|
-
function mathFenceBoxes(left,right,body,c,size,least=
|
|
403
|
-
const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(
|
|
404
|
-
|
|
457
|
+
function mathFenceBoxes(left,right,body,c,size,least=0,measure=body) {
|
|
458
|
+
const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(measure.h-axis,measure.d+axis),target=size?size*mathScale(c):Math.max(least*mathScale(c),2*reach*0.901,2*reach-0.5*mathScale(c));
|
|
459
|
+
// An empty side is TeX's null delimiter: \nulldelimiterspace wide.
|
|
460
|
+
const side=value=>!value || value==='.'?mathBox(c.size*0.12):mathDelimiter(value,target,c),a=side(left),b=side(right);
|
|
405
461
|
return mathCompose([[a,0,0],[body,a.w,0],[b,a.w+body.w,0]],a.w+body.w+b.w,{class:'inner'});
|
|
406
462
|
}
|
|
407
463
|
|
|
464
|
+
// MathML's menclose notations, drawn with the rule thickness \boxed uses around a 0.2 em padding.
|
|
465
|
+
function mathEnclose(n,c) {
|
|
466
|
+
const set=new Set(n.notation),s=mathScale(c),line=mathConstant('FractionRuleThickness',c,0.04),pad=0.2*s,
|
|
467
|
+
b=set.has('radical')?mathLayout({type:'root',body:n.body},c):mathLayout(n.body,c),
|
|
468
|
+
has=(...names)=>names.some(name=>set.has(name)),round=has('circle'),
|
|
469
|
+
left=has('box','roundedbox','circle','left','longdiv','phasorangle'),right=has('box','roundedbox','circle','right','actuarial','madruwb'),
|
|
470
|
+
top=has('box','roundedbox','circle','top','longdiv','actuarial'),bottom=has('box','roundedbox','circle','bottom','madruwb','phasorangle'),
|
|
471
|
+
// A circle is the ellipse through the padded box's corners; longdiv's bracket and phasorangle's slope need room at the left.
|
|
472
|
+
grow=round?(Math.SQRT2-1)/2:0,padL=(left?pad:0)+(has('longdiv')?0.3*s:has('phasorangle')?0.4*s:0)+grow*(b.w+2*pad),padR=(right?pad:0)+grow*(b.w+2*pad),
|
|
473
|
+
padT=(top?pad:0)+grow*(b.h+b.d+2*pad),padB=(bottom?pad:0)+grow*(b.h+b.d+2*pad),
|
|
474
|
+
w=padL+b.w+padR,y0=-b.h-padT,y1=b.d+padB,x0=has('longdiv','phasorangle')?padL-pad:0,m=mathNumber,paths=[];
|
|
475
|
+
const segment=(xa,ya,xb,yb)=>paths.push('M'+m(xa)+' '+m(ya)+'L'+m(xb)+' '+m(yb));
|
|
476
|
+
if(has('box'))paths.push('M0 '+m(y0)+'H'+m(w)+'V'+m(y1)+'H0Z');
|
|
477
|
+
else if(has('roundedbox')) {const r=Math.min(0.25*s,(y1-y0)/2,w/2);paths.push('M'+m(r)+' '+m(y0)+'H'+m(w-r)+'A'+m(r)+' '+m(r)+' 0 0 1 '+m(w)+' '+m(y0+r)+'V'+m(y1-r)+'A'+m(r)+' '+m(r)+' 0 0 1 '+m(w-r)+' '+m(y1)+'H'+m(r)+'A'+m(r)+' '+m(r)+' 0 0 1 0 '+m(y1-r)+'V'+m(y0+r)+'A'+m(r)+' '+m(r)+' 0 0 1 '+m(r)+' '+m(y0)+'Z');}
|
|
478
|
+
else if(round) {const rx=w/2,ry=(y1-y0)/2;paths.push('M0 '+m(y0+ry)+'A'+m(rx)+' '+m(ry)+' 0 1 0 '+m(w)+' '+m(y0+ry)+'A'+m(rx)+' '+m(ry)+' 0 1 0 0 '+m(y0+ry)+'Z');}
|
|
479
|
+
else {
|
|
480
|
+
if(set.has('left'))segment(0,y0,0,y1);
|
|
481
|
+
if(has('right','actuarial','madruwb'))segment(w,y0,w,y1);
|
|
482
|
+
if(has('top','longdiv','actuarial'))segment(x0,y0,w,y0);
|
|
483
|
+
if(has('bottom','madruwb','phasorangle'))segment(has('phasorangle')?0:0,y1,w,y1);
|
|
484
|
+
}
|
|
485
|
+
if(set.has('longdiv'))paths.push('M'+m(x0)+' '+m(y0)+'Q'+m(x0+0.3*s)+' '+m((y0+y1)/2)+' '+m(x0-0.05*s)+' '+m(y1));
|
|
486
|
+
if(set.has('phasorangle'))segment(0,y1,x0+0.1*s,y0);
|
|
487
|
+
if(set.has('horizontalstrike'))segment(0,-mathConstant('AxisHeight',c,0.25),w,-mathConstant('AxisHeight',c,0.25));
|
|
488
|
+
if(set.has('verticalstrike'))segment(w/2,y0,w/2,y1);
|
|
489
|
+
if(set.has('updiagonalstrike'))segment(0,y1,w,y0);
|
|
490
|
+
if(set.has('downdiagonalstrike'))segment(0,y0,w,y1);
|
|
491
|
+
if(set.has('updiagonalarrow')) {const tip=0.2*s;segment(0,y1,w,y0);paths.push('M'+m(w-tip)+' '+m(y0)+'H'+m(w)+'V'+m(y0+tip));}
|
|
492
|
+
const fill=n.background?'<path d="M0 '+m(y0)+'H'+m(w)+'V'+m(y1)+'H0Z" fill="'+mathEscape(n.background)+'" fill-opacity="1"/>':'',
|
|
493
|
+
stroke='<path d="'+paths.join('')+'" fill="none" stroke="currentColor" stroke-opacity="1" stroke-width="'+m(line)+'"/>';
|
|
494
|
+
const box=mathCompose([[b,padL,0]],w,{h:-y0,d:y1,class:b.class});
|
|
495
|
+
box.svg=fill+stroke+box.svg;
|
|
496
|
+
if(n.color)box.svg='<g fill="'+mathEscape(n.color)+'" color="'+mathEscape(n.color)+'" fill-opacity="1" stroke-opacity="1">'+box.svg+'</g>';
|
|
497
|
+
return box;
|
|
498
|
+
}
|
|
499
|
+
|
|
408
500
|
function mathAccent(n,c) {
|
|
409
501
|
const position=n.position || 'over';let nucleus=n.base;
|
|
410
502
|
while(nucleus?.type==='style' || (nucleus?.type==='row' && nucleus.children.length===1))nucleus=nucleus.type==='style'?nucleus.body:nucleus.children[0];
|
|
411
503
|
const b=mathLayout(n.base,position==='under'?c:{...c,cramped:true,dotless:nucleus?.type==='glyph' && !n.overlay && /^[\u0300-\u036f\u20d0-\u20ff]$/u.test(n.value)}),s=mathScale(c);
|
|
412
504
|
// A brace is an operator: centred on its base, with no italic correction to shift its labels.
|
|
413
|
-
|
|
505
|
+
// TeX's rules 12 and 18a: scripts on an accented character sit by the character; a bar, or an accent over more than one character, is a box.
|
|
506
|
+
const brace=n.limits==='always',bar=/^(overline|underline|¯|_)$/.test(n.value) && !n.overlay,character=!bar && nucleus?.type==='glyph',
|
|
507
|
+
semantics={class:n.class || (brace?'op':b.class),limits:n.limits || b.limits,italic:brace || !(character || n.overlay)?0:b.italic,accent:b.accent,scriptBase:character || n.overlay?b.scriptBase || b:undefined};
|
|
414
508
|
if(n.overlay) {
|
|
415
509
|
const w=Math.max(b.w,0.2*s),line=mathConstant('FractionRuleThickness',c,0.04);
|
|
416
510
|
const rising='M0 '+mathNumber(b.d)+'L'+mathNumber(w)+' '+mathNumber(-b.h),
|
|
@@ -423,21 +517,29 @@ function mathAccent(n,c) {
|
|
|
423
517
|
}
|
|
424
518
|
if (n.value==='overline' || n.value==='underline' || n.value==='¯' || n.value==='_') {
|
|
425
519
|
const over=position!=='under',line=mathConstant(over?'OverbarRuleThickness':'UnderbarRuleThickness',c,0.04),gap=mathConstant(over?'OverbarVerticalGap':'UnderbarVerticalGap',c,0.1);
|
|
520
|
+
// amsmath's \varliminf underlines lim over a strut 0.2 ex@ deep.
|
|
521
|
+
if(n.varlim && !over)b.d=Math.max(b.d,0.02*s);
|
|
426
522
|
const y=over?-b.h-gap-line:b.d+gap;
|
|
427
523
|
const result=mathCompose([[b,0,0],[mathRule(b.w,line,y),0,0]],b.w,semantics);
|
|
428
524
|
result[over?'h':'d']+=mathConstant(over?'OverbarExtraAscender':'UnderbarExtraDescender',c,0.04);
|
|
429
525
|
return result;
|
|
430
526
|
}
|
|
431
527
|
const names={hat:'̂',widehat:'̂',tilde:'̃',widetilde:'̃',bar:'̄',vec:'⃗',dot:'̇',ddot:'̈',dddot:'⃛',ddddot:'⃜',acute:'́',grave:'̀',breve:'̆',check:'̌',overbrace:'⏞',underbrace:'⏟',overrightarrow:'→',overleftarrow:'←',overleftrightarrow:'↔'};
|
|
432
|
-
//
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
528
|
+
// The font's accent attachment aligns both top and bottom accents; a through stroke stays centered.
|
|
529
|
+
// TeX's stretchy arrows and harpoons over or under a formula are the font's combining arrows, set as accents.
|
|
530
|
+
const arrows=n.stretch && n.class!=='op' && (position==='over'?{'→':'⃗','←':'⃖','↔':'⃡','↼':'⃐','⇀':'⃑'}:position==='under'?{'→':'⃯','←':'⃮','↔':'͍'}:{}),
|
|
531
|
+
value=arrows?.[n.value] && MATH_FONT.chars[arrows[n.value].codePointAt(0)]!==undefined?arrows[n.value]:names[n.value] || n.value,accentStyle={...c,flattenAccent:position!=='under' && b.h>mathConstant('FlattenedAccentBaseHeight',c,0.65)},
|
|
532
|
+
a=n.stretch?mathStretch(value,Math.max(b.w,s*0.3),accentStyle,true,n.class!=='op'):mathGlyph(value,accentStyle,{variant:'roman'}),
|
|
533
|
+
x=position==='through' || brace?(b.w-a.w)/2:(b.accent ?? b.w/2)-(a.accent ?? a.w/2),combining=/^[\u0300-\u036f\u20d0-\u20ff]$/u.test(value);
|
|
436
534
|
let y;
|
|
437
535
|
if(position==='through')y=0;
|
|
438
|
-
|
|
439
|
-
else if(
|
|
536
|
+
// A glyph the font draws below the baseline hangs from the base's depth, as LuaTeX sets a bottom accent.
|
|
537
|
+
else if(position==='under')y=a.inkTop>=0?b.d:b.d+mathConstant('UnderbarVerticalGap',c,0.1)-a.inkTop;
|
|
538
|
+
// A glyph drawn above the x-height keeps its designed height, raised by the base's height above AccentBaseHeight.
|
|
539
|
+
else if(combining || a.inkBottom<0)y=-Math.max(0,b.h-mathConstant('AccentBaseHeight',c,0.48));
|
|
440
540
|
else y=-b.h-mathConstant('OverbarVerticalGap',c,0.1)-a.inkBottom;
|
|
541
|
+
// amsmath's \varinjlim and \varprojlim stack lim, a 1.5 ex@ kern, the arrow and a kern of -1 ex@ (ex@ is 1 pt).
|
|
542
|
+
if(n.varlim && position==='under')return mathCompose([[b,0,0],[a,x,b.d+0.15*s+a.h]],b.w,{...semantics,d:b.d+0.15*s+a.h+a.d-0.1*s});
|
|
441
543
|
// A combining under-accent's box is its ink: its advance box rests far below the mark.
|
|
442
544
|
if(position==='under')return mathCompose([[b,0,0],[{...a,h:-a.inkTop,d:a.inkBottom},x,y]],b.w,semantics);
|
|
443
545
|
if(position==='over') {
|
|
@@ -458,8 +560,10 @@ function mathTable(n,c) {
|
|
|
458
560
|
if(paired && i%2) return mathRow([{type:'row',children:[]},...(cell.type==='row'?cell.children:[cell])],cellStyle);
|
|
459
561
|
return mathLayout(cell,cellStyle);
|
|
460
562
|
}));
|
|
461
|
-
|
|
462
|
-
|
|
563
|
+
// A cell spanning columns (\multicolumn, \hdotsfor) and an \intertext line do not set their columns' widths.
|
|
564
|
+
const own=(r,i)=>{const cell=n.rows[r][i];return !(cell?.span>1 || cell?.covered || cell?.intertext);};
|
|
565
|
+
const cols=Math.max(n.align?.length || 0,n.pairs?2*n.pairs:0,...rows.map((r,k)=>n.rows[k][0]?.intertext?0:r.length)),s=mathScale(c),cs=mathScale(cellStyle),
|
|
566
|
+
widths=Array.from({length:cols},(_,i)=>Math.max(0,...rows.map((row,r)=>own(r,i)?row[i]?.w || 0:0))),
|
|
463
567
|
align=n.env==='eqnarray'?Array.from({length:cols},(_,i)=>['r','c','l'][i%3]):n.align || Array(cols).fill('c');
|
|
464
568
|
if(rows.length*(cols+(n.columnInsertions?.length || 0))+(n.columnRules?.length || 0)+(n.rowRules?.length || 0)>100000)
|
|
465
569
|
throw Object.assign(new Error('Array composition exceeds the rendering budget'),{code:'resource-limit'});
|
|
@@ -468,54 +572,101 @@ function mathTable(n,c) {
|
|
|
468
572
|
if(insertion.before<0 || insertion.before>cols) throw Object.assign(new Error('Array insertion exceeds its columns'),{code:'invalid-alignment'});
|
|
469
573
|
insertions[insertion.before].push({...insertion,box:mathLayout(insertion.body,cellStyle)});
|
|
470
574
|
}
|
|
575
|
+
// LaTeX's array keeps half its column gap (\arraycolsep) outside the edge columns. Rules take no width;
|
|
576
|
+
// each further rule in a run adds \doublerulesep.
|
|
577
|
+
// amsmath's smallmatrix has a thin space at each side and a thick space between its columns.
|
|
578
|
+
const ruleRuns=Array(cols+1).fill(0),edge=/^d?array$/.test(n.env)?s/2:/smallmatrix$/.test(n.env)?s/6:0;
|
|
579
|
+
for(const boundary of n.columnRules || [])if(boundary>=0 && boundary<=cols)ruleRuns[boundary]++;
|
|
580
|
+
const ruleSep=0.2*s,ruleStarts=[];
|
|
471
581
|
const gaps=Array.from({length:cols+1},(_,i)=>{
|
|
472
|
-
let gap=i===0 || i===cols?
|
|
582
|
+
let gap=i===0 || i===cols?edge:paired?(i%2?0:/^(alignat|alignedat)$/.test(n.env)?0:2*s):/smallmatrix$/.test(n.env)?5/18*s:small?cs/3:n.env==='CD'?0:s;
|
|
473
583
|
if(insertions[i].some(item=>item.replaceGap))gap=0;
|
|
474
|
-
|
|
584
|
+
const content=gap+insertions[i].reduce((sum,item)=>sum+item.box.w,0);
|
|
585
|
+
ruleStarts.push(i===0?0:i===cols?content:content/2);
|
|
586
|
+
return content+Math.max(0,ruleRuns[i]-1)*ruleSep;
|
|
475
587
|
});
|
|
588
|
+
// A spanning cell wider than its columns widens the last of them, as TeX's \multispan does.
|
|
589
|
+
for(const [r,row] of n.rows.entries())for(const [i,cell] of row.entries())if(cell?.span>1 && !cell.dots) {
|
|
590
|
+
const last=Math.min(cols,i+cell.span)-1,room=widths.slice(i,last+1).reduce((a,b)=>a+b,0)+gaps.slice(i+1,last+1).reduce((a,b)=>a+b,0);
|
|
591
|
+
if(rows[r][i].w>room)widths[last]+=rows[r][i].w-room;
|
|
592
|
+
}
|
|
476
593
|
const starts=[],ends=[],boundaries=[],insertionItems=[];let w=0;
|
|
477
594
|
for(let i=0;i<=cols;i++) {
|
|
478
595
|
const contentWidth=insertions[i].reduce((sum,item)=>sum+item.box.w,0);
|
|
479
|
-
boundaries.push(w+
|
|
596
|
+
boundaries.push(w+ruleStarts[i]);
|
|
480
597
|
let x=w+(gaps[i]-contentWidth)/2;
|
|
481
598
|
for(const item of insertions[i]) {insertionItems.push([item.box,x]);x+=item.box.w;}
|
|
482
599
|
w+=gaps[i];if(i<cols) {starts.push(w);w+=widths[i];ends.push(w);}
|
|
483
600
|
}
|
|
484
601
|
const insertionHeight=Math.max(0,...insertionItems.map(([b])=>b.h)),insertionDepth=Math.max(0,...insertionItems.map(([b])=>b.d)),
|
|
485
|
-
|
|
486
|
-
|
|
602
|
+
// LaTeX's array strut is 0.7 and 0.3 of a 1.2 em baseline skip (cases stretches it by 1.2); rows abut,
|
|
603
|
+
// and only the display alignments add \jot between them.
|
|
604
|
+
strut=small || n.env==='CD'?[0.7,0.2]:/cases$/.test(n.env)?[1.008,0.432]:[0.84,0.36],
|
|
605
|
+
rowGap=small?0.2:n.env==='CD'?0.3:/^(align|flalign|split|[lr]?gather|eqnarray|multline)/.test(n.env)?0.3:0,
|
|
606
|
+
heights=rows.map(row=>Math.max(strut[0]*cs,insertionHeight,...row.map(b=>b.h))),
|
|
607
|
+
depths=rows.map(row=>Math.max(strut[1]*cs,insertionDepth,...row.map(b=>b.d))),baselines=[];
|
|
608
|
+
// A full-width rule between rows takes \arrayrulewidth of height; a run of them steps by \doublerulesep.
|
|
609
|
+
const line=mathConstant('FractionRuleThickness',c,0.04),hlines=Array(rows.length+1).fill(0),hlineStarts=[];
|
|
610
|
+
for(const rule of n.rowRules || [])if(rule.from===undefined && rule.to===undefined && rule.before>=0 && rule.before<=rows.length)hlines[rule.before]++;
|
|
611
|
+
const hlineSpace=k=>k?line+(k-1)*ruleSep:0;
|
|
487
612
|
let total=0;
|
|
488
|
-
|
|
613
|
+
// amsmath's subarray has no strut: its rows are a baseline skip apart (the script font's stack shifts), or a
|
|
614
|
+
// lineskip of three rules apart where they would come closer.
|
|
615
|
+
// smallmatrix's rows are 6 ex@ apart with a lineskip of 1.5 ex@ (ex@ is 1 pt).
|
|
616
|
+
const skip=n.env==='subarray' || n.env==='substack'?{base:(mathConstant('StackTopShiftUp',c,0.444)+mathConstant('StackBottomShiftDown',c,0.345))*cs/s,line:3*mathConstant('FractionRuleThickness',cellStyle,0.04)}:
|
|
617
|
+
/smallmatrix$/.test(n.env)?{base:0.6*s,line:0.15*s}:n.env==='CD'?{base:2*cs,line:0.3*cs}:null;
|
|
618
|
+
if(skip)for(const [r,row] of rows.entries()) {heights[r]=Math.max(0,...row.map(b=>b.h));depths[r]=Math.max(0,...row.map(b=>b.d));}
|
|
619
|
+
for(let r=0;r<=rows.length;r++) {
|
|
620
|
+
hlineStarts.push(total);total+=hlineSpace(hlines[r]);
|
|
621
|
+
if(r===rows.length)break;
|
|
489
622
|
total+=heights[r];baselines.push(total);total+=depths[r];
|
|
490
|
-
if(r+1<rows.length)total+=
|
|
623
|
+
if(r+1<rows.length)total+=skip?Math.max(skip.base-depths[r]-heights[r+1],skip.line):rowGap*cs+(n.rowGaps?.[r] || 0)*s;
|
|
491
624
|
}
|
|
492
625
|
const offset=n.position==='t'?-(baselines[0] || 0):n.position==='b'?-(baselines.at(-1) || 0):-total/2-mathConstant('AxisHeight',c,0.25),items=[];
|
|
493
626
|
for(let r=0;r<rows.length;r++) {
|
|
627
|
+
if(n.rows[r][0]?.intertext) {items.push([rows[r][0],0,baselines[r]+offset]);continue;}
|
|
494
628
|
for(let i=0;i<cols;i++) {
|
|
495
|
-
const
|
|
496
|
-
|
|
629
|
+
const cell=n.rows[r][i];
|
|
630
|
+
if(cell?.covered)continue;
|
|
631
|
+
const last=cell?.span>1?Math.min(cols,i+cell.span)-1:i,width=(ends[last] ?? starts[i])-starts[i];
|
|
632
|
+
// amsmath's \hdotsfor: dots 3 mu apart times its spacing, spread evenly across the columns it fills.
|
|
633
|
+
if(cell?.dots) {
|
|
634
|
+
const dot=mathGlyph('.',cellStyle,{variant:'roman'}),step=dot.w+cell.dots*3/18*cs,count=Math.max(1,Math.floor(width/step)),spread=width/count;
|
|
635
|
+
for(let k=0;k<count;k++)items.push([dot,starts[i]+k*spread+(spread-dot.w)/2,baselines[r]+offset]);
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
const b=rows[r][i] || mathBox(),a=cell?.spanAlign || (/^multlined?$/.test(n.env) && cols===1?(r===0?'l':r===rows.length-1?'r':'c'):align[i] || 'c'),
|
|
639
|
+
dx=a==='r'?width-b.w:a==='l'?0:(width-b.w)/2;
|
|
497
640
|
items.push([b,starts[i]+dx,baselines[r]+offset]);
|
|
498
641
|
}
|
|
499
642
|
for(const [b,x] of insertionItems)items.push([b,x,baselines[r]+offset]);
|
|
500
643
|
}
|
|
501
|
-
const
|
|
502
|
-
|
|
644
|
+
const ruleCounts=new Map(),band=r=>[hlineStarts[r]+hlineSpace(hlines[r]),hlineStarts[r+1]+hlineSpace(hlines[r+1])];
|
|
645
|
+
const vertical=(x,from,to,dashed)=>items.push([mathBox(line/2,0,to-from,'<path data-math-line="vertical" d="M0 0v'+mathNumber(to-from)+'" fill="none" stroke="currentColor" stroke-width="'+mathNumber(line)+'"'+(dashed?' stroke-dasharray="'+mathNumber(.15*s)+' '+mathNumber(.1*s)+'"':'')+'/>',{left:-line/2}),x,offset+from]);
|
|
646
|
+
// A \multicolumn replaces the rules of the columns it spans (the first column's left rule too) with its own.
|
|
647
|
+
const spans=n.rows.flatMap((row,r)=>row.flatMap((cell,i)=>cell?.span>1 || cell?.spanRules?[{r,i,last:Math.min(cols,i+(cell.span || 1))-1,rules:cell.spanRules || []}]:[]));
|
|
648
|
+
for(const [index,boundary] of (n.columnRules || []).entries()) {
|
|
503
649
|
if(boundary<0 || boundary>cols)throw Object.assign(new Error('Array rule exceeds its columns'),{code:'invalid-rule'});
|
|
504
650
|
const count=ruleCounts.get(boundary) || 0;ruleCounts.set(boundary,count+1);
|
|
505
|
-
const x=boundaries[boundary]+count*0.
|
|
506
|
-
|
|
651
|
+
const x=boundaries[boundary]+count*ruleSep,gaps=spans.filter(span=>span.i<boundary && boundary<=span.last+1 || span.i===0 && boundary===0).map(span=>band(span.r)).sort((a,b)=>a[0]-b[0]);
|
|
652
|
+
let y=0;
|
|
653
|
+
for(const [top,bottom] of gaps) {if(top>y)vertical(x,y,top,n.columnDashes?.[index]);y=Math.max(y,bottom);}
|
|
654
|
+
if(y<total)vertical(x,y,total,n.columnDashes?.[index]);
|
|
507
655
|
}
|
|
656
|
+
for(const span of spans)for(const rule of span.rules)vertical(rule===0?boundaries[span.i]:boundaries[span.last+1],...band(span.r));
|
|
508
657
|
ruleCounts.clear();
|
|
509
658
|
for(const rule of n.rowRules || []) {
|
|
510
659
|
const boundary=rule.before,from=rule.from ?? 0,to=rule.to ?? cols;
|
|
511
660
|
if(boundary<0 || boundary>rows.length || from<0 || to>cols)throw Object.assign(new Error('Array rule exceeds its cells'),{code:'invalid-rule'});
|
|
512
661
|
const count=ruleCounts.get(boundary) || 0;ruleCounts.set(boundary,count+1);
|
|
513
|
-
const
|
|
662
|
+
const full=rule.from===undefined && rule.to===undefined,
|
|
663
|
+
y=(full?hlineStarts[boundary]+line/2+count*ruleSep:boundary===0?0:boundary===rows.length?total:(baselines[boundary-1]+depths[boundary-1]+baselines[boundary]-heights[boundary])/2+count*0.15*s)+offset,
|
|
514
664
|
left=from===0?0:boundaries[from],right=to===cols?w:boundaries[to];
|
|
515
665
|
const stroke='<path data-math-line="horizontal" d="M0 0H'+mathNumber(right-left)+'" fill="none" stroke="currentColor" stroke-width="'+mathNumber(line)+'"'+(rule.dashed?' stroke-dasharray="'+mathNumber(.15*s)+' '+mathNumber(.1*s)+'"':'')+'/>';
|
|
516
666
|
items.push([mathBox(right-left,line/2,line/2,stroke),left,y]);
|
|
517
667
|
}
|
|
518
|
-
|
|
668
|
+
// An array is a \vcenter, an ordinary atom; a fenced one is an inner atom, as \left and \right make it.
|
|
669
|
+
const b=mathCompose(items,Math.max(w,...rows.map((row,r)=>n.rows[r][0]?.intertext?row[0].w:0)),{class:'ord',h:Math.max(0,-offset),d:Math.max(0,total+offset)});
|
|
519
670
|
const delimiters={pmatrix:['(',')'],bmatrix:['[',']'],Bmatrix:['{','}'],vmatrix:['|','|'],Vmatrix:['‖','‖'],
|
|
520
671
|
psmallmatrix:['(',')'],bsmallmatrix:['[',']'],Bsmallmatrix:['{','}'],vsmallmatrix:['|','|'],Vsmallmatrix:['‖','‖'],
|
|
521
672
|
cases:['{',''],dcases:['{',''],rcases:['','}'],drcases:['','}']};
|
|
@@ -530,19 +681,25 @@ function mathLayout(n,c) {
|
|
|
530
681
|
const b=mathLayout({...n,at:undefined},c);
|
|
531
682
|
return {...b,svg:'<g data-math-at="'+n.at+'">'+b.svg+'</g>'};
|
|
532
683
|
}
|
|
684
|
+
// An empty argument shows the placeholder box a missing one does, as a place to tap.
|
|
685
|
+
if(c.spans && n.at!==undefined && n.type==='row' && !n.children.length)
|
|
686
|
+
return mathLayout({type:'glyph',value:'□',variant:'roman',at:n.at},c);
|
|
533
687
|
if(c.budget && ++c.budget.nodes>100000)throw Object.assign(new Error('Mathematical layout exceeds the rendering budget'),{code:'resource-limit'});
|
|
534
688
|
switch(n.type) {
|
|
535
|
-
case 'row':
|
|
689
|
+
case 'row': {const b=mathRow(n.children,c);if(n.group)Object.assign(b,{class:'ord',limits:undefined});return b;}
|
|
536
690
|
case 'glyph': {
|
|
537
|
-
//
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
const
|
|
543
|
-
|
|
691
|
+
// TeX spaces a \middle as a closing atom, and a binary atom after it becomes ordinary.
|
|
692
|
+
const middle=n.delimiter && !n.delimiterSize?{class:'close',middle:true}:{};
|
|
693
|
+
// amsmath's \big to \Bigg are \left and \right around a strut 1.2 to 3 times a parenthesis's height and depth,
|
|
694
|
+
// so TeX's \delimiterfactor and \delimitershortfall choose the size, and the strut sets the box.
|
|
695
|
+
if(n.delimiterSize) {
|
|
696
|
+
const paren=MATH_FONT.glyph(MATH_FONT.chars[40]),s=mathScale(c),strut=n.delimiterSize*(paren[4]-paren[2])/MATH_FONT.units*s,axis=mathConstant('AxisHeight',c,0.25);
|
|
697
|
+
const b=mathDelimiter(n.value,Math.max(strut*0.901,strut-0.5*s),c);
|
|
698
|
+
return {...b,h:Math.max(b.h,axis+strut/2),d:Math.max(b.d,strut/2-axis),class:n.class || 'ord',...middle};
|
|
544
699
|
}
|
|
545
|
-
|
|
700
|
+
if(n.delimiter && c.delimiterTarget)return {...mathDelimiter(n.value,c.delimiterTarget,c),class:n.class || 'ord',...middle};
|
|
701
|
+
if(n.stretch)return {...mathStretch(n.value,c.stretchTarget || mathScale(c),c,true,false,!!c.stretchTarget),class:n.class || 'rel',limits:n.limits,stretchAxis:'horizontal'};
|
|
702
|
+
let b=mathGlyph(n.value,c,{class:n.class || 'ord',...middle,variant:n.variant || (c.variant==='normal'?n.defaultVariant || 'normal':c.variant),large:n.large,limits:n.limits});
|
|
546
703
|
if(n.large && c.display && !c.level) {
|
|
547
704
|
const target=mathConstant('DisplayOperatorMinHeight',c,1.3),a=mathStretch(n.value,target,c);
|
|
548
705
|
b=mathCompose([[a,0,(a.h-a.d)/2-mathConstant('AxisHeight',c,0.25)]],a.w,{class:n.class || 'op',italic:a.italic,limits:n.limits,large:true,glyph:a.glyph,unitScale:a.unitScale});
|
|
@@ -554,18 +711,20 @@ function mathLayout(n,c) {
|
|
|
554
711
|
case 'scripts': return mathScripts(n,c);
|
|
555
712
|
case 'frac': return mathFraction(n,c);
|
|
556
713
|
case 'root': return mathRoot(n,c);
|
|
714
|
+
case 'enclose': return mathEnclose(n,c);
|
|
557
715
|
case 'fence': {
|
|
558
716
|
// A nested fence does not inherit an outer \middle target. Its cached box
|
|
559
717
|
// survives the outer fence's second pass, keeping nested layout linear.
|
|
560
718
|
const cache=c.cache || (c.cache=new WeakMap()),key=[c.size,c.level,c.variant,c.display,c.cramped,c.stretchTarget].join('|');
|
|
561
719
|
let entries=cache.get(n);if(entries?.has(key))return {...entries.get(key)};
|
|
562
|
-
const local={...c,delimiterTarget:undefined};let b=mathLayout(n.body,local);
|
|
720
|
+
const local={...c,delimiterTarget:undefined};let b=mathLayout(n.body,local);const first=b;
|
|
563
721
|
// Only a \middle needs the second pass, sized to the first pass's body.
|
|
564
722
|
if(n.body && mathHasMiddle(n.body)) {
|
|
565
|
-
const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(b.h-axis,b.d+axis),target=Math.max(
|
|
723
|
+
const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(b.h-axis,b.d+axis),target=Math.max(2*reach*0.901,2*reach-0.5*mathScale(c));
|
|
566
724
|
b=mathLayout(n.body,{...local,delimiterTarget:target});
|
|
567
725
|
}
|
|
568
|
-
|
|
726
|
+
// LuaTeX sizes \left and \right from the body as \middle is sized, not from the grown \middle.
|
|
727
|
+
b=mathFenceBoxes(n.left,n.right,b,local,n.size,0,first);if(n.class)b.class=n.class;
|
|
569
728
|
if(!entries)cache.set(n,entries=new Map());entries.set(key,b);return {...b};
|
|
570
729
|
}
|
|
571
730
|
case 'accent': return mathAccent(n,c);
|
|
@@ -591,20 +750,51 @@ function mathLayout(n,c) {
|
|
|
591
750
|
return b;
|
|
592
751
|
}
|
|
593
752
|
case 'overunder': {
|
|
594
|
-
const
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
753
|
+
const s=mathScale(c),ss=mathScale(mathScriptStyle(c)),kind=n.arrow || '',doubled=/^(Leftarrow|Rightarrow|Leftrightarrow)$/.test(kind),
|
|
754
|
+
paired=/^(rightleftharpoons|leftrightharpoons)$/.test(kind),
|
|
755
|
+
label=(x,cramped)=>x && !(n.base?.stretch && !n.diagram && x.type==='row' && !x.children.length)?mathLayout(x,mathScriptStyle(c,cramped)):null;
|
|
756
|
+
let over=label(n.over),under=label(n.under,true);
|
|
757
|
+
// mathtools puts a text control-space beside each double-arrow label, including an empty one.
|
|
758
|
+
if(doubled) {
|
|
759
|
+
const left=kind!=='Rightarrow'?0.333*s:0,right=kind!=='Leftarrow'?0.333*s:0,
|
|
760
|
+
padded=b=>mathCompose([[b || mathBox(),left,0]],(b?.w || 0)+left+right);
|
|
761
|
+
over=padded(over);under=padded(under);
|
|
601
762
|
}
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
763
|
+
// mhchem raises its lower label to a common 1.25 ex top and smashes its height before adding limits.
|
|
764
|
+
if(n.unspaced && under)under={...mathCompose([[under,0,under.h-1.25*MATH_FONT.xHeight/MATH_FONT.units*s]],under.w),h:0};
|
|
765
|
+
const pad=(n.labelPad ?? (doubled?10:14))/18*ss,target=Math.max((n.minWidth || (/^hook/.test(kind)?10/9:1))*s,Math.max(over?.w || 0,under?.w || 0)+pad),
|
|
766
|
+
shift=n.unspaced && n.base.value==='→'?-2/18*ss:/^(leftarrow|rightarrow|leftrightarrow|mapsto|hookleftarrow|hookrightarrow|leftharpoonup|leftharpoondown|rightharpoonup|rightharpoondown)$/.test(kind)?(/^(left|hook)/.test(kind)?1:-1)*1.5/18*ss:0;
|
|
767
|
+
// These arrows, and amsmath's overset/underset/stackrel, are operators with TeX's ordinary limit gaps.
|
|
768
|
+
const stack=(b,above,below,dx=shift)=>{
|
|
769
|
+
const w=Math.max(b.w,above?.w || 0,below?.w || 0),items=[[b,(w-b.w)/2,0]];
|
|
770
|
+
if(above) {
|
|
771
|
+
const rise=n.accentGap?b.h+above.inkBottom+mathConstant('OverbarVerticalGap',c,0.1):b.h+Math.max(mathConstant('UpperLimitBaselineRiseMin',c,0.111),mathConstant('UpperLimitGapMin',c,0.2)+above.d);
|
|
772
|
+
items.push([above,(w-above.w)/2+dx,-rise]);
|
|
773
|
+
}
|
|
774
|
+
if(below) {
|
|
775
|
+
const drop=n.accentGap?b.d-below.inkTop+mathConstant('UnderbarVerticalGap',c,0.1):b.d+Math.max(mathConstant('LowerLimitBaselineDropMin',c,0.6),mathConstant('LowerLimitGapMin',c,0.167)+below.h);
|
|
776
|
+
items.push([below,(w-below.w)/2+dx,drop]);
|
|
777
|
+
}
|
|
778
|
+
return mathCompose(items,w,{class:n.unspaced?'ord':n.class || b.class});
|
|
779
|
+
};
|
|
780
|
+
if(paired) {
|
|
781
|
+
// Each half carries the opposite label as a phantom. Even an empty phantom retains its limit gap.
|
|
782
|
+
const right=kind==='rightleftharpoons',phantom=b=>({...b || mathBox(),svg:''}),dy=0.22*MATH_FONT.xHeight/MATH_FONT.units*s,
|
|
783
|
+
top=stack(mathStretch(right?'⇀':'↼',target,c,true,false,true),over,phantom(under),(right?-1:1)*1.5/18*ss),
|
|
784
|
+
bottom=stack(mathStretch(right?'↽':'⇁',target,c,true,false,true),phantom(over),under,(right?1:-1)*1.5/18*ss);
|
|
785
|
+
return mathCompose([[top,0,-dy],[bottom,top.w-bottom.w,dy]],top.w,{class:'rel'});
|
|
606
786
|
}
|
|
607
|
-
|
|
787
|
+
let b;
|
|
788
|
+
if(/^hook/.test(kind)) {
|
|
789
|
+
// The small Latin Modern hook owns five mu; joining it to the shaft removes three mu.
|
|
790
|
+
const right=kind==='hookrightarrow',arrow=mathStretch(right?'→':'←',target-2/18*s,c,true,false,true),hook=mathGlyphIndex(MATH_FONT.arrowHook,c),width=arrow.w+2/18*s;
|
|
791
|
+
if(right)b=mathCompose([[hook,0,0],[arrow,2/18*s,0]],width);
|
|
792
|
+
else {
|
|
793
|
+
const reflected=mathBox(5/18*s,hook.h,hook.d,'<g transform="translate('+mathNumber(5/18*s)+' 0) scale(-1 1)">'+hook.svg+'</g>');
|
|
794
|
+
b=mathCompose([[arrow,0,0],[reflected,arrow.w-3/18*s,0]],width);
|
|
795
|
+
}
|
|
796
|
+
} else b=n.diagram && n.base.value==='='?mathCompose([[mathRule(target,0.04*s,-0.28*s),0,0],[mathRule(target,0.04*s,-0.04*s),0,0]],target):mathLayout(n.base,{...c,stretchTarget:target});
|
|
797
|
+
return stack(b,over,under);
|
|
608
798
|
}
|
|
609
799
|
case 'phantom': {const b=mathLayout(n.body,c);return mathBox(n.mode==='v'?0:b.w,n.mode==='h'?0:b.h,n.mode==='h'?0:b.d);}
|
|
610
800
|
case 'smash': {const b=mathLayout(n.body,c);return {...b,h:n.mode==='b'?b.h:0,d:n.mode==='t'?b.d:0};}
|
|
@@ -612,7 +802,7 @@ function mathLayout(n,c) {
|
|
|
612
802
|
case 'raise': {const b=mathLayout(n.body,c),s=mathScale(c);return mathCompose([[b,0,n.center?(b.h-b.d)/2-mathConstant('AxisHeight',c,0.25):-n.amount*s]],b.w,{class:b.class,...(n.height===undefined?{}:{h:n.height*s}),...(n.depth===undefined?{}:{d:n.depth*s})});}
|
|
613
803
|
case 'rule': {const s=mathScale(c);return mathRule(n.width*s,(n.height+n.depth)*s,-n.height*s);}
|
|
614
804
|
case 'link': {const b=mathLayout(n.body,c);const url=new URL(n.href);if(!['http:','https:'].includes(url.protocol))throw Object.assign(new Error('Unsupported equation link'),{code:'unsafe-url'});b.svg='<a href="'+mathEscape(n.href)+'" aria-label="'+mathEscape(n.href)+'" tabindex="0" target="_blank" rel="noopener noreferrer">'+b.svg+'</a>';return b;}
|
|
615
|
-
default: throw Object.assign(new Error('Unsupported
|
|
805
|
+
default: throw Object.assign(new Error('Unsupported math construct: '+n.type),{code:'unsupported-construct'});
|
|
616
806
|
}
|
|
617
807
|
}
|
|
618
808
|
|