-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrender-math.js
More file actions
411 lines (341 loc) · 12.2 KB
/
Copy pathrender-math.js
File metadata and controls
411 lines (341 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import { mathjax } from 'mathjax-full/js/mathjax';
import { MathJax as globalMathjax } from 'mathjax-full/js/components/global';
import { AssistiveMmlHandler } from 'mathjax-full/js/a11y/assistive-mml';
import { EnrichHandler } from 'mathjax-full/js/a11y/semantic-enrich';
import { MenuHandler } from 'mathjax-full/js/ui/menu/MenuHandler';
import { FindMathML } from 'mathjax-full/js/input/mathml/FindMathML';
import { MathML } from 'mathjax-full/js/input/mathml';
import { TeX } from 'mathjax-full/js/input/tex';
import { CHTML } from 'mathjax-full/js/output/chtml';
import { RegisterHTMLHandler } from 'mathjax-full/js/handlers/html';
import { browserAdaptor } from 'mathjax-full/js/adaptors/browserAdaptor';
import { AllPackages } from 'mathjax-full/js/input/tex/AllPackages';
import { engineReady } from 'speech-rule-engine/js/common/system';
// import pkg from '../../package.json';
import { chtmlNodes, mmlNodes } from './mstack';
import debug from 'debug';
import { unWrapMath, wrapMath } from './normalization';
import { MmlFactory } from 'mathjax-full/js/core/MmlTree/MmlFactory';
import { SerializedMmlVisitor } from 'mathjax-full/js/core/MmlTree/SerializedMmlVisitor';
import { CHTMLWrapperFactory } from 'mathjax-full/js/output/chtml/WrapperFactory';
import { CHTMLmspace } from 'mathjax-full/js/output/chtml/Wrappers/mspace';
import { HTMLDomStrings } from 'mathjax-full/js/handlers/html/HTMLDomStrings';
if (typeof window !== 'undefined') {
RegisterHTMLHandler(browserAdaptor());
}
let sreReady = false;
engineReady().then(() => {
sreReady = true;
});
const visitor = new SerializedMmlVisitor();
const toMMl = (node) => visitor.visitTree(node);
const log = debug('pie-lib:math-rendering');
const NEWLINE_BLOCK_REGEX = /\\embed\{newLine\}\[\]/g;
const NEWLINE_LATEX = '\\newline ';
const getGlobal = () => {
// TODO does it make sense to use version?
// const key = `${pkg.name}@${pkg.version.split('.')[0]}`;
// It looks like Ed made this change when he switched from mathjax3 to mathjax-full
// I think it was supposed to make sure version 1 (using mathjax3) is not used
// in combination with version 2 (using mathjax-full)
// TODO higher level wrappers use this instance of math-rendering, and if 2 different instances are used, math rendering is not working
// so I will hardcode this for now until a better solution is found
const key = '@pie-lib/math-rendering@2';
if (typeof window !== 'undefined') {
if (!window[key]) {
window[key] = {};
}
return window[key];
} else {
return {};
}
};
/** Add temporary support for a global singleDollar override
* <code>
* // This will enable single dollar rendering
* window.pie = window.pie || {};
* window.pie.mathRendering = {useSingleDollar: true };
* </code>
*/
const defaultOpts = () => getGlobal().opts || {};
export const fixMathElement = (element) => {
if (element.dataset.mathHandled) {
return;
}
let property = 'innerText';
if (element.textContent) {
property = 'textContent';
}
if (element[property]) {
element[property] = wrapMath(unWrapMath(element[property]).unwrapped);
// because mathquill doesn't understand line breaks, sometimes we end up with custom elements on prompts/rationale/etc.
// we need to replace the custom embedded elements with valid latex that Mathjax can understand
element[property] = element[property].replace(NEWLINE_BLOCK_REGEX, NEWLINE_LATEX);
element.dataset.mathHandled = true;
}
};
export const fixMathElements = (el = document) => {
const mathElements = el.querySelectorAll('[data-latex]');
mathElements.forEach((item) => fixMathElement(item));
};
const adjustMathMLStyle = (el = document) => {
const nodes = el.querySelectorAll('math');
nodes.forEach((node) => node.setAttribute('displaystyle', 'true'));
};
class myFindMathML extends FindMathML {
processMath(set) {
const adaptor = this.adaptor;
for (const mml of Array.from(set)) {
if (adaptor.kind(adaptor.parent(mml)) === 'mjx-assistive-mml') {
set.delete(mml);
}
}
return super.processMath(set);
}
}
const createMathMLInstance = (opts, docProvided = document) => {
opts = opts || defaultOpts();
if (opts.useSingleDollar) {
// eslint-disable-next-line
console.warn('[math-rendering] using $ is not advisable, please use $$..$$ or \\(...\\)');
}
const packages = AllPackages.filter((name) => name !== 'bussproofs'); // Bussproofs needs an output jax
// The autoload extension predefines all the macros from the extensions that haven't been loaded already
// so that they automatically load the needed extension when they are first used
packages.push('autoload');
const macros = {
parallelogram: '\\lower.2em{\\Huge\\unicode{x25B1}}',
overarc: '\\overparen',
napprox: '\\not\\approx',
longdiv: '\\enclose{longdiv}',
abs: ['\\left|#1\\right|', 1],
};
const texConfig = opts.useSingleDollar
? {
packages,
macros,
inlineMath: [
['$', '$'],
['\\(', '\\)'],
],
processEscapes: true,
}
: {
packages,
macros,
};
const mmlConfig = {
parseError: function (node) {
// function to process parsing errors
// eslint-disable-next-line no-console
console.log('error:', node);
this.error(this.adaptor.textContent(node).replace(/\n.*/g, ''));
},
FindMathML: new myFindMathML(),
};
let cachedMathjax;
if (globalMathjax && globalMathjax.version !== mathjax.version) {
// handling other MathJax version on the page
// replacing it temporarily with the version we have
window.MathJax._ = window.MathJax._ || {};
window.MathJax.config = window.MathJax.config || {};
cachedMathjax = window.MathJax;
Object.assign(globalMathjax, mathjax);
}
const fontURL = `https://unpkg.com/mathjax-full@${mathjax.version}/ts/output/chtml/fonts/tex-woff-v2`;
const htmlConfig = {
fontURL,
wrapperFactory: new CHTMLWrapperFactory({
...CHTMLWrapperFactory.defaultNodes,
...chtmlNodes,
}),
};
const mml = new MathML(mmlConfig);
const customMmlFactory = new MmlFactory({
...MmlFactory.defaultNodes,
...mmlNodes,
});
const classFactory = EnrichHandler(
MenuHandler(AssistiveMmlHandler(mathjax.handlers.handlesDocument(docProvided))),
mml,
);
const html = classFactory.create(docProvided, {
compileError: (mj, math, err) => {
// eslint-disable-next-line no-console
console.log('bad math?:', math);
// eslint-disable-next-line no-console
console.error(err);
},
typesetError: function (doc, math, err) {
// eslint-disable-next-line no-console
console.log('typeset error');
// eslint-disable-next-line no-console
console.error(err);
doc.typesetError(math, err);
},
sre: {
speech: 'deep',
},
enrichSpeech: 'deep',
InputJax: [new TeX(texConfig), mml],
OutputJax: new CHTML(htmlConfig),
DomStrings: new HTMLDomStrings({
skipHtmlTags: [
'script',
'noscript',
'style',
'textarea',
'pre',
'code',
'annotation',
'annotation-xml',
'mjx-assistive-mml',
'mjx-container',
],
}),
});
// Note: we must set this *after* mathjax.document (no idea why)
mml.setMmlFactory(customMmlFactory);
if (cachedMathjax) {
// if we have a cached version, we replace it here
window.MathJax = cachedMathjax;
}
return html;
};
let enrichSpeechInitialized = false;
const bootstrap = (opts) => {
if (typeof window === 'undefined') {
return { Typeset: () => ({}) };
}
const html = createMathMLInstance(opts);
return {
version: mathjax.version,
html: html,
Typeset: function (...elements) {
const attemptRender = (temporary = false) => {
let updatedDocument = this.html.findMath(elements.length ? { elements } : {}).compile();
if (!temporary && sreReady) {
try {
updatedDocument = updatedDocument.enrich();
} catch (e) {
// If enrich fails, speech-rule-engine isn't actually ready yet
// eslint-disable-next-line no-console
console.warn('[math-rendering] Speech-rule-engine not fully initialized, skipping enrichment');
sreReady = false;
}
}
updatedDocument = updatedDocument.getMetrics().typeset();
// assistiveMml() is what produces the <mjx-assistive-mml> element that
// screen readers (VoiceOver, JAWS, NVDA) use to read math semantically.
// It only serializes MathJax's internal MathML tree via LimitedMmlVisitor
// and does NOT depend on speech-rule-engine, so it must always run –
// otherwise fractions, roots, etc. get flattened to raw digits in AT.
try {
updatedDocument = updatedDocument.assistiveMml();
} catch (e) {
// eslint-disable-next-line no-console
console.warn('[math-rendering] Failed to attach assistive MathML:', e);
}
// attachSpeech() relies on speech strings computed during enrich(),
// which requires speech-rule-engine to be ready. Skip it gracefully
// if SRE isn't initialised yet – screen readers will still read the
// MathML structure produced above.
if (!temporary && sreReady) {
try {
updatedDocument = updatedDocument.attachSpeech();
} catch (e) {
// eslint-disable-next-line no-console
console.warn('[math-rendering] Speech-rule-engine not fully initialized, skipping speech attachment');
sreReady = false;
}
}
updatedDocument = updatedDocument.addMenu().updateDocument();
if (!enrichSpeechInitialized && typeof updatedDocument.math.list?.next?.data === 'object') {
enrichSpeechInitialized = true;
}
try {
const list = updatedDocument.math.list;
if (list) {
for (let item = list.next; typeof item.data !== 'symbol'; item = item.next) {
const mathMl = toMMl(item.data.root);
const parsedMathMl = mathMl.replaceAll('\n', '');
item.data.typesetRoot.setAttribute('data-mathml', parsedMathMl);
item.data.typesetRoot.setAttribute('tabindex', '-1');
}
}
} catch (e) {
// eslint-disable-next-line no-console
console.error(e.toString());
}
updatedDocument.clear();
};
if (!enrichSpeechInitialized) {
attemptRender(true);
}
mathjax.handleRetriesFor(() => {
attemptRender();
});
},
};
};
const renderMath = (el, renderOpts) => {
if (
window &&
window.MathJax &&
window.MathJax.customKey &&
window.MathJax.customKey == '@pie-lib/math-rendering-accessible@1'
) {
return;
}
const isString = typeof el === 'string';
let executeOn = document.body;
if (isString) {
const div = document.createElement('div');
div.innerHTML = el;
executeOn = div;
}
fixMathElements(executeOn);
adjustMathMLStyle(executeOn);
if (isString) {
const html = createMathMLInstance(undefined, executeOn);
const updatedDocument = html.findMath().compile().getMetrics().typeset().updateDocument();
const list = updatedDocument.math.list;
const item = list.next;
if (!item) {
return '';
}
const mathMl = toMMl(item.data.root);
const parsedMathMl = mathMl.replaceAll('\n', '');
return parsedMathMl;
}
if (!getGlobal().instance) {
getGlobal().instance = bootstrap(renderOpts);
}
if (!el) {
log('el is undefined');
return;
}
if (el instanceof Element && getGlobal().instance?.Typeset) {
getGlobal().instance.Typeset(el);
} else if (el.length && getGlobal().instance?.Typeset) {
const arr = Array.from(el);
getGlobal().instance.Typeset(...arr);
}
};
/**
* This style is added to overried default styling of mjx-mspace Mathjax tag
* In mathjax src code \newline latex gets parsed to <mjx-mspace></mjx-mspace>,
* but has the default style
* 'mjx-mspace': {
"display": 'in-line',
"text-align": 'left'
} which prevents it from showing as a newline value
*/
CHTMLmspace.styles = {
'mjx-mspace': {
display: 'block',
'text-align': 'center',
height: '5px',
},
};
export default renderMath;