rapier-math 2.2.0 → 2.4.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 +1 -1
- package/dist/index.d.ts +8 -0
- package/dist/index.mjs +1 -1
- package/dist/rapier-math.js +567 -143
- package/docs/api.md +6 -2
- package/docs/font-source.md +17 -11
- package/docs/math-components.json +6 -6
- package/docs/math-resources.json +45 -39
- package/package.json +1 -1
- package/src/math/api.js +2 -2
- package/src/math/browser.js +28 -17
- package/src/math/build-font.py +153 -226
- package/src/math/classic.js +1 -1
- package/src/math/font.js +66 -33
- package/src/math/layout.js +69 -29
- package/src/math/mathml.js +19 -12
- package/src/math/package-layout.mjs +1 -0
- package/src/math/parser.js +347 -32
- package/src/math/responsive.js +10 -7
- package/src/math/source.js +8 -3
- package/src/math/symbols.js +19 -9
- package/src/math/variants.js +2 -2
- package/src/tools/build-math.mjs +3 -3
- package/tests/typeset.mjs +172 -0
package/src/math/layout.js
CHANGED
|
@@ -25,7 +25,7 @@ const mathConstant = (name, c, fallback) => (MATH_FONT.constants[name] ?? fallba
|
|
|
25
25
|
const mathScriptStyle = (c, cramped = c.cramped) => ({...c, level: Math.min(2, c.level + 1), display: false, cramped});
|
|
26
26
|
const mathScreenRelayout = (n,c,ratio) => mathLayout(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()});
|
|
27
27
|
const mathBox = (w = 0, h = 0, d = 0, svg = '', extra = {}) => ({w, h, d, svg, left: 0, right: w, inkTop: -h, inkBottom: d, class: 'ord', ...extra});
|
|
28
|
-
const mathMove = (b, x, y) => b.svg ? '<g transform="translate(' + mathNumber(x) + ' ' + mathNumber(y) + ')">' + b.svg + '</g>'
|
|
28
|
+
const mathMove = (b, x, y) => !b.svg || x === 0 && y === 0 ? b.svg : '<g transform="translate(' + mathNumber(x) + ' ' + mathNumber(y) + ')">' + b.svg + '</g>';
|
|
29
29
|
|
|
30
30
|
function mathCompose(items, width, extra = {}) {
|
|
31
31
|
let h = 0, d = 0, left = 0, right = width, inkTop=Infinity, inkBottom=-Infinity, svg = '';
|
|
@@ -65,8 +65,10 @@ function mathGlyphIndex(id, c, extra = {}) {
|
|
|
65
65
|
function mathGlyph(value, c, extra = {}) {
|
|
66
66
|
const cp = value.codePointAt(0);
|
|
67
67
|
if (value.length !== (cp > 0xffff ? 2 : 1)) return mathText(value, c, extra);
|
|
68
|
-
const
|
|
69
|
-
|
|
68
|
+
const variant = extra.variant || c.variant, mapped = mathStyledCodePoint(cp, variant);
|
|
69
|
+
// A styled dotless i or j is the styled letter's dotless form (Unicode has italic ones only).
|
|
70
|
+
const dotless = (cp === 0x1d6a4 || cp === 0x1d6a5) && !/^(normal|italic|roman)$/.test(variant) ? MATH_FONT.dotless[MATH_FONT.chars[mathStyledCodePoint(cp - 0x1d6a4 + 105, variant)]] : undefined;
|
|
71
|
+
const id = dotless ?? MATH_FONT.chars[mapped] ?? MATH_FONT.chars[cp];
|
|
70
72
|
if (id === undefined) {
|
|
71
73
|
const composed = mathFallbackGlyph(value, c, extra);
|
|
72
74
|
if (composed) return composed;
|
|
@@ -206,7 +208,9 @@ function mathStretch(value, target, c, horizontal = false) {
|
|
|
206
208
|
function mathDelimiter(value, target, c) {
|
|
207
209
|
if(!value || value==='.')return mathBox();
|
|
208
210
|
const b=mathStretch(value,target,c), axis=mathConstant('AxisHeight',c,0.25);
|
|
209
|
-
|
|
211
|
+
// TeXbook rule 19 centres a delimiter's box on the axis; a corner's box keeps it at its corner.
|
|
212
|
+
const centre=b.extended || b.glyph===undefined?(b.inkTop+b.inkBottom)/2:(b.d-b.h)/2;
|
|
213
|
+
return mathCompose([[b,0,-centre-axis]],b.w,{class:'inner',extended:true,italic:b.italic});
|
|
210
214
|
}
|
|
211
215
|
|
|
212
216
|
// The TeXbook's inter-atom spacing table (chapter 18). Rows: the left atom; columns: the right atom, in
|
|
@@ -245,7 +249,8 @@ function mathRow(children,c) {
|
|
|
245
249
|
const items=[];let x=0,previous=null;
|
|
246
250
|
for (const b of boxes) {
|
|
247
251
|
if (!b.space) {
|
|
248
|
-
|
|
252
|
+
// TeXbook Appendix G rule 17: a character's italic correction follows it, whatever comes next.
|
|
253
|
+
if(previous?.italic && previous.class!=='op')x+=previous.italic;
|
|
249
254
|
x+=mathSpace(previous?.class,b.class,c);
|
|
250
255
|
}
|
|
251
256
|
items.push([b,x,0]);x+=b.w;
|
|
@@ -253,7 +258,7 @@ function mathRow(children,c) {
|
|
|
253
258
|
}
|
|
254
259
|
const last=boxes.at(-1);
|
|
255
260
|
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,
|
|
256
|
-
...(boxes.length===1 ? {accent:last.accent,limits:last.limits,large:last.large,scriptBase:last.scriptBase} : {})});
|
|
261
|
+
...(boxes.length===1 ? {accent:last.accent,limits:last.limits,large:last.large,scriptBase:last.scriptBase,accentInk:last.accentInk} : {})});
|
|
257
262
|
}
|
|
258
263
|
|
|
259
264
|
function mathKern(b,corner,height) {
|
|
@@ -278,12 +283,13 @@ function mathContourBands(box, dy = 0) {
|
|
|
278
283
|
return bands;
|
|
279
284
|
}
|
|
280
285
|
|
|
286
|
+
const mathScriptGap = c => c.screen ? Math.max(.035 * mathScale(c), .9 / (c.screen.fontSize * c.screen.pixelRatio)) : .025 * mathScale(c);
|
|
281
287
|
function mathContourScript(base, script, dy, nominal, c) {
|
|
282
288
|
const a = mathContourBands(base);
|
|
283
289
|
if (!a) return nominal;
|
|
284
290
|
const b = mathContourBands(script, dy) || [{top: script.inkTop + dy, bottom: script.inkBottom + dy,
|
|
285
291
|
left: script.left, right: script.right}];
|
|
286
|
-
const gap =
|
|
292
|
+
const gap = mathScriptGap(c);
|
|
287
293
|
let j = 0, edge = -Infinity;
|
|
288
294
|
for (const left of a) {
|
|
289
295
|
while (j < b.length && b[j].bottom + gap < left.top) j++;
|
|
@@ -328,7 +334,10 @@ function mathScripts(n,c) {
|
|
|
328
334
|
const kern=Math.min(mathKern(base,0,rise-upDescent)+mathKern(up,3,-upDescent),mathKern(base,0,baseAscent)+mathKern(up,3,baseAscent-rise));
|
|
329
335
|
// A large operator's italic correction moves its subscript left, not its superscript right.
|
|
330
336
|
const nominal=b.w+(b.large?0:b.italic || 0)+kern;
|
|
331
|
-
|
|
337
|
+
let x=MATH_FONT.kern[base.glyph]?nominal:mathContourScript(base,up,-rise,nominal,c);
|
|
338
|
+
// A superscript beside an over-accent clears the accent's ink as well as the letter's.
|
|
339
|
+
const a=b.accentInk,gap=mathScriptGap(c);
|
|
340
|
+
if(a && up.inkTop-rise<a.bottom+gap && up.inkBottom-rise+gap>a.top)x=Math.max(x,a.right+gap-up.left);
|
|
332
341
|
items.push([up,x,-rise]);w=Math.max(w,x+up.w);
|
|
333
342
|
}
|
|
334
343
|
if (down) {
|
|
@@ -337,14 +346,20 @@ function mathScripts(n,c) {
|
|
|
337
346
|
const x=MATH_FONT.kern[base.glyph]?nominal:mathContourScript(base,down,drop,nominal,c);
|
|
338
347
|
items.push([down,x,drop]);w=Math.max(w,x+down.w);
|
|
339
348
|
}
|
|
340
|
-
|
|
349
|
+
// \prescript's scripts end together at its base.
|
|
350
|
+
if (n.pre) for (const item of items.slice(1)) item[1]=w-item[0].w;
|
|
351
|
+
// A subscript tucked under a slanted letter leaves the letter's top overhang for the next atom to clear.
|
|
352
|
+
const advance=w+mathConstant('SpaceAfterScript',c,0.05);
|
|
353
|
+
return mathCompose(items,advance,{class:b.class,italic:n.pre || b.large?0:Math.max(0,b.w+(b.italic || 0)-advance)});
|
|
341
354
|
}
|
|
342
355
|
|
|
343
356
|
function mathFraction(n,c,width) {
|
|
344
357
|
if (n.style) c={...c,level:({display:0,text:0,script:1,scriptscript:2})[n.style],display:n.style==='display',cramped:false};
|
|
345
358
|
const display=c.display && c.level===0, child=display?{...c,display:false}:mathScriptStyle(c);
|
|
346
|
-
|
|
347
|
-
|
|
359
|
+
let top=width===undefined?mathLayout(n.num,child):mathResponsiveLayout(n.num,child,Math.max(.05,width-.2*mathScale(c)));
|
|
360
|
+
// amsmath's \cfrac opens its numerator with LaTeX's \strut: 0.7 and 0.3 of a 1.2 em baseline skip.
|
|
361
|
+
if(n.strut)top={...top,h:Math.max(top.h,.84*mathScale(child)),d:Math.max(top.d,.36*mathScale(child))};
|
|
362
|
+
const bottom=mathLayout(n.den,{...child,cramped:true}),axis=mathConstant('AxisHeight',c,0.25);
|
|
348
363
|
const line=n.bar===false?0:n.barThickness===undefined?mathConstant('FractionRuleThickness',c,0.04):n.barThickness*mathScale(c);
|
|
349
364
|
let rise=mathConstant(line?(display?'FractionNumeratorDisplayStyleShiftUp':'FractionNumeratorShiftUp'):(display?'StackTopDisplayStyleShiftUp':'StackTopShiftUp'),c,display?0.68:0.4),
|
|
350
365
|
drop=mathConstant(line?(display?'FractionDenominatorDisplayStyleShiftDown':'FractionDenominatorShiftDown'):(display?'StackBottomDisplayStyleShiftDown':'StackBottomShiftDown'),c,display?0.68:0.35);
|
|
@@ -360,20 +375,24 @@ function mathFraction(n,c,width) {
|
|
|
360
375
|
const numeratorX=n.align==='l'?pad:n.align==='r'?w-pad-top.w:(w-top.w)/2;
|
|
361
376
|
const items=[[top,numeratorX,-rise],[bottom,(w-bottom.w)/2,drop]];
|
|
362
377
|
if (line) items.push([mathRule(w,line,-axis-line/2),0,0]);
|
|
363
|
-
|
|
378
|
+
// LaTeX's \frac, \binom and \genfrac brace their fraction: an ordinary atom, not TeX's bare inner.
|
|
379
|
+
const b=mathCompose(items,w,{class:'ord',innerLines:top.lines || 1,fitted:!!top.fitted});
|
|
364
380
|
if(width!==undefined && c.screen)b.refit=ratio=>mathFraction(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()},width);
|
|
365
381
|
// TeX's generalized fractions fence at least its delim1 (display) or delim2 size.
|
|
366
|
-
if (n.left || n.right) return mathFenceBoxes(n.left || '',n.right || '',b,c,undefined,display?2.39:1.01);
|
|
382
|
+
if (n.left || n.right) return {...mathFenceBoxes(n.left || '',n.right || '',b,c,undefined,display?2.39:1.01),class:'ord'};
|
|
367
383
|
return b;
|
|
368
384
|
}
|
|
369
385
|
|
|
370
386
|
function mathRoot(n,c) {
|
|
371
|
-
const body=mathLayout(n.body,{...c,cramped:true}),line=mathConstant('RadicalRuleThickness',c,0.04),
|
|
372
|
-
|
|
373
|
-
const sign=mathStretch('√',body.h+body.d+gap+line,c)
|
|
387
|
+
const body=mathLayout(n.body,{...c,cramped:true}),line=mathConstant('RadicalRuleThickness',c,0.04),extra=mathConstant('RadicalExtraAscender',c,0.05);
|
|
388
|
+
let gap=mathConstant(c.display && !c.level?'RadicalDisplayStyleVerticalGap':'RadicalVerticalGap',c,0.1);
|
|
389
|
+
const sign=mathStretch('√',body.h+body.d+gap+line,c);
|
|
390
|
+
// TeXbook Appendix G rule 11: a sign taller than needed splits its excess evenly above and below the radicand.
|
|
391
|
+
gap+=Math.max(0,sign.inkBottom-sign.inkTop-(body.h+body.d+gap+line))/2;
|
|
392
|
+
const rise=-sign.inkTop-body.h-gap-line,
|
|
374
393
|
index=n.index?mathLayout(n.index,{...c,level:2,display:false}):null;
|
|
375
394
|
let before=0,idxX=0;
|
|
376
|
-
if(index) {idxX=Math.max(0,mathConstant('RadicalKernBeforeDegree',c,0.2));before=
|
|
395
|
+
if(index) {idxX=Math.max(0,mathConstant('RadicalKernBeforeDegree',c,0.2));before=Math.max(0,idxX+index.w+mathConstant('RadicalKernAfterDegree',c,-0.3));}
|
|
377
396
|
const bodyX=before+sign.w,w=bodyX+body.w,items=[[sign,before,rise],[body,bodyX,0]];
|
|
378
397
|
items.push([mathRule(body.w,line,-body.h-gap-line),bodyX,0]);
|
|
379
398
|
if(index) {const ratio=(MATH_FONT.constants.RadicalDegreeBottomRaisePercent ?? 60)/100;items.push([index,idxX,sign.inkBottom+rise-(sign.inkBottom-sign.inkTop)*ratio-index.inkBottom]);}
|
|
@@ -390,7 +409,8 @@ function mathAccent(n,c) {
|
|
|
390
409
|
const position=n.position || 'over';let nucleus=n.base;
|
|
391
410
|
while(nucleus?.type==='style' || (nucleus?.type==='row' && nucleus.children.length===1))nucleus=nucleus.type==='style'?nucleus.body:nucleus.children[0];
|
|
392
411
|
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);
|
|
393
|
-
|
|
412
|
+
// A brace is an operator: centred on its base, with no italic correction to shift its labels.
|
|
413
|
+
const brace=n.limits==='always',semantics={class:n.class || b.class,limits:n.limits || b.limits,italic:brace?0:b.italic,accent:b.accent,scriptBase:b.scriptBase || b};
|
|
394
414
|
if(n.overlay) {
|
|
395
415
|
const w=Math.max(b.w,0.2*s),line=mathConstant('FractionRuleThickness',c,0.04);
|
|
396
416
|
const rising='M0 '+mathNumber(b.d)+'L'+mathNumber(w)+' '+mathNumber(-b.h),
|
|
@@ -409,21 +429,29 @@ function mathAccent(n,c) {
|
|
|
409
429
|
return result;
|
|
410
430
|
}
|
|
411
431
|
const names={hat:'̂',widehat:'̂',tilde:'̃',widetilde:'̃',bar:'̄',vec:'⃗',dot:'̇',ddot:'̈',dddot:'⃛',ddddot:'⃜',acute:'́',grave:'̀',breve:'̆',check:'̌',overbrace:'⏞',underbrace:'⏟',overrightarrow:'→',overleftarrow:'←',overleftrightarrow:'↔'};
|
|
432
|
+
// An under-accent (or \slashed's stroke) centres on its base, as in TeX and MathML Core: attachment points are for top accents.
|
|
412
433
|
const value=names[n.value] || n.value,accentStyle={...c,flattenAccent:position!=='under' && b.h>mathConstant('FlattenedAccentBaseHeight',c,0.65)},
|
|
413
434
|
a=n.stretch?mathStretch(value,Math.max(b.w,s*0.3),accentStyle,true):mathGlyph(value,accentStyle,{variant:'roman'}),
|
|
414
|
-
x=(b.accent ?? b.w/2)-(a.accent ?? a.w/2),combining=/^[\u0300-\u036f\u20d0-\u20ff]$/u.test(value);
|
|
435
|
+
x=position!=='over' || brace?(b.w-a.w)/2:(b.accent ?? b.w/2)-(a.accent ?? a.w/2),combining=/^[\u0300-\u036f\u20d0-\u20ff]$/u.test(value);
|
|
415
436
|
let y;
|
|
416
|
-
if(position==='
|
|
437
|
+
if(position==='through')y=0;
|
|
438
|
+
else if(position==='under')y=b.d+mathConstant('UnderbarVerticalGap',c,0.1)-a.inkTop;
|
|
417
439
|
else if(combining)y=-Math.max(0,b.h-mathConstant('AccentBaseHeight',c,0.48));
|
|
418
440
|
else y=-b.h-mathConstant('OverbarVerticalGap',c,0.1)-a.inkBottom;
|
|
441
|
+
// A combining under-accent's box is its ink: its advance box rests far below the mark.
|
|
442
|
+
if(position==='under')return mathCompose([[b,0,0],[{...a,h:-a.inkTop,d:a.inkBottom},x,y]],b.w,semantics);
|
|
443
|
+
if(position==='over') {
|
|
444
|
+
const g=a.glyph===undefined?null:MATH_FONT.glyph(a.glyph),left=g?(a.glyphX || 0)+g[1]*a.unitScale:a.left,right=g?(a.glyphX || 0)+g[3]*a.unitScale:a.right;
|
|
445
|
+
semantics.accentInk={left:x+left,right:x+right,top:y+a.inkTop,bottom:y+a.inkBottom};
|
|
446
|
+
}
|
|
419
447
|
return mathCompose([[b,0,0],[a,x,y]],b.w,semantics);
|
|
420
448
|
}
|
|
421
449
|
|
|
422
450
|
function mathTable(n,c) {
|
|
423
451
|
const small=/smallmatrix$/.test(n.env) || n.env==='subarray' || n.env==='substack',
|
|
424
452
|
paired=/^(align(?:ed)?(?:at)?|flalign|split)$/.test(n.env),
|
|
425
|
-
display=paired || /^(gather(?:ed)?|eqnarray|multline
|
|
426
|
-
cellStyle={...c,level:small?Math.max(1,c.level):c.level,display:small?false:display};
|
|
453
|
+
display=paired || /^([lr]?gather(?:ed)?|eqnarray|multline(?:d)?|equation|drcases|dcases|darray)$/.test(n.env),
|
|
454
|
+
cellStyle={...c,level:small?Math.max(1,c.level):c.level,display:small?false:display,cramped:false};
|
|
427
455
|
const rows=n.rows.map(row=>row.map((cell,i)=>{
|
|
428
456
|
// The second cell in each equation pair continues the first math list.
|
|
429
457
|
// An empty ordinary atom supplies the left neighbour of a leading relation.
|
|
@@ -441,7 +469,7 @@ function mathTable(n,c) {
|
|
|
441
469
|
insertions[insertion.before].push({...insertion,box:mathLayout(insertion.body,cellStyle)});
|
|
442
470
|
}
|
|
443
471
|
const gaps=Array.from({length:cols+1},(_,i)=>{
|
|
444
|
-
let gap=i===0 || i===cols?0:paired?(i%2?0:/^(alignat|alignedat)$/.test(n.env)?0:2*s):small?cs/3:s;
|
|
472
|
+
let gap=i===0 || i===cols?0:paired?(i%2?0:/^(alignat|alignedat)$/.test(n.env)?0:2*s):small?cs/3:n.env==='CD'?5/18*s:s;
|
|
445
473
|
if(insertions[i].some(item=>item.replaceGap))gap=0;
|
|
446
474
|
return gap+insertions[i].reduce((sum,item)=>sum+item.box.w,0);
|
|
447
475
|
});
|
|
@@ -464,7 +492,7 @@ function mathTable(n,c) {
|
|
|
464
492
|
const offset=n.position==='t'?-(baselines[0] || 0):n.position==='b'?-(baselines.at(-1) || 0):-total/2-mathConstant('AxisHeight',c,0.25),items=[];
|
|
465
493
|
for(let r=0;r<rows.length;r++) {
|
|
466
494
|
for(let i=0;i<cols;i++) {
|
|
467
|
-
const b=rows[r][i] || mathBox(),a
|
|
495
|
+
const b=rows[r][i] || mathBox(),a=/^multlined?$/.test(n.env) && cols===1?(r===0?'l':r===rows.length-1?'r':'c'):align[i] || 'c',
|
|
468
496
|
dx=a==='r'?widths[i]-b.w:a==='l'?0:(widths[i]-b.w)/2;
|
|
469
497
|
items.push([b,starts[i]+dx,baselines[r]+offset]);
|
|
470
498
|
}
|
|
@@ -497,11 +525,17 @@ function mathTable(n,c) {
|
|
|
497
525
|
|
|
498
526
|
function mathLayout(n,c) {
|
|
499
527
|
if(!n)return mathBox();
|
|
528
|
+
// With spans, each symbol carries its source offset for the host's tap-to-place.
|
|
529
|
+
if(c.spans && n.at!==undefined && (n.type==='glyph' || n.type==='text')) {
|
|
530
|
+
const b=mathLayout({...n,at:undefined},c);
|
|
531
|
+
return {...b,svg:'<g data-math-at="'+n.at+'">'+b.svg+'</g>'};
|
|
532
|
+
}
|
|
500
533
|
if(c.budget && ++c.budget.nodes>100000)throw Object.assign(new Error('Mathematical layout exceeds the rendering budget'),{code:'resource-limit'});
|
|
501
534
|
switch(n.type) {
|
|
502
535
|
case 'row': return mathRow(n.children,c);
|
|
503
536
|
case 'glyph': {
|
|
504
|
-
|
|
537
|
+
// Latin Modern's designed \big to \Bigg parentheses are 5 to 9 units short of 1.2, 1.8, 2.4 and 3 em.
|
|
538
|
+
if(n.delimiterSize || (n.delimiter && c.delimiterTarget))return {...mathDelimiter(n.value,n.delimiterSize?(n.delimiterSize-.01)*mathScale(c):c.delimiterTarget,c),class:n.class || 'ord'};
|
|
505
539
|
if(n.stretch)return {...mathStretch(n.value,c.stretchTarget || mathScale(c),c,true),class:n.class || 'rel',limits:n.limits,stretchAxis:'horizontal'};
|
|
506
540
|
if(n.value==='…' || n.value==='⋯') {
|
|
507
541
|
// TeX's \ldots and \cdots are three punctuation dots with punctuation spacing, wider than the font's ellipses.
|
|
@@ -526,7 +560,8 @@ function mathLayout(n,c) {
|
|
|
526
560
|
const cache=c.cache || (c.cache=new WeakMap()),key=[c.size,c.level,c.variant,c.display,c.cramped,c.stretchTarget].join('|');
|
|
527
561
|
let entries=cache.get(n);if(entries?.has(key))return {...entries.get(key)};
|
|
528
562
|
const local={...c,delimiterTarget:undefined};let b=mathLayout(n.body,local);
|
|
529
|
-
|
|
563
|
+
// Only a \middle needs the second pass, sized to the first pass's body.
|
|
564
|
+
if(n.body && mathHasMiddle(n.body)) {
|
|
530
565
|
const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(b.h-axis,b.d+axis),target=Math.max(mathScale(c),2*reach*0.901,2*reach-0.5*mathScale(c));
|
|
531
566
|
b=mathLayout(n.body,{...local,delimiterTarget:target});
|
|
532
567
|
}
|
|
@@ -539,6 +574,10 @@ function mathLayout(n,c) {
|
|
|
539
574
|
const style={...c};if(n.variant)style.variant=n.variant;if(n.absoluteSize!==undefined)style.size=n.absoluteSize;if(n.size!==undefined)style.size*=n.size;
|
|
540
575
|
if(n.mathStyle) {style.level=({display:0,text:0,script:1,scriptscript:2})[n.mathStyle];style.display=n.mathStyle==='display';style.cramped=false;}
|
|
541
576
|
const b=mathLayout(n.body,style);if(n.class)b.class=n.class;if(n.limits)b.limits=n.limits;
|
|
577
|
+
if(n.smashOperator) {
|
|
578
|
+
const op=mathLayout(n.body.type==='scripts'?n.body.base:n.body,style),extra=Math.max(0,(b.w-op.w)/2),left=n.smashOperator.includes('l')?extra:0;
|
|
579
|
+
Object.assign(b,mathCompose([[{...b},-left,0]],b.w-left-(n.smashOperator.includes('r')?extra:0),{class:b.class}));
|
|
580
|
+
}
|
|
542
581
|
if(n.width!==undefined) {
|
|
543
582
|
const width=n.width*mathScale(style),shift=n.align==='right'?width-b.w:n.align==='center'?(width-b.w)/2:0;
|
|
544
583
|
Object.assign(b,mathCompose([[{...b},shift,0]],width,{class:b.class}));
|
|
@@ -553,7 +592,7 @@ function mathLayout(n,c) {
|
|
|
553
592
|
}
|
|
554
593
|
case 'overunder': {
|
|
555
594
|
const over=n.over?mathLayout(n.over,mathScriptStyle(c)):null,under=n.under?mathLayout(n.under,mathScriptStyle(c,true)):null,
|
|
556
|
-
b=mathLayout(n.base,{...c,stretchTarget:Math.max(mathScale(c),Math.max(over?.w || 0,under?.w || 0)+0.4*mathScale(c))});
|
|
595
|
+
b=mathLayout(n.base,{...c,stretchTarget:Math.max((n.minWidth || 1)*mathScale(c),Math.max(over?.w || 0,under?.w || 0)+0.4*mathScale(c))});
|
|
557
596
|
const w=Math.max(b.w,over?.w || 0,under?.w || 0),items=[[b,(w-b.w)/2,0]],stretched=b.stretchAxis==='horizontal';
|
|
558
597
|
if(over) {
|
|
559
598
|
const rise=stretched?Math.max(mathConstant('StretchStackTopShiftUp',c,0.8),b.h+over.inkBottom+mathConstant('StretchStackGapAboveMin',c,0.1)):
|
|
@@ -569,7 +608,8 @@ function mathLayout(n,c) {
|
|
|
569
608
|
}
|
|
570
609
|
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);}
|
|
571
610
|
case 'smash': {const b=mathLayout(n.body,c);return {...b,h:n.mode==='b'?b.h:0,d:n.mode==='t'?b.d:0};}
|
|
572
|
-
|
|
611
|
+
// \vcenter centres its box on the maths axis.
|
|
612
|
+
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})});}
|
|
573
613
|
case 'rule': {const s=mathScale(c);return mathRule(n.width*s,(n.height+n.depth)*s,-n.height*s);}
|
|
574
614
|
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;}
|
|
575
615
|
default: throw Object.assign(new Error('Unsupported maths construct: '+n.type),{code:'unsupported-construct'});
|
|
@@ -579,5 +619,5 @@ function mathLayout(n,c) {
|
|
|
579
619
|
import {MATH_FONT} from './font.js';
|
|
580
620
|
import {mathStyledCodePoint} from './variants.js';
|
|
581
621
|
import {mathFallbackGlyph} from './fallbacks.js';
|
|
582
|
-
import {mathResponsiveLayout} from './responsive.js';
|
|
622
|
+
import {mathResponsiveLayout, mathHasMiddle} from './responsive.js';
|
|
583
623
|
export {mathNumber, mathScale, mathScreenStroke, mathConstant, mathBox, mathCompose, mathGlyphIndex, mathRule, mathStretch, mathEscape, mathScreenRelayout, mathSpace, mathRow, mathFraction, mathFenceBoxes, mathLayout, mathFontRatio, mathText};
|
package/src/math/mathml.js
CHANGED
|
@@ -59,7 +59,9 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
59
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
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
61
|
};
|
|
62
|
-
|
|
62
|
+
// An operator's form and movable limits belong to it alone, not to the expressions inside it.
|
|
63
|
+
const inner = context => ({...context, form: undefined, movableLimits: undefined});
|
|
64
|
+
const scriptContext = context => ({...inner(context), display: false, level: Math.min(2, context.level + 1)});
|
|
63
65
|
const styledContext = (context, node) => {
|
|
64
66
|
const next = {...context};
|
|
65
67
|
if (node.variant) next.variant = node.variant;
|
|
@@ -102,7 +104,7 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
102
104
|
if (kind === 'mi' && face !== 'normal' && face !== 'italic') attributes.mathvariant = 'normal';
|
|
103
105
|
token(kind, styled, attributes, context);
|
|
104
106
|
};
|
|
105
|
-
const kind = node => node.tokenKind || (/^\p{Decimal_Number}+$/u.test(node.value) ? 'mn' : /^[
|
|
107
|
+
const kind = node => node.tokenKind || (/^\p{Decimal_Number}+$/u.test(node.value) ? 'mn' : /^[∞∅ℵℶℷℸ℘℧⅁]$/.test(node.value) ? 'mi' :
|
|
106
108
|
['op', 'bin', 'rel', 'open', 'close', 'punct', 'inner'].includes(node.class) ||
|
|
107
109
|
/^[\p{Sm}\p{P}\p{Sc}\p{So}\p{Sk}\u2061-\u2064]$/u.test(node.value) ? 'mo' : 'mi');
|
|
108
110
|
const classOf = node => {
|
|
@@ -156,6 +158,8 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
156
158
|
}
|
|
157
159
|
|
|
158
160
|
function row(children, context, depth) {
|
|
161
|
+
// movablelimits belongs to an operator that is itself the base, not to operators inside a compound base.
|
|
162
|
+
if (children.length > 1) context = {...context, movableLimits: undefined};
|
|
159
163
|
open('mrow');
|
|
160
164
|
let previous;
|
|
161
165
|
for (let index = 0; index < children.length; index++) {
|
|
@@ -182,8 +186,11 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
182
186
|
previous = 'ord'; index = end - 1; continue;
|
|
183
187
|
}
|
|
184
188
|
let form;
|
|
185
|
-
if (node.type === 'glyph' && node.
|
|
186
|
-
|
|
189
|
+
if ((node.type === 'glyph' || node.type === 'style' && node.body.type === 'glyph') && classOf(node) === 'bin') {
|
|
190
|
+
// TeX's rule 5: a binary operator before a relation, a closing symbol or nothing is not infix.
|
|
191
|
+
const next = children.slice(index + 1).find(child => child.type !== 'space');
|
|
192
|
+
form = !previous || ['bin', 'op', 'rel', 'open', 'punct'].includes(previous) ? 'prefix' : !next || ['rel', 'close', 'punct'].includes(classOf(next)) ? 'postfix' : 'infix';
|
|
193
|
+
}
|
|
187
194
|
emit(node, {...context, form}, depth + 1);
|
|
188
195
|
if (node.type !== 'space') previous = classOf(node);
|
|
189
196
|
}
|
|
@@ -211,7 +218,7 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
211
218
|
before[insertion.before].push(insertion.body);
|
|
212
219
|
}
|
|
213
220
|
const small = /smallmatrix$/.test(node.env) || node.env === 'subarray' || node.env === 'substack';
|
|
214
|
-
const display = /^(align(?:ed)?(?:at)?|flalign|split|gather(?:ed)?|eqnarray|multline
|
|
221
|
+
const display = /^(align(?:ed)?(?:at)?|flalign|split|[lr]?gather(?:ed)?|eqnarray|multline(?:d)?|equation|drcases|dcases|darray)$/.test(node.env);
|
|
215
222
|
const cellContext = {...context, display: small ? false : display, level: small ? Math.max(1, context.level) : context.level};
|
|
216
223
|
const delimiters = {pmatrix: ['(', ')'], bmatrix: ['[', ']'], Bmatrix: ['{', '}'], vmatrix: ['|', '|'], Vmatrix: ['‖', '‖'],
|
|
217
224
|
psmallmatrix: ['(', ')'], bsmallmatrix: ['[', ']'], Bsmallmatrix: ['{', '}'], vsmallmatrix: ['|', '|'], Vsmallmatrix: ['‖', '‖'],
|
|
@@ -223,7 +230,7 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
223
230
|
for (let column = 0; column < columns; column++) {
|
|
224
231
|
if (++metrics.nodes > 100000) fail('resource-limit', 'MathML table cells exceed its work budget.');
|
|
225
232
|
let align = node.env === 'eqnarray' ? ['r', 'c', 'l'][column % 3] : node.align?.[column] || 'c';
|
|
226
|
-
if (node.env
|
|
233
|
+
if (/^multlined?$/.test(node.env) && columns === 1) align = at === 0 ? 'l' : at === rows.length - 1 ? 'r' : 'c';
|
|
227
234
|
open('mtd', {style: 'text-align:' + ({l: 'left', r: 'right', c: 'center'}[align] || 'center')});
|
|
228
235
|
open('mrow');
|
|
229
236
|
for (const body of before[column]) emit(body, cellContext, depth + 1);
|
|
@@ -270,20 +277,20 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
270
277
|
if (node.left || node.right) { open('mrow'); fence(node.left, 'prefix', local); }
|
|
271
278
|
open('mfrac', {linethickness: node.bar === false ? '0' : node.barThickness === undefined ? undefined : em(node.barThickness)});
|
|
272
279
|
const child = local.display && local.level === 0 ? {...local, display: false} : scriptContext(local);
|
|
273
|
-
emit(node.num, child, depth + 1); emit(node.den, child, depth + 1); close('mfrac');
|
|
280
|
+
emit(node.num, inner(child), depth + 1); emit(node.den, inner(child), depth + 1); close('mfrac');
|
|
274
281
|
if (node.left || node.right) { fence(node.right, 'postfix', local); close('mrow'); }
|
|
275
282
|
if (node.style) close('mstyle');
|
|
276
283
|
if (node.align) warn('semantic-fraction-alignment', 'The fraction relationship is preserved; continued-fraction numerator alignment is left to the MathML host.');
|
|
277
284
|
break;
|
|
278
285
|
}
|
|
279
286
|
case 'root':
|
|
280
|
-
open(node.index ? 'mroot' : 'msqrt'); emit(node.body, context, depth + 1);
|
|
281
|
-
if (node.index) emit(node.index, {...context, display: false, level: 2}, depth + 1);
|
|
287
|
+
open(node.index ? 'mroot' : 'msqrt'); emit(node.body, inner(context), depth + 1);
|
|
288
|
+
if (node.index) emit(node.index, {...inner(context), display: false, level: 2}, depth + 1);
|
|
282
289
|
close(node.index ? 'mroot' : 'msqrt'); break;
|
|
283
290
|
case 'fence':
|
|
284
|
-
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;
|
|
291
|
+
open('mrow'); fence(node.left, 'prefix', context, node.size); emit(node.body, inner(context), depth + 1); fence(node.right, 'postfix', context, node.size); close('mrow'); break;
|
|
285
292
|
case 'accent': {
|
|
286
|
-
if (node.overlay) {
|
|
293
|
+
if (node.overlay || node.position === 'through') {
|
|
287
294
|
warn('semantic-overlay', 'An overlay uses the MathML 3 menclose extension; hosts implementing only Core may omit the cancellation or negation mark.');
|
|
288
295
|
const notation = node.value === '╲' ? 'downdiagonalstrike' : node.value === '╳' ? 'updiagonalstrike downdiagonalstrike' : node.value === '↗' ? 'updiagonalarrow' : node.value === '─' ? 'horizontalstrike' : 'updiagonalstrike';
|
|
289
296
|
open('menclose', {notation}); emit(node.base, context, depth + 1); close('menclose'); break;
|
|
@@ -342,7 +349,7 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
342
349
|
open('mpadded', {height: node.mode === 'b' ? undefined : '0', depth: node.mode === 't' ? undefined : '0'});
|
|
343
350
|
emit(node.body, context, depth + 1); close('mpadded'); break;
|
|
344
351
|
case 'raise':
|
|
345
|
-
open('mpadded', {voffset: em(node.amount), height: node.height === undefined ? undefined : em(node.height), depth: node.depth === undefined ? undefined : em(node.depth)});
|
|
352
|
+
open('mpadded', {voffset: node.center ? undefined : em(node.amount), height: node.height === undefined ? undefined : em(node.height), depth: node.depth === undefined ? undefined : em(node.depth)});
|
|
346
353
|
emit(node.body, context, depth + 1); close('mpadded'); break;
|
|
347
354
|
case 'rule':
|
|
348
355
|
warn('semantic-rule-presentation', 'A rule is represented as a decorative mathematical space; no additional mathematical relationship is inferred.');
|
|
@@ -12,6 +12,7 @@ export function mathPackagePath(file) {
|
|
|
12
12
|
'math/package-check.mjs': 'tests/check.mjs',
|
|
13
13
|
'math/package-verify.mjs': 'tests/verify.mjs',
|
|
14
14
|
'math/adoption-verify.mjs': 'tests/adoption.mjs',
|
|
15
|
+
'math/typeset-verify.mjs': 'tests/typeset.mjs',
|
|
15
16
|
};
|
|
16
17
|
if (owners[file]) return owners[file];
|
|
17
18
|
if (file.startsWith('math/examples/')) return file.slice(5);
|