1import {displayError} from './common.js';
2
3function targetElement(el) {
4 // The target element is either the current element if it has the
5 // `is-loading` class or the pre that contains it
6 return el.classList.contains('is-loading') ? el : el.closest('pre');
7}
8
9export async function renderMath() {
10 const els = document.querySelectorAll('.markup code.language-math');
11 if (!els.length) return;
12
13 const [{default: katex}] = await Promise.all([
14 import(/* webpackChunkName: "katex" */'katex/dist/katex.js'),
15 import(/* webpackChunkName: "katex" */'katex/dist/katex.css'),
16 ]);
17
18 const MAX_CHARS = 1000;
19 const MAX_SIZE = 25;
20 const MAX_EXPAND = 1000;
21
22 for (const el of els) {
23 const target = targetElement(el);
24 if (target.hasAttribute('data-render-done')) continue;
25 const source = el.textContent;
26
27 if (source.length > MAX_CHARS) {
28 displayError(target, new Error(`Math source of ${source.length} characters exceeds the maximum allowed length of ${MAX_CHARS}.`));
29 continue;
30 }
31
32 const displayMode = el.classList.contains('display');
33 const nodeName = displayMode ? 'p' : 'span';
34
35 try {
36 const tempEl = document.createElement(nodeName);
37 katex.render(source, tempEl, {
38 maxSize: MAX_SIZE,
39 maxExpand: MAX_EXPAND,
40 displayMode,
41 });
42 target.replaceWith(tempEl);
43 } catch (error) {
44 displayError(target, error);
45 }
46 }
47}