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
#![forbid(unsafe_code)]
#![deny(missing_docs)]
use core::cell::RefCell;
pub mod error;
pub use error::{Error, Result};
pub mod opts;
pub use opts::{Opts, OptsBuilder, OutputType};
mod js_engine;
use js_engine::{Engine, JsEngine, JsValue};
const KATEX_SRC: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/vendor/katex.min.js"));
const MHCHEM_SRC: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/vendor/contrib/mhchem.min.js"
));
thread_local! {
static KATEX: Result<RefCell<Engine>> = init_katex();
}
fn init_katex<Engine: JsEngine>() -> Result<RefCell<Engine>> {
let mut engine = Engine::new()?;
engine.eval(KATEX_SRC)?;
engine.eval(MHCHEM_SRC)?;
engine.eval(
"function renderToString(input, opts) { return katex.renderToString(input, opts); }",
)?;
Ok(RefCell::new(engine))
}
#[inline]
fn render_inner<Engine: JsEngine>(
engine: &mut Engine,
input: &str,
opts: impl AsRef<Opts>,
) -> Result<String> {
use core::iter;
let input = Engine::JsValue::from_string(input.to_owned());
let opts: Engine::JsValue = opts.as_ref().to_js_value();
let args = iter::once(input).chain(iter::once(opts));
engine.call_function("renderToString", args)?.into_string()
}
pub fn render_with_opts(input: &str, opts: impl AsRef<Opts>) -> Result<String> {
KATEX.with(|engine| {
engine
.as_ref()
.map_err(|e| e.clone())
.and_then(|engine| render_inner(&mut *engine.borrow_mut(), input, opts))
})
}
#[inline]
pub fn render(input: &str) -> Result<String> {
render_with_opts(input, Opts::default())
}
#[cfg(test)]
mod tests;