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
use katex_wasmbind::{KaTeXOptions, OutputType};
use yew::{prelude::*, Component, ComponentLink, Html, ShouldRender};

#[derive(Properties, Clone, PartialEq)]
pub struct KaTeXProperties {
    pub math: String,
    #[prop_or(true)]
    pub inline: bool,
    #[prop_or(false)]
    pub mathml: bool,
}

pub struct KaTeX {
    pub math_rendered: Html,
    pub props: KaTeXProperties,
}

impl Component for KaTeX {
    type Message = ();
    type Properties = KaTeXProperties;

    fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self {
        Self { math_rendered: Default::default(), props }
    }

    fn update(&mut self, _: Self::Message) -> ShouldRender {
        false
    }

    fn change(&mut self, props: Self::Properties) -> ShouldRender {
        match self.props == props {
            true => false,
            false => {
                self.props = props;
                true
            }
        }
    }

    fn view(&self) -> Html {
        let mut render = if self.props.inline {
            KaTeXOptions::inline_mode()
        }
        else {
            KaTeXOptions::display_mode()
        };
        if self.props.mathml {
            render.set_output_format(&OutputType::Mathml);
        }
        let t = yew::utils::document().create_element("span").unwrap();
        t.set_inner_html(&render.render(&self.props.math));
        Html::VRef(t.into())
    }
}