-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
70 lines (61 loc) · 2.1 KB
/
index.ts
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
import type { Root, RootContent } from 'hast';
import type { Plugin } from 'unified';
import temml from 'temml';
import { SKIP, visitParents } from 'unist-util-visit-parents';
import { toText } from 'hast-util-to-text';
import { fromHtmlIsomorphic } from 'hast-util-from-html-isomorphic';
type Options = Partial<temml.Options>;
const rehypeMathML: Plugin<[Options?], Root> = (options) => {
return (tree) => {
visitParents(tree, 'element', (element, parents) => {
const classes = Array.isArray(element.properties.className)
? element.properties.className
: [];
const languageMath = classes.includes('language-math');
const mathDisplay = classes.includes('math-display');
const mathInline = classes.includes('math-inline');
if (!languageMath && !mathDisplay && !mathInline) return;
let scope = element;
let parent = parents[parents.length - 1];
let displayMode = mathDisplay;
if (
element.tagName === 'code' &&
languageMath &&
parent &&
parent.type === 'element' &&
parent.tagName === 'pre'
) {
scope = parent;
parent = parents[parents.length - 2];
displayMode = true;
}
if (!parent) return;
const latex = toText(scope, { whitespace: 'pre' });
let result: RootContent[];
try {
const mathml = temml.renderToString(
latex,
Object.assign({}, options || {}, { displayMode: displayMode }),
);
result = fromHtmlIsomorphic(mathml, { fragment: true }).children;
} catch (error) {
result = [
{
type: 'element',
tagName: 'span',
properties: {
className: ['rehype-mathml-error'],
style: 'color:' + ((options || {}).errorColor || '#b22222'),
title: String(error),
},
children: [{ type: 'text', value: latex }],
},
];
}
const index = parent.children.indexOf(scope);
parent.children.splice(index, 1, ...result);
return SKIP;
});
};
};
export default rehypeMathML;