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.
@@ -68,7 +68,8 @@ function mathFlowAtoms(n,box,x=0,y=0) {
68
68
  return n.children.flatMap((child,i)=>{const [b,dx,dy]=box.rowItems[i];return mathFlowAtoms(child,b,x+dx,y+dy);});
69
69
  if(n.type==='style' && n.width===undefined && !n.border && !n.background && !n.class && !n.limits) {
70
70
  const atoms=mathFlowAtoms(n.body,box,x,y);
71
- if(n.color) {
71
+ // A box the body did not unpack already carries this colour from mathLayout.
72
+ if(n.color && !(atoms.length===1 && atoms[0][0]===box)) {
72
73
  const paint=b=>({...b,svg:'<g fill="'+mathEscape(n.color)+'" color="'+mathEscape(n.color)+'" fill-opacity="1" stroke-opacity="1">'+b.svg+'</g>',
73
74
  ...(b.refit?{refit:ratio=>paint(b.refit(ratio))}:{}),...(b.flowWrap?{flowWrap:width=>paint(b.flowWrap(width))}:{})});
74
75
  return atoms.map(([b,dx,dy])=>[paint(b),dx,dy]);
@@ -77,8 +78,9 @@ function mathFlowAtoms(n,box,x=0,y=0) {
77
78
  }
78
79
  if(n.type==='frac' && n.bar!==false && n.barThickness!==0)box={...box,flowFactor:true};
79
80
  if(n.type==='glyph' && n.value==='⋯')box={...box,flowDots:true};
81
+ // An explicit \bigl or \bigr class wins; an ordinary \big( still pairs by its glyph.
80
82
  if(n.type==='glyph' && '([{⌈⌊⟨⦅⟦⟪⦃)]}⌉⌋⟩⦆⟧⟫⦄'.includes(n.value))
81
- box={...box,flowFence:')]}⌉⌋⟩⦆⟧⟫⦄'.includes(n.value)?'close':'open'};
83
+ box={...box,flowFence:n.class==='open' || n.class==='close'?n.class:')]}⌉⌋⟩⦆⟧⟫⦄'.includes(n.value)?'close':'open'};
82
84
  return [[box,x,y]];
83
85
  }
84
86
 
@@ -93,15 +95,15 @@ function mathRefitRow(items,advance,ratio) {
93
95
 
94
96
  function mathWrapRow(box,c,width,{relationIndent,binaryIndent}={}) {
95
97
  if(mathInkWidth(box)<=width || !box.rowItems?.length)return mathFitBox(box,width,c);
96
- const atoms=box.rowItems.map(item=>[...item]),breaks=[0];let ink=false,depth=0,previous=null;
98
+ const atoms=box.rowItems.map(item=>[...item]),found=[];let ink=false,depth=0,previous=null;
97
99
  for(let i=0;i<atoms.length;i++) {
98
100
  const b=atoms[i][0],next=atoms[i+1]?.[0],fence=b.flowFence || b.class;
99
101
  if(fence==='close')depth=Math.max(0,depth-1);
100
- if(ink && !depth && (b.class==='rel' || b.class==='bin' || b.flowDots && (previous?.flowFactor && next?.flowFactor || (previous?.flowFence || previous?.class)==='close' && (next?.flowFence || next?.class)==='open')))breaks.push(i);
102
+ if(ink && (b.class==='rel' || b.class==='bin' || b.flowDots && (previous?.flowFactor && next?.flowFactor || (previous?.flowFence || previous?.class)==='close' && (next?.flowFence || next?.class)==='open')))found.push([i,depth]);
101
103
  if(fence==='open')depth++;
102
104
  if(b.svg){ink=true;previous=b;}
103
105
  }
104
- breaks.push(atoms.length);
106
+ const breaks=[0,...found.map(([i])=>i),atoms.length],levels=[0,...found.map(([,level])=>level),0];
105
107
  // Reuse structural wrapping before shrinking an oversized, otherwise indivisible atom.
106
108
  const deltas=Array(atoms.length).fill(0);let changed=false;
107
109
  for(let segment=0;segment<breaks.length-1;segment++) {
@@ -150,7 +152,8 @@ function mathWrapRow(box,c,width,{relationIndent,binaryIndent}={}) {
150
152
  left=Math.min(left,x-origin+b.left);right=Math.max(right,x-origin+b.right,x-origin+b.w);
151
153
  }
152
154
  const extent=right-left,over=Math.max(0,extent-available)/available,slack=Math.max(0,available-extent)/available;
153
- const last=end===breaks.length-1,penalty=last?0:atoms[breaks[end]][0].class==='rel'?0:18;
155
+ // A break inside brackets costs more than any fitting line, yet less than overflowing one.
156
+ const last=end===breaks.length-1,penalty=last?0:(atoms[breaks[end]][0].class==='rel'?0:18)+200*levels[end];
154
157
  const cost=costs[end]+12+penalty+(last?8:60)*slack*slack+(over?100000*(1+over*over):0);
155
158
  if(cost<costs[start]) {costs[start]=cost;next[start]=end;}
156
159
  if(extent>available && end>start+1)break;
@@ -252,4 +255,4 @@ function mathResponsiveLayout(n,c,width,natural=mathLayout(n,c)) {
252
255
 
253
256
  import {MATH_FONT} from './font.js';
254
257
  import {mathNumber, mathEscape, mathScale, mathScreenStroke, mathConstant, mathScreenRelayout, mathCompose, mathSpace, mathRow, mathFraction, mathFenceBoxes, mathLayout} from './layout.js';
255
- export {mathResponsiveLayout, mathInkWidth};
258
+ export {mathResponsiveLayout, mathInkWidth, mathHasMiddle};
@@ -48,6 +48,8 @@ function mathDiagnostic(cause) {
48
48
  offset:Number.isFinite(cause?.offset)?cause.offset:0};
49
49
  if(message.length>1024 || cause?.messageTruncated)error.messageTruncated=true;
50
50
  if(cause?.sourceOmitted)error.sourceOmitted=true;
51
+ const suggestion=cause?.suggestion ?? (cause?.code==='unsupported-command'?mathSuggest(cause.command):cause?.code==='unsupported-environment'?mathSuggest(cause.environment,true):undefined);
52
+ if(suggestion)error.suggestion=suggestion;
51
53
  if(rawCommand!==undefined) {
52
54
  const command=String(rawCommand);
53
55
  error.command=command.slice(0,128).replace(/[\ud800-\udbff]$/,'');
@@ -56,12 +58,15 @@ function mathDiagnostic(cause) {
56
58
  return error;
57
59
  }
58
60
 
59
- function mathPrepare(source) {
61
+ function mathPrepare(source, options) {
60
62
  const text = String(source ?? ''), safe = mathAdmitSource(text);
61
63
  let tree, error = safe.error;
62
- if (!error) try { tree = parseMathTex(text); } catch (cause) { error = mathDiagnostic(cause); }
64
+ if (!error) try { tree = parseMathTex(text); } catch (cause) {
65
+ tree = options?.preview ? parseMathTexPreview(text, cause, options.caret ?? text.length) : null;
66
+ if (!tree) { tree = undefined; error = mathDiagnostic(cause); }
67
+ }
63
68
  return {text, safe, tree, error};
64
69
  }
65
70
 
66
- import {parseMathTex} from './parser.js';
71
+ import {parseMathTex, parseMathTexPreview, mathSuggest} from './parser.js';
67
72
  export {mathDiagnostic, mathPrepare, mathSourceUTF16};
@@ -27,16 +27,23 @@ surd=√ diagup=╱ diagdown=╲ Bbbk=𝕜
27
27
  // Lowercase Greek retains the ordinary mathematical italic convention.
28
28
  for (const name of 'alpha beta gamma delta epsilon varepsilon zeta eta theta vartheta iota kappa varkappa lambda mu nu xi omicron pi varpi rho varrho sigma varsigma tau upsilon phi varphi chi psi omega digamma'.split(' '))
29
29
  MATH_SYMBOLS[name] = Object.freeze({...MATH_SYMBOLS[name], variant: 'normal'});
30
+ // upgreek: \upalpha to \upomega and \Upgamma to \Upomega are upright.
31
+ for (const name of Object.keys(MATH_SYMBOLS).filter(name => /^[a-z]+$/.test(name) && MATH_SYMBOLS[name].variant === 'normal')) {
32
+ MATH_SYMBOLS['up' + name] = Object.freeze({...MATH_SYMBOLS[name], variant: 'roman'});
33
+ const capital = name[0].toUpperCase() + name.slice(1);
34
+ if (MATH_SYMBOLS[capital]) MATH_SYMBOLS['Up' + name] = MATH_SYMBOLS[capital];
35
+ }
30
36
  for (const name of Object.keys(MATH_SYMBOLS).filter(name => /^var[A-Z]/.test(name)))
31
37
  MATH_SYMBOLS[name] = Object.freeze({...MATH_SYMBOLS[name], variant: 'italic'});
32
38
  mathSymbolGroup('bin', `
33
- pm=± mp=∓ times=× div=÷ cdot=⋅ cdotp=⋅ ast=∗ star=⋆ circ=∘ bullet=∙ diamond=⋄
39
+ dotminus=∸ cupdot=⊍ barvee=⊽
40
+ pm=± mp=∓ times=× div=÷ cdot=⋅ ast=∗ star=⋆ circ=∘ bullet=∙ diamond=⋄
34
41
  cap=∩ cup=∪ uplus=⊎ sqcap=⊓ sqcup=⊔ vee/lor=∨ wedge/land=∧ setminus=∖ smallsetminus=∖
35
42
  oplus=⊕ ominus=⊖ otimes=⊗ oslash=⊘ odot=⊙ bigcirc=◯ dag/dagger=† ddag/ddagger=‡ amalg=⨿
36
43
  triangleleft=◁ triangleright=▷ lhd=⊲ rhd=⊳ unlhd=⊴ unrhd=⊵ wr=≀
37
44
  barwedge=⊼ veebar=⊻ doublebarwedge=⩞ curlywedge=⋏ curlyvee=⋎ boxplus=⊞ boxminus=⊟ boxtimes=⊠ boxdot=⊡
38
45
  ltimes=⋉ rtimes=⋊ leftthreetimes=⋋ rightthreetimes=⋌ dotplus=∔ divideontimes=⋇
39
- circledast=⊛ circledcirc=⊚ circleddash=⊝ intercal=⊺ centerdot=· land=∧ lor=∨ bigtriangleup=△ bigtriangledown=▽
46
+ circledast=⊛ circledcirc=⊚ circleddash=⊝ intercal=⊺ centerdot=· bigtriangleup=△ bigtriangledown=▽ Cup=⋓ Cap=⋒
40
47
  `, {variant: 'roman'});
41
48
  mathSymbolGroup('rel', `
42
49
  le/leq=≤ ge/geq=≥ neq/ne=≠ equiv=≡ sim=∼ simeq=≃ approx=≈ cong=≅ asymp=≍ propto=∝
@@ -58,9 +65,10 @@ nprec=⊀ nsucc=⊁ npreceq=⋠ nsucceq=⋡ precneqq=⪵ succneqq=⪶ precnsim=
58
65
  nsubset=⊄ nsupset=⊅ nsubseteq=⊈ nsupseteq=⊉ nsubseteqq=⊈ nsupseteqq=⊉ subsetneq=⊊ supsetneq=⊋
59
66
  varsubsetneq=⊊ varsupsetneq=⊋ subsetneqq=⫋ supsetneqq=⫌ varsubsetneqq=⫋ varsupsetneqq=⫌
60
67
  nmid=∤ nparallel=∦ nshortmid=∤ nshortparallel=∦ nvdash=⊬ nVdash=⊮ nvDash=⊭ nVDash=⊯
61
- ntriangleleft=⋪ ntriangleright=⋫ ntrianglelefteq=⋬ ntrianglerighteq=⋭ coloneqq/coloneq=≔ eqqcolon=≕
68
+ ntriangleleft=⋪ ntriangleright=⋫ ntrianglelefteq=⋬ ntrianglerighteq=⋭ coloneqq=≔ eqqcolon=≕ vcentcolon=∶ dblcolon/Colon=∷ And=&
62
69
  `, {variant: 'roman'});
63
70
  mathSymbolGroup('rel', `
71
+ questeq=≟ veeeq=≚ stareq=≛ eqdef=≝ estimates/corresponds=≙ Equiv=≣
64
72
  leftarrow/gets=← rightarrow/to=→ leftrightarrow=↔ Leftarrow=⇐ Rightarrow=⇒ Leftrightarrow=⇔
65
73
  longleftarrow=⟵ longrightarrow=⟶ longleftrightarrow=⟷ Longleftarrow=⟸ Longrightarrow=⟹ Longleftrightarrow=⟺
66
74
  mapsto=↦ longmapsto=⟼ hookleftarrow=↩ hookrightarrow=↪ nearrow=↗ searrow=↘ nwarrow=↖ swarrow=↙
@@ -72,29 +80,31 @@ Lleftarrow=⇚ Rrightarrow=⇛ twoheadleftarrow=↞ twoheadrightarrow=↠ leftar
72
80
  looparrowleft=↫ looparrowright=↬ leftrightsquigarrow=↭ rightsquigarrow/leadsto=⇝ curvearrowleft=↶ curvearrowright=↷
73
81
  circlearrowleft=↺ circlearrowright=↻ dashleftarrow=⇠ dashrightarrow=⇢ multimap=⊸
74
82
  nleftarrow=↚ nrightarrow=↛ nleftrightarrow=↮ nLeftarrow=⇍ nRightarrow=⇏ nLeftrightarrow=⇎
83
+ Lsh=↰ Rsh=↱ Ldsh=↲ Rdsh=↳ twoheaduparrow=↟ twoheaddownarrow=↡ updownarrows=⇅ downuparrows=⇵ leftsquigarrow=⇜ longrightsquigarrow=⟿
75
84
  `, {variant: 'roman'});
76
85
  mathSymbolGroup('op', `
77
86
  sum=∑ prod=∏ coprod=∐ bigcup=⋃ bigcap=⋂ bigvee=⋁ bigwedge=⋀ biguplus=⨄ bigsqcup=⨆
78
- bigotimes=⨂ bigoplus=⨁ bigodot=⨀ bigamalg=⨿ bigsqcap=⨅
87
+ bigotimes=⨂ bigoplus=⨁ bigodot=⨀ bigamalg=∐ bigsqcap=⨅ bigcupdot=⨃ bigtimes=⨉
79
88
  `, {large: true, limits: 'display', variant: 'roman'});
80
89
  mathSymbolGroup('op', `
81
90
  int=∫ iint=∬ iiint=∭ iiiint=⨌ oint=∮ oiint=∯ oiiint=∰ intop=∫ smallint=∫
82
- intclockwise=∱ varointclockwise=∲ ointctrclockwise=∳ sumint=⨋
91
+ intclockwise=∱ varointclockwise=∲ ointctrclockwise=∳ sumint=⨋ awint=⨑
83
92
  `, {large: true, limits: 'never', variant: 'roman'});
84
93
  MATH_SYMBOLS.intop = Object.freeze({...MATH_SYMBOLS.intop, limits: 'display'});
85
94
  MATH_SYMBOLS.smallint = Object.freeze({...MATH_SYMBOLS.smallint, large: false});
86
- mathSymbolGroup('open', 'langle=⟨ lbrace={ lgroup=⟮ lbrack=[ lfloor=⌊ lceil=⌈ lvert=| lVert=‖ lmoustache=⎰ llbracket=⟦ ulcorner=⌜ llcorner=⌞', {variant: 'roman'});
87
- mathSymbolGroup('close', 'rangle=⟩ rbrace=} rgroup=⟯ rbrack=] rfloor=⌋ rceil=⌉ rvert=| rVert=‖ rmoustache=⎱ rrbracket=⟧ urcorner=⌝ lrcorner=⌟', {variant: 'roman'});
88
- mathSymbolGroup('ord', 'vert=| Vert=‖ backslash=∖ slash=/', {variant: 'roman'});
95
+ mathSymbolGroup('open', 'langle/lang=⟨ lAngle=⟪ lbrace={ lgroup=⟮ lbrack=[ lfloor=⌊ lceil=⌈ lvert=| lVert=‖ lmoustache=⎰ llbracket=⟦ ulcorner=⌜ llcorner=⌞', {variant: 'roman'});
96
+ mathSymbolGroup('close', 'rangle/rang=⟩ rAngle=⟫ rbrace=} rgroup=⟯ rbrack=] rfloor=⌋ rceil=⌉ rvert=| rVert=‖ rmoustache=⎱ rrbracket=⟧ urcorner=⌝ lrcorner=⌟', {variant: 'roman'});
97
+ mathSymbolGroup('ord', 'vert=| Vert=‖ backslash=\\ slash=/', {variant: 'roman'});
89
98
  mathSymbolGroup('inner', 'dotsc=… cdots=⋯ dotsb=⋯ dotsm=⋯ dotsi=⋯ dotso=… ddots=⋱ mathellipsis=…', {variant: 'roman'});
90
99
  mathSymbolGroup('ord', 'vdots=⋮', {variant: 'roman'});
100
+ mathSymbolGroup('inner', 'iddots/adots=⋰', {variant: 'roman'});
91
101
  mathSymbolGroup('punct', 'colon=: cdotp=⋅', {variant: 'roman'});
92
102
  MATH_SYMBOLS.ldots = MATH_SYMBOLS.dots = Object.freeze({type: 'glyph', value: '…', class: 'inner', variant: 'roman'});
93
103
  for (const [name, symbol] of Object.entries(MATH_SYMBOLS)) {
94
104
  const {variant, ...fields} = symbol;
95
105
  MATH_SYMBOLS[name] = Object.freeze({...fields, defaultVariant: variant});
96
106
  }
97
- const MATH_NAMED_OPERATORS = new Set(('arccos arcsin arctan arccot arcsec arccsc cos cosh cot coth csc csch sec sech sin sinh tan tanh exp log ln lg lb det dim gcd hom ker arg deg Pr erf erfc mod').split(' '));
107
+ const MATH_NAMED_OPERATORS = new Set(('arccos arcsin arctan arccot arcsec arccsc cos cosh cot coth csc csch sec sech sin sinh tan tanh exp log ln lg lb det dim gcd hom ker arg deg Pr erf erfc').split(' '));
98
108
  const MATH_LIMIT_OPERATORS = new Set(('lim limsup liminf sup inf max min injlim projlim varlimsup varliminf varinjlim varprojlim').split(' '));
99
109
 
100
110
 
@@ -2,11 +2,11 @@
2
2
  // Unicode mathematical alphabets shared by SVG and MathML. No font lookup.
3
3
  const MATH_STYLED_RANGES = {
4
4
  italic: [0x1d434, 0x1d44e, null], bold: [0x1d400, 0x1d41a, 0x1d7ce],
5
- 'bold-italic': [0x1d468, 0x1d482, null], script: [0x1d49c, 0x1d4b6, null],
5
+ 'bold-italic': [0x1d468, 0x1d482, 0x1d7ce], script: [0x1d49c, 0x1d4b6, null],
6
6
  'bold-script': [0x1d4d0, 0x1d4ea, null], fraktur: [0x1d504, 0x1d51e, null],
7
7
  'bold-fraktur': [0x1d56c, 0x1d586, null], 'double-struck': [0x1d538, 0x1d552, 0x1d7d8],
8
8
  'sans-serif': [0x1d5a0, 0x1d5ba, 0x1d7e2], 'sans-serif-bold': [0x1d5d4, 0x1d5ee, 0x1d7ec],
9
- 'sans-serif-italic': [0x1d608, 0x1d622, null], 'sans-serif-bold-italic': [0x1d63c, 0x1d656, null],
9
+ 'sans-serif-italic': [0x1d608, 0x1d622, null], 'sans-serif-bold-italic': [0x1d63c, 0x1d656, 0x1d7ec],
10
10
  monospace: [0x1d670, 0x1d68a, 0x1d7f6],
11
11
  };
12
12
  const MATH_STYLED_LEGACY = {
@@ -12,10 +12,10 @@ import {mathModules, mathClassicSource} from '../math/package-build.mjs';
12
12
  import {mathReadme} from '../math/package-readme.mjs';
13
13
 
14
14
  const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
15
- export const MATH_VERSION = '2.2.0';
15
+ export const MATH_VERSION = '2.4.0';
16
16
  export const MATH_BUNDLE = 'rapier-math-' + MATH_VERSION + '.js';
17
17
  export const MATH_SOURCES = ['font.js', 'symbols.js', 'parser.js', 'source.js', 'variants.js', 'layout.js', 'fallbacks.js', 'responsive.js', 'api.js', 'browser.js', 'mathml.js', 'semantic-api.js', 'combined.js', 'classic.js'].map(name => 'math/' + name);
18
- export const MATH_RECIPE = ['math/build-font.py', 'math/FONT-SOURCE.md', 'math/FONT-LICENSE.txt', 'math/package-verify.mjs', 'tools/build-math.mjs', 'math/LICENSE-MIT', 'math/adoption-verify.mjs', 'math/package-build.mjs', 'math/package-layout.mjs', 'math/package-check.mjs', 'math/package-readme.mjs', 'math/README.md', 'math/SEMANTICS.md', 'math/semantic-verify.mjs'];
18
+ export const MATH_RECIPE = ['math/build-font.py', 'math/FONT-SOURCE.md', 'math/FONT-LICENSE.txt', 'math/package-verify.mjs', 'tools/build-math.mjs', 'math/LICENSE-MIT', 'math/adoption-verify.mjs', 'math/package-build.mjs', 'math/package-layout.mjs', 'math/package-check.mjs', 'math/package-readme.mjs', 'math/README.md', 'math/SEMANTICS.md', 'math/semantic-verify.mjs', 'math/typeset-verify.mjs'];
19
19
  export const MATH_ADOPTION = ['delimiters.mjs', 'markdown-rules.mjs', 'reuse.mjs', 'integration.mjs', 'markdown-it.mjs', 'rehype.mjs', 'stream.mjs',
20
20
  'accessible.mjs', 'accessible.css', 'mathml.d.ts', 'combined.d.ts', 'accessible.d.ts',
21
21
  'index.d.ts', 'classic.d.ts', 'delimiters.d.ts', 'integration.d.ts', 'markdown-it.d.ts', 'rehype.d.ts', 'stream.d.ts',
@@ -122,7 +122,7 @@ export async function buildMath({root = ROOT, updatePins = true, packageLayout =
122
122
  const version = /var MATH_VERSION = '[^']+';/;
123
123
  if (!version.test(loader)) throw new Error('The math loader version could not be located');
124
124
  // The route keeps its release-tagged origin (tools/version-sync.mjs); only the bundle's filename changes.
125
- const cdn = /(key: 'math',[\s\S]*?cdn: '(https:\/\/cdn\.jsdelivr\.net\/gh\/jackskip22\/rapier-plugins@[^/']+\/)math\/)[^']+(')/;
125
+ const cdn = /(key: 'math',[\s\S]*?url: '(https:\/\/cdn\.jsdelivr\.net\/gh\/jackskip22\/rapier-plugins@[^/']+\/)math\/)[^']+(')/;
126
126
  if (!cdn.test(loader)) throw new Error('The math loader CDN pin could not be located');
127
127
  await writeFile(loaderPath, loader.replace(version, "var MATH_VERSION = '" + MATH_VERSION + "';")
128
128
  .replace(block, (_, before, middle, after) => before + bytes.length + middle + sha384 + after)
@@ -0,0 +1,172 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Typesetting faults, each with its reproducer. Where the TeXbook's Appendix G decides, the expected
3
+ // value is LuaTeX's own output for the same formula (unicode-math, Latin Modern Math 1.959), in ems.
4
+ // Replay: node tests/typeset.mjs [package-root]. Ink is measured from the font's own contour strips.
5
+ import assert from 'node:assert/strict';
6
+ import {dirname, resolve} from 'node:path';
7
+ import {fileURLToPath, pathToFileURL} from 'node:url';
8
+
9
+ const root = resolve(process.argv[2] || resolve(dirname(fileURLToPath(import.meta.url)), '..'));
10
+ const load = file => import(pathToFileURL(resolve(root, 'src/math', file)).href);
11
+ const {MATH_FONT} = await load('font.js'), L = await load('layout.js');
12
+ const {mathPrepare} = await load('source.js'), {mathToMathML} = await load('semantic-api.js'), {renderMath} = await load('api.js');
13
+ const context = (display = false) => ({size: 1, level: 0, variant: 'normal', cramped: false, display, cache: new WeakMap(), budget: {nodes: 0, outlineBytes: 0}});
14
+ function layout(tex, display = false) {
15
+ const {tree, error} = mathPrepare(tex);
16
+ assert(!error, tex + ': ' + error?.message);
17
+ return L.mathLayout(tree, context(display));
18
+ }
19
+ const mathml = tex => mathToMathML(tex).mathml;
20
+
21
+ // Every outline in an SVG fragment: its glyph, origin and scale, from the transforms that place it.
22
+ const paths = new Map();
23
+ function glyphOf(d) {
24
+ if (!paths.size) for (let id = 0, g; (g = MATH_FONT.glyph(id)); id++) { if (g?.[7] && !paths.has(g[7])) paths.set(g[7], id); }
25
+ return paths.get(d);
26
+ }
27
+ function glyphs(svg) {
28
+ const found = [], stack = [[0, 0, 1, 1]];
29
+ for (const [tag] of svg.matchAll(/<\/?g\b[^>]*>|<path\b[^>]*>/g)) {
30
+ if (tag === '</g>') { stack.pop(); continue; }
31
+ const [x, y, sx, sy] = stack.at(-1), t = /translate\(([-\d.e]+) ([-\d.e]+)\)/.exec(tag), s = /scale\(([-\d.e]+) ([-\d.e]+)\)/.exec(tag);
32
+ let next = [x, y, sx, sy];
33
+ if (tag.startsWith('<g')) {
34
+ if (t) next = [x + sx * +t[1], y + sy * +t[2], sx, sy];
35
+ if (s) next = [next[0], next[1], sx * +s[1], sy * +s[2]];
36
+ stack.push(next);
37
+ } else {
38
+ const d = /\bd="([^"]+)"/.exec(tag)?.[1], id = d && glyphOf(d);
39
+ if (id !== undefined && s) found.push({id, x, y, sx: sx * +s[1], sy: sy * -s[2]});
40
+ }
41
+ }
42
+ return found;
43
+ }
44
+ // Horizontal ink strips of a placed glyph (its contour profile; its bounds when unprofiled).
45
+ function strips({id, x, y, sx, sy}) {
46
+ const g = MATH_FONT.glyph(id), p = MATH_FONT.profile(id), out = [];
47
+ if (!p) return [{top: y - g[4] * sy, bottom: y - g[2] * sy, left: x + g[1] * sx, right: x + g[3] * sx}];
48
+ for (let i = 1; i < p.length; i++) if (p[i])
49
+ out.push({top: y - (p[0] + i * MATH_FONT.edgeStep) * sy, bottom: y - (p[0] + (i - 1) * MATH_FONT.edgeStep) * sy, left: x + p[i][0] * sx, right: x + p[i][1] * sx});
50
+ return out;
51
+ }
52
+ // Smallest horizontal gap between two glyphs' ink where they share a height; negative when the ink overlaps.
53
+ function inkGap(a, b) {
54
+ let gap = Infinity;
55
+ for (const s of strips(a)) for (const t of strips(b))
56
+ if (s.top < t.bottom && t.top < s.bottom) gap = Math.min(gap, Math.max(t.left - s.right, s.left - t.right) <= 0 ? -Math.min(s.right - t.left, t.right - s.left) : Math.max(t.left - s.right, s.left - t.right));
57
+ return gap;
58
+ }
59
+ const ink = item => strips(item).reduce((r, s) => ({left: Math.min(r.left, s.left), right: Math.max(r.right, s.right), top: Math.min(r.top, s.top), bottom: Math.max(r.bottom, s.bottom)}), {left: Infinity, right: -Infinity, top: Infinity, bottom: -Infinity});
60
+ const near = (actual, expected, message, tolerance = 0.01) => assert(Math.abs(actual - expected) <= tolerance, message + ': ' + actual.toFixed(3) + ' (TeX ' + expected + ')');
61
+
62
+ const cells = [];
63
+ const cell = (id, claim, check) => cells.push({id, claim, check});
64
+
65
+ cell('F1', 'a superscript clears an over-accent', () => {
66
+ for (const tex of [String.raw`\hat{i}^2`, String.raw`\vec{x}^2`, String.raw`\tilde{\jmath}^2`, String.raw`\dot{x}^n`]) {
67
+ const [, accent, script] = glyphs(layout(tex).svg);
68
+ assert(inkGap(accent, script) > 0, tex + ': superscript ink meets the accent');
69
+ }
70
+ // TeX's rule 18a keeps \hat{x}^2 where x^2 is.
71
+ near(glyphs(layout(String.raw`\hat{x}^2`).svg)[2].x, glyphs(layout('x^2').svg)[1].x, String.raw`\hat{x}^2 script`, 0.08);
72
+ });
73
+ cell('F2', 'a subscript keeps the slanted letter clear of the next', () => {
74
+ for (const tex of ['V_i H', 'V_i T', 'W_i Y']) {
75
+ const items = glyphs(layout(tex).svg);
76
+ assert(inkGap(items[0], items.at(-1)) >= 0, tex + ': the next letter meets the slanted letter');
77
+ }
78
+ });
79
+ cell('F3', 'an under-accent adds only its own depth', () => {
80
+ assert(layout(String.raw`\utilde{x}`).d <= 0.492, String.raw`\utilde{x} depth exceeds TeX's 0.492`);
81
+ assert(layout(String.raw`\underaccent{\bar}{x}`).d <= 0.439, String.raw`\underaccent{\bar}{x} depth exceeds TeX's 0.439`);
82
+ });
83
+ cell('F4', 'braces centre on slanted letters', () => {
84
+ const over = glyphs(layout(String.raw`\overbrace{f}`, true).svg), f = over.find(item => item.id === MATH_FONT.chars[0x1d453]);
85
+ const middle = item => (ink(item).left + ink(item).right) / 2;
86
+ near(middle(over.find(item => item !== f)) - f.x, layout('f', true).w / 2, String.raw`\overbrace{f} brace centre`, 0.01);
87
+ const v = layout(String.raw`\underbrace{V}_n`, true), items = glyphs(v.svg), n = items.at(-1), nW = MATH_FONT.glyph(n.id)[0] * n.sx;
88
+ const vItem = items.find(item => item.id === MATH_FONT.chars[0x1d449]);
89
+ near(n.x + nW / 2 - vItem.x, layout('V', true).w / 2, String.raw`\underbrace{V}_n label centre`, 0.01);
90
+ });
91
+ cell('F5', 'a radical degree kerns into the sign', () => {
92
+ const sign = glyphs(layout(String.raw`\sqrt[3]{x}`).svg).find(item => item.id === MATH_FONT.chars[0x221a]);
93
+ near(sign.x, 0.062, String.raw`\sqrt[3]{x} sign x`, 0.003);
94
+ });
95
+ cell('F6', 'corner delimiters sit where TeX puts them', () => {
96
+ const items = glyphs(layout(String.raw`\left\ulcorner\frac{a}{b}\right\urcorner`, true).svg);
97
+ near(items[0].y, 0.135, String.raw`\ulcorner origin y`);
98
+ const low = glyphs(layout(String.raw`\left\llcorner\frac{a}{b}\right\lrcorner`, true).svg);
99
+ near(low[0].y, -0.380, String.raw`\llcorner origin y`);
100
+ });
101
+ cell('F7', 'starred cases set conditions as text', () => {
102
+ const {tree, error} = mathPrepare(String.raw`\begin{cases*} x & if $x > 0$ \\ 0 & otherwise \end{cases*}`);
103
+ assert(!error, 'cases*: ' + error?.message);
104
+ const condition = JSON.stringify(tree.children[0].body ?? tree.children[0]);
105
+ assert(/"type":"text","value":"if/.test(condition) && /"value":"otherwise"/.test(condition), 'cases* condition is text');
106
+ });
107
+ cell('F8', 'mhchem isotopes', () => {
108
+ const {tree, error} = mathPrepare(String.raw`\ce{^{235}_{92}U + ^1_0n}`);
109
+ assert(!error);
110
+ assert(!/"base":\{"type":"glyph","value":"\+"/.test(JSON.stringify(tree)), String.raw`\ce: the scripts before n stay on n, not on +`);
111
+ const items = glyphs(layout(String.raw`\ce{^{235}_{92}U}`).svg), right = item => item.x + MATH_FONT.glyph(item.id)[0] * item.sx;
112
+ near(right(items[2]), right(items[4]), String.raw`\ce isotope scripts end together (TeX)`, 0.002);
113
+ });
114
+ cell('F9', 'bold digits and bold dotless letters', () => {
115
+ assert.equal(layout(String.raw`\boldsymbol{0}`).glyph, MATH_FONT.chars[0x1d7ce], String.raw`\boldsymbol{0} is a bold digit`);
116
+ assert.equal(layout(String.raw`\bm{1}`).glyph, MATH_FONT.chars[0x1d7cf], String.raw`\bm{1} is a bold digit`);
117
+ assert.equal(layout(String.raw`\boldsymbol{\imath}`).glyph, MATH_FONT.dotless[MATH_FONT.chars[0x1d48a]], String.raw`\boldsymbol{\imath} is bold dotless`);
118
+ assert.equal(layout(String.raw`\mathbf{\jmath}`).glyph, MATH_FONT.dotless[MATH_FONT.chars[0x1d423]], String.raw`\mathbf{\jmath} is bold dotless`);
119
+ });
120
+ cell('F10', 'binary and fraction spacing, matrix cells', () => {
121
+ near(layout(String.raw`a\boldsymbol{+}b`).w, 2.180, String.raw`a\boldsymbol{+}b width`, 0.002);
122
+ near(layout(String.raw`a\textcolor{red}{+}b`).w, 1.736, String.raw`a\textcolor{red}{+}b width (a braced group is ordinary)`, 0.002);
123
+ const f = layout(String.raw`\frac{1}{2},`);
124
+ near(f.rowItems[1][1] - f.rowItems[0][0].w, 0, String.raw`\frac{1}{2}, space before the comma`, 0.002);
125
+ const cramped = layout(String.raw`\frac{1}{\begin{matrix}x^2\end{matrix}}`, true), plain = layout(String.raw`\begin{matrix}x^2\end{matrix}`);
126
+ near(glyphs(cramped.svg).at(-1).y - glyphs(cramped.svg).at(-2).y, glyphs(plain.svg).at(-1).y - glyphs(plain.svg).at(-2).y, 'matrix cell superscript rise inside a denominator', 0.001);
127
+ });
128
+ cell('F11', 'MathML Core attributes', () => {
129
+ assert(!/movablelimits="false">max/.test(mathml(String.raw`\overline{A_{\max}}`)), String.raw`\max in a script keeps its own limits`);
130
+ assert(/<mtable displaystyle="true"[^>]*data-math-environment="darray"/.test(mathml(String.raw`\begin{darray}{c}x\end{darray}`)), 'darray is display style');
131
+ assert(/<mi[^>]*>℧<\/mi><mi[^>]*>⅁<\/mi>/.test(mathml(String.raw`\mho\Game`)), String.raw`\mho and \Game are identifiers`);
132
+ assert(!/form="infix"[^>]*>\+/.test(mathml('(a+)')), 'a trailing plus is not infix');
133
+ });
134
+ cell('F12', 'colour paints once; a fence without \\middle lays out once', () => {
135
+ const svg = renderMath(String.raw`\color{red}a+b+c=1+2+3`, {maxWidth: 3}).svg;
136
+ assert(!/<g fill="red"[^>]*><g fill="red"/.test(svg), 'colour is painted twice');
137
+ const {tree} = mathPrepare(String.raw`\left(a+b\right)`), c = context();
138
+ L.mathLayout(tree, c);
139
+ const {tree: body} = mathPrepare('(a+b)'), d = context();
140
+ L.mathLayout(body, d);
141
+ assert(c.budget.nodes <= d.budget.nodes, 'fence body laid out twice: ' + c.budget.nodes + ' visits for ' + d.budget.nodes);
142
+ });
143
+ cell('F13', 'what people write most', () => {
144
+ const inputs = [String.raw`\SI{9.81}{m.s^{-2}}`, String.raw`\SI{3}{\kilo\gram\metre\per\second\squared}`, String.raw`\num{12345.678}`, String.raw`\si{\ohm}`, String.raw`\unit{\micro\metre}`, String.raw`\ang{30;15;10}`,
145
+ String.raw`\mel{n}{H}{m}`, String.raw`\ev{x}`, String.raw`\ip{a}{b}`, String.raw`\op{a}{b}`, String.raw`\pb{f}{g}`, String.raw`\qq{if}`, String.raw`\qc`, String.raw`\Res`,
146
+ String.raw`\idotsint`, String.raw`\smashoperator{\sum_{i=1}^n}`, String.raw`\begin{multlined}a\\b\end{multlined}`, String.raw`\begin{lgathered}a\\b\end{lgathered}`, String.raw`\begin{rgathered}a\\b\end{rgathered}`,
147
+ String.raw`\mathmakebox[2em][l]{x}`, String.raw`\not\in`, String.raw`\not\subset`];
148
+ const rejected = inputs.filter(tex => mathPrepare(tex).error);
149
+ assert.deepEqual(rejected, [], 'rejected');
150
+ });
151
+
152
+ cell('P1', 'a formula being typed previews without an error', () => {
153
+ for (const tex of [String.raw`\frac{-b\pm\sqrt{b^2-4ac}}{2a}`, String.raw`\begin{pmatrix}1 & 2\\3 & 4\end{pmatrix}`, String.raw`\left(x+1\right)^{\sqrt[3]{y}}`])
154
+ for (let i = 1; i <= tex.length; i++) {
155
+ const prefix = tex.slice(0, i), result = renderMath(prefix, {preview: true});
156
+ assert.deepEqual(result.errors, [], 'preview of ' + prefix);
157
+ assert(result.svg.includes('<title>' + prefix.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</title>'), 'exact source of ' + prefix);
158
+ }
159
+ for (const [tex, caret] of [[String.raw`\sqrt{x^}`, 8], [String.raw`\sqrt{x+\}`, 9], [String.raw`a+\fra{}`, 6]])
160
+ assert.deepEqual(renderMath(tex, {preview: true, caret}).errors, [], 'preview at the caret of ' + tex);
161
+ assert.equal(renderMath(String.raw`\frac{1}{`).errors.length, 1, 'strict rendering is unchanged');
162
+ assert.equal(renderMath(String.raw`\frac{a}{b} \farc + 1`, {preview: true}).errors[0]?.suggestion, String.raw`\frac`, 'a fault before the end stays, with a suggestion');
163
+ });
164
+
165
+ const results = [];
166
+ for (const {id, claim, check} of cells) {
167
+ try { check(); results.push([id, 'green', claim]); }
168
+ catch (error) { results.push([id, 'red', claim + ': ' + error.message]); }
169
+ }
170
+ for (const row of results) console.log(row.join('\t'));
171
+ assert(results.every(row => row[1] === 'green'), 'red cells');
172
+ console.log(JSON.stringify({cells: results.length, typesetting: 'TeX where Appendix G decides'}));