rapier-math 2.6.1 → 2.7.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/LICENSE +1 -1
- package/README.md +1 -1
- package/dist/index.mjs +1 -1
- package/dist/rapier-math.js +227 -122
- package/docs/font-source.md +27 -16
- package/docs/math-components.json +8 -8
- package/docs/math-resources.json +26 -26
- package/package.json +1 -1
- package/src/math/FONT-LICENSE.txt +1 -1
- package/src/math/build-font.py +36 -24
- package/src/math/classic.js +1 -1
- package/src/math/font.js +5 -5
- package/src/math/layout.js +68 -84
- package/src/math/mathml.js +53 -7
- package/src/math/parser.js +102 -25
- package/src/tools/build-math.mjs +3 -3
package/src/math/layout.js
CHANGED
|
@@ -47,7 +47,6 @@ function mathGlyphIndex(id, c, extra = {}) {
|
|
|
47
47
|
const pixels=c.screen?c.screen.fontSize*scale:Infinity,
|
|
48
48
|
optical=Math.max(c.level,pixels<10?2:pixels<15?1:0);
|
|
49
49
|
if(optical && alternates)id=alternates[Math.min(optical,alternates.length)-1];
|
|
50
|
-
if(c.flattenAccent)id=MATH_FONT.flatAccents[id] ?? id;
|
|
51
50
|
const g = MATH_FONT.glyph(id), s = scale / MATH_FONT.units, stroke = mathScreenStroke(c,scale), radius = stroke / 2;
|
|
52
51
|
if (!g) throw Object.assign(new Error('Unsupported mathematical glyph'), {code:'unsupported-glyph'});
|
|
53
52
|
if(c.budget) {
|
|
@@ -132,6 +131,8 @@ function mathTextWord(value, text) {
|
|
|
132
131
|
for (const ch of value) {
|
|
133
132
|
if (run && /\p{M}/u.test(ch)) { run += ch; continue; }
|
|
134
133
|
const b = mathGlyph(ch, text);
|
|
134
|
+
// LaTeX's visible verbatim space retains its TFM box around the same Mono outline.
|
|
135
|
+
if(text.verbatim && ch==='␣')Object.assign(b,{h:79/360*mathScale(text),d:1/9*mathScale(text)});
|
|
135
136
|
if (b.host) { run += ch; continue; }
|
|
136
137
|
flush(); items.push([b,x,0]); x += b.w;
|
|
137
138
|
}
|
|
@@ -147,10 +148,10 @@ const mathWordDirection = word => {
|
|
|
147
148
|
};
|
|
148
149
|
|
|
149
150
|
function mathText(value, c, extra = {}) {
|
|
150
|
-
//
|
|
151
|
-
const text = {...c, variant: extra.variant || 'roman'}, space = mathScale(c)/3, words = [];
|
|
151
|
+
// Ordinary text collapses ASCII spaces; TeX ties and verbatim spaces retain each advance.
|
|
152
|
+
const text = {...c, variant: extra.variant || 'roman',verbatim:!!extra.verbatim}, space = mathScale(c)*(text.variant==='monospace'?.525:1/3), words = [];
|
|
152
153
|
// Letters (with their marks and joiners), numbers and punctuation are separate pieces of a word.
|
|
153
|
-
for (const part of String(value).match(
|
|
154
|
+
for (const part of String(value).match(/[ \t\r\n]+|\s|[\p{L}\p{M}\p{Cf}]+|\p{Nd}+(?:[.,]\p{Nd}+)*|[^\s\p{L}\p{M}\p{Cf}\p{Nd}]+/gu) || [])
|
|
154
155
|
words.push(/^\s+$/u.test(part) ? {w: part === '\u2009' ? mathScale(c)/6 : space, dir: null} : {box: mathTextWord(part, text), dir: mathWordDirection(part)});
|
|
155
156
|
// The Unicode bidirectional algorithm in a left-to-right line: a number after right-to-left words joins them,
|
|
156
157
|
// as does a neutral between two of them; each right-to-left run reads from the right.
|
|
@@ -195,34 +196,11 @@ function mathStretch(value, target, c, horizontal = false, accent = false, exact
|
|
|
195
196
|
return mathCompose([[b,x,0]],width,{italic:b.italic,accent:b.accent+x});
|
|
196
197
|
};
|
|
197
198
|
const natural = shape(id);
|
|
198
|
-
|
|
199
|
+
const construction = (horizontal ? MATH_FONT.horizontal : MATH_FONT.vertical)[id];
|
|
199
200
|
const extent = b => horizontal ? b.w : b.inkBottom-b.inkTop;
|
|
200
201
|
if (extent(natural) >= target) return natural;
|
|
201
|
-
// Some donor arrowheads advertise a zero connector on the joining side.
|
|
202
|
-
// Keep their designed heads and extend the drawn shaft instead of joining outside those bounds.
|
|
203
|
-
if(horizontal && '→↔↦'.includes(value) && construction?.assembly?.parts.some((p,i,parts)=>i && Math.min(parts[i-1][2],p[1])<MATH_FONT.minConnectorOverlap))construction=null;
|
|
204
202
|
if (!construction) {
|
|
205
203
|
if(!horizontal || natural.w<=0)return natural;
|
|
206
|
-
// These font glyphs have straight central shafts but no MATH assembly.
|
|
207
|
-
// Preserve both end shapes and widen only a narrow central strip.
|
|
208
|
-
if('=⇌⇋↞↠→↔↦'.includes(value)) {
|
|
209
|
-
const g=MATH_FONT.glyph(natural.glyph),unit=natural.unitScale,added=target-natural.w,
|
|
210
|
-
split=g[0]*(value==='↞'?0.75:value==='↠'?0.25:0.5),half=g[0]*0.05,
|
|
211
|
-
left=split-half,right=split+half,delta=added/unit;
|
|
212
|
-
// The two-headed arrows have their plain shaft opposite both heads.
|
|
213
|
-
// All decoded font segments are absolute M/L/H/V/C/Z commands.
|
|
214
|
-
const shift=x=>x<=left?x:x>=right?x+delta:x+(x-left)*delta/(right-left);
|
|
215
|
-
let command='',coordinate=0;
|
|
216
|
-
const path=g[7].replace(/[MLHVCZ]|-?\d+(?:\.\d+)?/g,token=>{
|
|
217
|
-
if(/[MLHVCZ]/.test(token)){command=token;coordinate=0;return token;}
|
|
218
|
-
const isX=command!=='V' && (command==='H' || coordinate%2===0);coordinate++;
|
|
219
|
-
return isX?mathNumber(shift(Number(token))):token;
|
|
220
|
-
});
|
|
221
|
-
const svg='<path d="'+path+'" transform="scale('+mathNumber(unit)+' '+mathNumber(-unit)+')"'+
|
|
222
|
-
(c.screen?' data-math-ink="'+mathNumber(mathScale(c))+'"':'')+
|
|
223
|
-
(natural.stroke?' stroke="currentColor" stroke-width="'+mathNumber(natural.stroke/unit)+'" stroke-linejoin="round" paint-order="stroke fill"':'')+'/>';
|
|
224
|
-
return {...natural,w:target,right:natural.right+added,accent:target/2,svg,glyph:undefined};
|
|
225
|
-
}
|
|
226
204
|
const ratio=target/natural.w;
|
|
227
205
|
return {...natural,w:target,left:natural.left*ratio,right:natural.right*ratio,accent:(natural.accent ?? natural.w/2)*ratio,
|
|
228
206
|
svg:'<g transform="scale('+mathNumber(ratio)+' 1)">'+natural.svg+'</g>',glyph:undefined};
|
|
@@ -230,23 +208,14 @@ function mathStretch(value, target, c, horizontal = false, accent = false, exact
|
|
|
230
208
|
let last = natural;
|
|
231
209
|
// 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
210
|
for (const [glyph,advance] of exact && construction.assembly?.parts?.some(p=>p[4]) ? [] : construction.variants || []) {
|
|
233
|
-
const
|
|
234
|
-
//
|
|
235
|
-
if (accent &&
|
|
236
|
-
last =
|
|
237
|
-
if (
|
|
211
|
+
const next = shape(glyph,advance), size = horizontal ? next.w : advance * mathScale(c) / MATH_FONT.units;
|
|
212
|
+
// LuaTeX tests a horizontal variant's advance, not the variant record's ink span.
|
|
213
|
+
if (accent && size > target) return last;
|
|
214
|
+
last = next;
|
|
215
|
+
if (size >= target) return last;
|
|
238
216
|
}
|
|
239
217
|
const a = construction.assembly;
|
|
240
|
-
if (!a?.parts?.length || !a.parts.some(p=>p[4]))
|
|
241
|
-
// A wide accent may outgrow its final designed variant without an extender.
|
|
242
|
-
// Expand only its horizontal outline; retain the font's vertical stroke shape.
|
|
243
|
-
if (horizontal && last.w>0 && target>last.w) {
|
|
244
|
-
const ratio=target/last.w;
|
|
245
|
-
return {...last,w:target,left:last.left*ratio,right:last.right*ratio,accent:(last.accent ?? last.w/2)*ratio,
|
|
246
|
-
svg:'<g transform="scale('+mathNumber(ratio)+' 1)">'+last.svg+'</g>',glyph:undefined};
|
|
247
|
-
}
|
|
248
|
-
return last;
|
|
249
|
-
}
|
|
218
|
+
if (!a?.parts?.length || !a.parts.some(p=>p[4])) return last;
|
|
250
219
|
const unit = mathScale(c)/MATH_FONT.units, wanted = target/unit;
|
|
251
220
|
const minOverlap = MATH_FONT.minConnectorOverlap || 0;
|
|
252
221
|
const extenders=a.parts.filter(p=>p[4]),fixed=a.parts.filter(p=>!p[4]),
|
|
@@ -316,11 +285,20 @@ function mathCharacterNode(n) {
|
|
|
316
285
|
}
|
|
317
286
|
|
|
318
287
|
function mathRow(children,c) {
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
if(n.type==='
|
|
323
|
-
|
|
288
|
+
// A chosen math list is spliced into its surroundings. Its math-style nodes govern later atoms too.
|
|
289
|
+
const entries=[];let current=c;
|
|
290
|
+
const append=nodes=>{for(const n of nodes) {
|
|
291
|
+
if(n.type==='choice') {append(mathChoice(n,current).children);continue;}
|
|
292
|
+
const declaration=n.type==='style' && n.declaration && n.mathStyle;
|
|
293
|
+
if(declaration)current={...current,level:({display:0,text:0,script:1,scriptscript:2})[n.mathStyle],display:n.mathStyle==='display',cramped:false};
|
|
294
|
+
entries.push({n,context:current,declaration});
|
|
295
|
+
}};
|
|
296
|
+
append(children);children=entries.map(entry=>entry.n);
|
|
297
|
+
const boxes=entries.map(({n,context,declaration})=>{
|
|
298
|
+
const box=declaration?mathBox(0,0,0,'',{space:true}):mathLayout(n,context);
|
|
299
|
+
if(context.screen)box.refit=ratio=>mathScreenRelayout(n,context,ratio);
|
|
300
|
+
if(n.type==='frac' && n.bar!==false && n.barThickness!==0 && !n.left && !n.right)box.flowWrap=width=>mathFraction(n,context,width);
|
|
301
|
+
if(n.type==='fence' && !n.size)box.flowWrap=width=>mathResponsiveLayout(n,context,width);
|
|
324
302
|
return box;
|
|
325
303
|
});
|
|
326
304
|
const significant=boxes.map((b,i)=>b.space?null:i).filter(i=>i!==null);
|
|
@@ -335,7 +313,7 @@ function mathRow(children,c) {
|
|
|
335
313
|
if (!b.space) {
|
|
336
314
|
// Appendix G rule 17 as LuaTeX applies it: a character's italic correction is kept only before another character.
|
|
337
315
|
if(previous?.italic && previous.class!=='op' && adjacent && mathCharacterNode(children[i]))x+=previous.italic;
|
|
338
|
-
x+=mathSpace(previous?.class,b.class,
|
|
316
|
+
x+=mathSpace(previous?.class,b.class,entries[i].context);
|
|
339
317
|
}
|
|
340
318
|
items.push([b,x,0]);x+=b.w;
|
|
341
319
|
if (!b.space) previous=b;
|
|
@@ -346,14 +324,6 @@ function mathRow(children,c) {
|
|
|
346
324
|
...(boxes.length===1 ? {accent:last.accent,limits:last.limits,large:last.large,scriptBase:last.scriptBase,accentInk:last.accentInk} : {})});
|
|
347
325
|
}
|
|
348
326
|
|
|
349
|
-
function mathKern(b,corner,height) {
|
|
350
|
-
const record=MATH_FONT.kern?.[b.glyph]?.[corner];
|
|
351
|
-
if (!record || !b.unitScale) return 0;
|
|
352
|
-
const [heights,values]=record; let i=0;
|
|
353
|
-
while (i<heights.length && (height+(b.glyphY || 0))/b.unitScale>=heights[i]) i++;
|
|
354
|
-
return (values[i] || 0)*b.unitScale;
|
|
355
|
-
}
|
|
356
|
-
|
|
357
327
|
const mathScriptGap = c => c.screen ? Math.max(.035 * mathScale(c), .9 / (c.screen.fontSize * c.screen.pixelRatio)) : .025 * mathScale(c);
|
|
358
328
|
function mathScripts(n,c) {
|
|
359
329
|
const b=mathLayout(n.base,c), up=n.sup?mathLayout(n.sup,mathScriptStyle(c)):null,
|
|
@@ -371,8 +341,8 @@ function mathScripts(n,c) {
|
|
|
371
341
|
}
|
|
372
342
|
return mathCompose(items,w,{class:b.class});
|
|
373
343
|
}
|
|
374
|
-
const base=b.scriptBase || b,boxed=base.glyph===undefined || base.extended,baseAscent=
|
|
375
|
-
upDescent=up?.
|
|
344
|
+
const base=b.scriptBase || b,boxed=base.glyph===undefined || base.extended,baseAscent=base.h,baseDescent=base.d,
|
|
345
|
+
upDescent=up?.d || 0,downAscent=down?.h || 0;
|
|
376
346
|
let rise=up?Math.max(mathConstant(c.cramped?'SuperscriptShiftUpCramped':'SuperscriptShiftUp',c,0.36),
|
|
377
347
|
upDescent+mathConstant('SuperscriptBottomMin',c,0.1),boxed?baseAscent-mathConstant('SuperscriptBaselineDropMax',c,0.25):0):0;
|
|
378
348
|
let drop=down?Math.max(mathConstant('SubscriptShiftDown',c,0.2),
|
|
@@ -386,9 +356,8 @@ function mathScripts(n,c) {
|
|
|
386
356
|
}
|
|
387
357
|
const items=[[b,0,0]]; let w=b.w;
|
|
388
358
|
if (up) {
|
|
389
|
-
const kern=Math.min(mathKern(base,0,rise-upDescent)+mathKern(up,3,-upDescent),mathKern(base,0,baseAscent)+mathKern(up,3,baseAscent-rise));
|
|
390
359
|
// A large operator's italic correction moves its subscript left, not its superscript right.
|
|
391
|
-
const nominal=b.w+(b.large?0:b.italic || 0)
|
|
360
|
+
const nominal=b.w+(b.large?0:b.italic || 0);
|
|
392
361
|
let x=nominal;
|
|
393
362
|
// A superscript beside an over-accent clears the accent's ink as well as the letter's.
|
|
394
363
|
const a=b.accentInk,gap=mathScriptGap(c);
|
|
@@ -396,8 +365,7 @@ function mathScripts(n,c) {
|
|
|
396
365
|
items.push([up,x,-rise]);w=Math.max(w,x+up.w);
|
|
397
366
|
}
|
|
398
367
|
if (down) {
|
|
399
|
-
const
|
|
400
|
-
const nominal=b.w-(b.large?b.italic || 0:0)+kern;
|
|
368
|
+
const nominal=b.w-(b.large?b.italic || 0:0);
|
|
401
369
|
items.push([down,nominal,drop]);w=Math.max(w,nominal+down.w);
|
|
402
370
|
}
|
|
403
371
|
// \prescript's scripts end together at its base.
|
|
@@ -414,12 +382,13 @@ function mathFraction(n,c,width) {
|
|
|
414
382
|
// amsmath's \cfrac opens its numerator with LaTeX's \strut: 0.7 and 0.3 of a 1.2 em baseline skip.
|
|
415
383
|
if(n.strut)top={...top,h:Math.max(top.h,.84*mathScale(child)),d:Math.max(top.d,.36*mathScale(child))};
|
|
416
384
|
const bottom=mathLayout(n.den,{...child,cramped:true}),axis=mathConstant('AxisHeight',c,0.25);
|
|
417
|
-
const line=n.bar===false?0:n.barThickness===undefined?mathConstant('FractionRuleThickness',c,0.04):n.barThickness*
|
|
385
|
+
const line=n.bar===false?0:n.barThickness===undefined?mathConstant('FractionRuleThickness',c,0.04):n.barThickness*c.size;
|
|
418
386
|
let rise=mathConstant(line?(display?'FractionNumeratorDisplayStyleShiftUp':'FractionNumeratorShiftUp'):(display?'StackTopDisplayStyleShiftUp':'StackTopShiftUp'),c,display?0.68:0.4),
|
|
419
387
|
drop=mathConstant(line?(display?'FractionDenominatorDisplayStyleShiftDown':'FractionDenominatorShiftDown'):(display?'StackBottomDisplayStyleShiftDown':'StackBottomShiftDown'),c,display?0.68:0.35);
|
|
420
388
|
if (line) {
|
|
421
|
-
|
|
422
|
-
|
|
389
|
+
const gap=name=>n.barThickness===undefined?mathConstant(name,c,display?0.12:0.06):line*(display?3:1);
|
|
390
|
+
rise=Math.max(rise,top.d+axis+line/2+gap(display?'FractionNumDisplayStyleGapMin':'FractionNumeratorGapMin'));
|
|
391
|
+
drop=Math.max(drop,bottom.h-axis+line/2+gap(display?'FractionDenomDisplayStyleGapMin':'FractionDenominatorGapMin'));
|
|
423
392
|
} else {
|
|
424
393
|
const min=mathConstant(display?'StackDisplayStyleGapMin':'StackGapMin',c,display?0.4:0.15),gap=rise+drop-top.d-bottom.h;
|
|
425
394
|
if (gap<min) {rise+=(min-gap)/2;drop+=(min-gap)/2;}
|
|
@@ -433,8 +402,11 @@ function mathFraction(n,c,width) {
|
|
|
433
402
|
// LaTeX's \frac, \binom and \genfrac brace their fraction: an ordinary atom, not TeX's bare inner.
|
|
434
403
|
const b=mathCompose(items,w,{class:'ord',innerLines:top.lines || 1,fitted:!!top.fitted});
|
|
435
404
|
if(width!==undefined && c.screen)b.refit=ratio=>mathFraction(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()},width);
|
|
436
|
-
//
|
|
437
|
-
if (n.left || n.right)
|
|
405
|
+
// Generalized fractions use the fixed \Umathfractiondelsize, independent of the numerator and denominator.
|
|
406
|
+
if (n.left || n.right) {
|
|
407
|
+
const delimiters=n.textDelimiters?{...c,level:0}:c,target=(display?2.4:1.01)*mathScale(c)/mathScale(delimiters);
|
|
408
|
+
return {...mathFenceBoxes(n.left || '',n.right || '',b,delimiters,target),class:'ord'};
|
|
409
|
+
}
|
|
438
410
|
return b;
|
|
439
411
|
}
|
|
440
412
|
|
|
@@ -445,13 +417,15 @@ function mathRoot(n,c) {
|
|
|
445
417
|
// TeXbook Appendix G rule 11: a sign taller than needed splits its excess evenly above and below the radicand.
|
|
446
418
|
gap+=Math.max(0,sign.inkBottom-sign.inkTop-(body.h+body.d+gap+line))/2;
|
|
447
419
|
const rise=-sign.inkTop-body.h-gap-line,
|
|
448
|
-
index=n.index?mathLayout(n.index,{...c,level:2,display:false}):null;
|
|
420
|
+
index=n.index?mathLayout(n.index,{...c,level:2,display:false,cramped:false}):null;
|
|
449
421
|
let before=0,idxX=0;
|
|
450
422
|
if(index) {idxX=Math.max(0,mathConstant('RadicalKernBeforeDegree',c,0.2));before=Math.max(0,idxX+index.w+mathConstant('RadicalKernAfterDegree',c,-0.3));}
|
|
451
423
|
const bodyX=before+sign.w,w=bodyX+body.w,items=[[sign,before,rise],[body,bodyX,0]];
|
|
452
424
|
items.push([mathRule(body.w,line,-body.h-gap-line),bodyX,0]);
|
|
453
|
-
|
|
454
|
-
|
|
425
|
+
const b=mathCompose(items,w);b.h+=extra;
|
|
426
|
+
if(!index)return b;
|
|
427
|
+
const ratio=(MATH_FONT.constants.RadicalDegreeBottomRaisePercent ?? 60)/100;
|
|
428
|
+
return mathCompose([[b,0,0],[index,idxX,sign.inkBottom+rise-(sign.inkBottom-sign.inkTop)*ratio]],w);
|
|
455
429
|
}
|
|
456
430
|
|
|
457
431
|
function mathFenceBoxes(left,right,body,c,size,least=0,measure=body) {
|
|
@@ -524,12 +498,11 @@ function mathAccent(n,c) {
|
|
|
524
498
|
result[over?'h':'d']+=mathConstant(over?'OverbarExtraAscender':'UnderbarExtraDescender',c,0.04);
|
|
525
499
|
return result;
|
|
526
500
|
}
|
|
527
|
-
const names={hat:'̂',widehat:'̂',tilde:'̃',widetilde:'̃',bar:'̄',vec:'⃗',dot:'̇',ddot:'̈',dddot:'⃛',ddddot:'⃜',acute:'́',grave:'̀',breve:'̆',check:'̌',overbrace:'⏞',underbrace:'⏟',overrightarrow:'→',overleftarrow:'←',overleftrightarrow:'↔'};
|
|
528
501
|
// The font's accent attachment aligns both top and bottom accents; a through stroke stays centered.
|
|
529
502
|
// TeX's stretchy arrows and harpoons over or under a formula are the font's combining arrows, set as accents.
|
|
530
503
|
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]:
|
|
532
|
-
a=n.stretch?mathStretch(value,Math.max(b.w,s*0.3),
|
|
504
|
+
value=arrows?.[n.value] && MATH_FONT.chars[arrows[n.value].codePointAt(0)]!==undefined?arrows[n.value]:n.value,
|
|
505
|
+
a=n.stretch?mathStretch(value,Math.max(b.w,s*0.3),c,true,n.class!=='op'):mathGlyph(value,c,{variant:'roman'}),
|
|
533
506
|
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);
|
|
534
507
|
let y;
|
|
535
508
|
if(position==='through')y=0;
|
|
@@ -667,14 +640,12 @@ function mathTable(n,c) {
|
|
|
667
640
|
}
|
|
668
641
|
// An array is a \vcenter, an ordinary atom; a fenced one is an inner atom, as \left and \right make it.
|
|
669
642
|
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)});
|
|
670
|
-
const
|
|
671
|
-
psmallmatrix:['(',')'],bsmallmatrix:['[',']'],Bsmallmatrix:['{','}'],vsmallmatrix:['|','|'],Vsmallmatrix:['‖','‖'],
|
|
672
|
-
cases:['{',''],dcases:['{',''],rcases:['','}'],drcases:['','}']};
|
|
673
|
-
const pair=delimiters[n.env];
|
|
643
|
+
const pair=mathTableDelimiters(n.env);
|
|
674
644
|
return pair?mathFenceBoxes(pair[0],pair[1],b,c):b;
|
|
675
645
|
}
|
|
676
646
|
|
|
677
647
|
function mathLayout(n,c) {
|
|
648
|
+
c.displayMode ??= c.display;
|
|
678
649
|
if(!n)return mathBox();
|
|
679
650
|
// With spans, each symbol carries its source offset for the host's tap-to-place.
|
|
680
651
|
if(c.spans && n.at!==undefined && (n.type==='glyph' || n.type==='text')) {
|
|
@@ -686,7 +657,15 @@ function mathLayout(n,c) {
|
|
|
686
657
|
return mathLayout({type:'glyph',value:'□',variant:'roman',at:n.at},c);
|
|
687
658
|
if(c.budget && ++c.budget.nodes>100000)throw Object.assign(new Error('Mathematical layout exceeds the rendering budget'),{code:'resource-limit'});
|
|
688
659
|
switch(n.type) {
|
|
689
|
-
case 'row': {
|
|
660
|
+
case 'row': {
|
|
661
|
+
const b=mathRow(n.children,c);
|
|
662
|
+
if(n.group) {
|
|
663
|
+
Object.assign(b,{class:'ord',limits:undefined});
|
|
664
|
+
// TeX collapses a single character before resolving choices; every other group stays a boxed nucleus.
|
|
665
|
+
if(!mathCharacterNode(n))Object.assign(b,{glyph:undefined,scriptBase:undefined,italic:0});
|
|
666
|
+
}
|
|
667
|
+
return b;
|
|
668
|
+
}
|
|
690
669
|
case 'glyph': {
|
|
691
670
|
// TeX spaces a \middle as a closing atom, and a binary atom after it becomes ordinary.
|
|
692
671
|
const middle=n.delimiter && !n.delimiterSize?{class:'close',middle:true}:{};
|
|
@@ -700,14 +679,18 @@ function mathLayout(n,c) {
|
|
|
700
679
|
if(n.delimiter && c.delimiterTarget)return {...mathDelimiter(n.value,c.delimiterTarget,c),class:n.class || 'ord',...middle};
|
|
701
680
|
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
681
|
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});
|
|
703
|
-
if(n.large
|
|
704
|
-
|
|
682
|
+
if(n.large) {
|
|
683
|
+
let a=c.display && !c.level?mathStretch(n.value,mathConstant('DisplayOperatorMinHeight',c,1.3),c):b;
|
|
684
|
+
// LuaTeX's vertical glyph boxes use CFF control bounds; the ink keeps its exact extrema.
|
|
685
|
+
const bounds=MATH_FONT.verticalBounds[a.glyph];
|
|
686
|
+
if(bounds)a={...a,h:Math.max(0,bounds[1]*a.unitScale),d:Math.max(0,-bounds[0]*a.unitScale)};
|
|
705
687
|
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});
|
|
706
688
|
}
|
|
707
689
|
return b;
|
|
708
690
|
}
|
|
709
|
-
case 'text': return mathText(n.value,c,{variant:n.variant || (c.variant==='normal'?'roman':c.variant),class:n.class,limits:n.limits});
|
|
710
|
-
case '
|
|
691
|
+
case 'text': return mathText(n.value,c,{variant:n.variant || (c.variant==='normal'?'roman':c.variant),class:n.class,limits:n.limits,verbatim:n.verbatim});
|
|
692
|
+
case 'choice': return mathLayout(mathChoice(n,c),c);
|
|
693
|
+
case 'space': return mathBox((c.displayMode && n.displayWidth!==undefined?n.displayWidth:n.width)*mathScale(c),0,0,'',{space:true});
|
|
711
694
|
case 'scripts': return mathScripts(n,c);
|
|
712
695
|
case 'frac': return mathFraction(n,c);
|
|
713
696
|
case 'root': return mathRoot(n,c);
|
|
@@ -797,7 +780,7 @@ function mathLayout(n,c) {
|
|
|
797
780
|
return stack(b,over,under);
|
|
798
781
|
}
|
|
799
782
|
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);}
|
|
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};}
|
|
783
|
+
case 'smash': {const b=mathLayout(n.body,c);return {...b,h:n.mode==='b'?b.h:0,d:n.mode==='t'?b.d:0,glyph:undefined,scriptBase:undefined};}
|
|
801
784
|
// \vcenter centres its box on the maths axis.
|
|
802
785
|
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})});}
|
|
803
786
|
case 'rule': {const s=mathScale(c);return mathRule(n.width*s,(n.height+n.depth)*s,-n.height*s);}
|
|
@@ -807,6 +790,7 @@ function mathLayout(n,c) {
|
|
|
807
790
|
}
|
|
808
791
|
|
|
809
792
|
import {MATH_FONT} from './font.js';
|
|
793
|
+
import {mathChoice,mathTableDelimiters} from './parser.js';
|
|
810
794
|
import {mathStyledCodePoint} from './variants.js';
|
|
811
795
|
import {mathFallbackGlyph} from './fallbacks.js';
|
|
812
796
|
import {mathResponsiveLayout, mathHasMiddle} from './responsive.js';
|
package/src/math/mathml.js
CHANGED
|
@@ -150,6 +150,16 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
150
150
|
};
|
|
151
151
|
|
|
152
152
|
function scripts(node, context, depth, base) {
|
|
153
|
+
if (node.pre) {
|
|
154
|
+
open('mmultiscripts');
|
|
155
|
+
if (base) base(); else emit(node.base, {...context, form: undefined, movableLimits: false}, depth + 1);
|
|
156
|
+
open('mprescripts'); close('mprescripts');
|
|
157
|
+
for (const part of [node.sub, node.sup]) {
|
|
158
|
+
if (part) emit(part, scriptContext(context), depth + 1);
|
|
159
|
+
else { open('mrow'); close('mrow'); }
|
|
160
|
+
}
|
|
161
|
+
close('mmultiscripts'); return;
|
|
162
|
+
}
|
|
153
163
|
const limits = node.limits || limitsOf(node.base), stacked = limits === 'always' || limits === 'display' && context.display && context.level === 0;
|
|
154
164
|
const name = stacked ? node.sub && node.sup ? 'munderover' : node.sub ? 'munder' : 'mover' : node.sub && node.sup ? 'msubsup' : node.sub ? 'msub' : 'msup';
|
|
155
165
|
open(name, stacked ? {accent: node.sup ? 'false' : undefined, accentunder: node.sub ? 'false' : undefined} : {});
|
|
@@ -160,12 +170,42 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
160
170
|
}
|
|
161
171
|
|
|
162
172
|
function row(children, context, depth) {
|
|
173
|
+
if (children.some(node => node.type === 'choice')) {
|
|
174
|
+
const selected = [];
|
|
175
|
+
let selectionContext = context;
|
|
176
|
+
const append = (nodes, level) => {
|
|
177
|
+
for (const node of nodes) {
|
|
178
|
+
if (node.type === 'style' && node.mathStyle && node.declaration && node.body.type === 'row' && !node.body.children.length)
|
|
179
|
+
selectionContext = styledContext(selectionContext, node);
|
|
180
|
+
if (node.type !== 'choice') { selected.push(node); continue; }
|
|
181
|
+
visit(node, level); family(node);
|
|
182
|
+
if (active.has(node)) fail('unsupported-semantic-node', 'A mathematical tree contains a cycle.');
|
|
183
|
+
active.add(node);
|
|
184
|
+
const branch = mathChoice(node, selectionContext);
|
|
185
|
+
visit(branch, level + 1);
|
|
186
|
+
append(branch.children, level + 2);
|
|
187
|
+
active.delete(node);
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
append(children, depth + 1); children = selected;
|
|
191
|
+
if (children.length !== 1) context = {...context, ordinary: undefined};
|
|
192
|
+
}
|
|
163
193
|
// movablelimits belongs to an operator that is itself the base, not to operators inside a compound base.
|
|
164
194
|
if (children.length > 1) context = {...context, movableLimits: undefined};
|
|
165
195
|
open('mrow');
|
|
166
|
-
let previous;
|
|
196
|
+
let previous, styled = false;
|
|
167
197
|
for (let index = 0; index < children.length; index++) {
|
|
168
198
|
const node = children[index];
|
|
199
|
+
if (node.type === 'style' && node.mathStyle && node.declaration && node.body.type === 'row' && !node.body.children.length) {
|
|
200
|
+
visit(node, depth + 1); visit(node.body, depth + 2); context = styledContext(context, node);
|
|
201
|
+
if (styled) close('mstyle');
|
|
202
|
+
open('mstyle', {displaystyle: String(context.display), scriptlevel: String(context.level)}); styled = true; continue;
|
|
203
|
+
}
|
|
204
|
+
// The parser's prescript uses a phantom nucleus followed by the real nucleus for SVG placement.
|
|
205
|
+
if (node.type === 'scripts' && node.pre && node.base?.type === 'phantom' && node.base.body === children[index + 1]) {
|
|
206
|
+
emit({...node, base: children[++index]}, context, depth + 1);
|
|
207
|
+
previous = classOf(node.base.body); continue;
|
|
208
|
+
}
|
|
169
209
|
if (numberPart(node)) {
|
|
170
210
|
let end = index + 1;
|
|
171
211
|
while (end < children.length && numberPart(children[end]) && sameNumberStyle(node, children[end])) end++;
|
|
@@ -190,12 +230,13 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
190
230
|
let form;
|
|
191
231
|
if ((node.type === 'glyph' || node.type === 'style' && node.body.type === 'glyph') && classOf(node) === 'bin') {
|
|
192
232
|
// TeX's rule 5: a binary operator before a relation, a closing symbol or nothing is not infix.
|
|
193
|
-
const next = children.slice(index + 1).find(child => child.type !== 'space');
|
|
233
|
+
const next = children.slice(index + 1).find(child => child.type !== 'space' && !(child.type === 'style' && child.mathStyle && child.declaration && child.body.type === 'row' && !child.body.children.length));
|
|
194
234
|
form = !previous || ['bin', 'op', 'rel', 'open', 'punct'].includes(previous) ? 'prefix' : !next || ['rel', 'close', 'punct'].includes(classOf(next)) ? 'postfix' : 'infix';
|
|
195
235
|
}
|
|
196
236
|
emit(node, {...context, form}, depth + 1);
|
|
197
237
|
if (node.type !== 'space') previous = classOf(node);
|
|
198
238
|
}
|
|
239
|
+
if (styled) close('mstyle');
|
|
199
240
|
close('mrow');
|
|
200
241
|
}
|
|
201
242
|
|
|
@@ -222,9 +263,7 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
222
263
|
const small = /smallmatrix$/.test(node.env) || node.env === 'subarray' || node.env === 'substack';
|
|
223
264
|
const display = /^(align(?:ed)?(?:at)?|flalign|split|[lr]?gather(?:ed)?|eqnarray|multline(?:d)?|equation|drcases|dcases|darray)$/.test(node.env);
|
|
224
265
|
const cellContext = {...context, display: small ? false : display, level: small ? Math.max(1, context.level) : context.level};
|
|
225
|
-
const delimiters =
|
|
226
|
-
psmallmatrix: ['(', ')'], bsmallmatrix: ['[', ']'], Bsmallmatrix: ['{', '}'], vsmallmatrix: ['|', '|'], Vsmallmatrix: ['‖', '‖'],
|
|
227
|
-
cases: ['{', ''], dcases: ['{', ''], rcases: ['', '}'], drcases: ['', '}']}[node.env];
|
|
266
|
+
const delimiters = mathTableDelimiters(node.env);
|
|
228
267
|
if (delimiters) { open('mrow'); fence(delimiters[0], 'prefix', context); }
|
|
229
268
|
open('mtable', {displaystyle: String(cellContext.display), scriptlevel: String(cellContext.level), 'data-math-environment': node.env});
|
|
230
269
|
for (let at = 0; at < rows.length; at++) {
|
|
@@ -262,10 +301,11 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
262
301
|
switch (node.type) {
|
|
263
302
|
// A braced group is an ordinary atom in TeX; an operator alone in it takes no spacing of its own.
|
|
264
303
|
case 'row': row(node.children, node.group && node.children.length === 1 ? {...context, ordinary: true} : {...context, ordinary: undefined}, depth); break;
|
|
304
|
+
case 'choice': emit(mathChoice(node, context), context, depth + 1); break;
|
|
265
305
|
case 'glyph': {
|
|
266
306
|
const name = kind(node), attributes = {};
|
|
267
307
|
if (name === 'mo') {
|
|
268
|
-
if (node.class === 'open' || node.class === 'close') { attributes.fence =
|
|
308
|
+
if (node.class === 'open' || node.class === 'close') { attributes.fence = String(!/^[!?]$/.test(node.value)); attributes.form = node.class === 'open' ? 'prefix' : 'postfix'; }
|
|
269
309
|
else if (node.class === 'punct') attributes.separator = 'true';
|
|
270
310
|
else if (context.form) attributes.form = context.form;
|
|
271
311
|
if (node.large !== undefined) attributes.largeop = String(!!node.large);
|
|
@@ -281,7 +321,10 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
281
321
|
}
|
|
282
322
|
case 'text': atom(node, node.value, ['op', 'bin', 'rel'].includes(node.class) ? 'mo' : 'mtext', context,
|
|
283
323
|
node.class === 'op' ? {form: 'prefix', movablelimits: String(node.limits === 'display')} : {}); break;
|
|
284
|
-
case 'space':
|
|
324
|
+
case 'space': {
|
|
325
|
+
const width = options.displayMode && node.displayWidth !== undefined ? node.displayWidth : node.width;
|
|
326
|
+
open('mspace', {width: em(Math.max(0, width)), style: width < 0 ? 'margin-left:' + em(width) : undefined}); close('mspace'); break;
|
|
327
|
+
}
|
|
285
328
|
case 'scripts': scripts(node, context, depth); break;
|
|
286
329
|
case 'frac': {
|
|
287
330
|
const local = node.style ? styledContext(context, {mathStyle: node.style}) : context;
|
|
@@ -350,6 +393,8 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
350
393
|
} else if (node.class) {
|
|
351
394
|
const leaf = singleToken(node.body);
|
|
352
395
|
if (leaf) emit({...leaf, class: node.class}, local, depth + 1);
|
|
396
|
+
else if (node.body.type === 'row' && node.body.children.filter(child => child.type !== 'space').length === 1 &&
|
|
397
|
+
node.body.children.every(child => child.type === 'space' || classOf(child) === node.class)) emit(node.body, local, depth + 1);
|
|
353
398
|
else {
|
|
354
399
|
warn('semantic-atom-class', 'A compound expression retains its mathematical children; its TeX atom class does not create a single MathML operator.');
|
|
355
400
|
emit(node.body, local, depth + 1);
|
|
@@ -431,4 +476,5 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
431
476
|
|
|
432
477
|
import {mathDiagnostic} from './source.js';
|
|
433
478
|
import {mathStyledCodePoint} from './variants.js';
|
|
479
|
+
import {mathChoice, mathTableDelimiters} from './parser.js';
|
|
434
480
|
export {mathML};
|