forked from remarkjs/remark-math
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
73 lines (60 loc) · 1.98 KB
/
index.js
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
/**
* @typedef {import('hast').Root} Root
* @typedef {import('katex').KatexOptions} Options
*/
import katex from 'katex'
import {visit} from 'unist-util-visit'
import {removePosition} from 'unist-util-remove-position'
import {toText} from 'hast-util-to-text'
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
const assign = Object.assign
const parseHtml = unified().use(rehypeParse, {fragment: true})
const source = 'rehype-katex'
/**
* Plugin to transform `<span class=math-inline>` and `<div class=math-display>`
* with KaTeX.
*
* @type {import('unified').Plugin<[Options?]|void[], Root>}
*/
export default function rehypeKatex(options) {
const settings = options || {}
const throwOnError = settings.throwOnError || false
return (tree, file) => {
visit(tree, 'element', (element) => {
const classes =
element.properties && Array.isArray(element.properties.className)
? element.properties.className
: []
const inline = classes.includes('math-inline')
const displayMode = classes.includes('math-display')
if (!inline && !displayMode) {
return
}
const value = toText(element, {whitespace: 'pre'})
/** @type {string} */
let result
try {
result = katex.renderToString(
value,
assign({}, settings, {displayMode, throwOnError: true})
)
} catch (error_) {
const error = /** @type {Error} */ (error_)
const fn = throwOnError ? 'fail' : 'message'
const origin = [source, error.name.toLowerCase()].join(':')
file[fn](error.message, element.position, origin)
result = katex.renderToString(
value,
assign({}, settings, {
displayMode,
throwOnError: false,
strict: 'ignore'
})
)
}
// @ts-expect-error: assume no `doctypes` in KaTeX result.
element.children = removePosition(parseHtml.parse(result), true).children
})
}
}