logo
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
use std::{
    cell::{Ref, RefCell, RefMut},
    fmt::{Debug, Formatter},
    rc::Rc,
};
use std::sync::Arc;

use dioxus::prelude::*;
use dioxus_elements::{div, GlobalAttributes};

use katex_wasmbind::KaTeXOptions;

pub mod builder;

/// A hook which keeping the context of KaTeX formula.
pub struct UseKatex {
    katex: Rc<RefCell<KaTeXOptions>>,
    updater: Arc<dyn Fn() + 'static>,
}

impl UseKatex {
    /// Get all config of KaTeX formula.
    pub fn get_config(&self) -> Ref<'_, KaTeXOptions> {
        self.katex.borrow()
    }
    /// Get the mutable reference of all config.
    pub fn get_config_mut(&self) -> RefMut<'_, KaTeXOptions> {
        self.katex.borrow_mut()
    }
    /// Set the formula to inline mode.
    pub fn set_inline_mode(&self) {
        self.get_config_mut().display_mode = false;
        self.needs_update();
    }
    /// Set the formula to display mode.
    pub fn set_display_mode(&self) {
        self.get_config_mut().display_mode = true;
        self.needs_update();
    }
    /// Notify the scheduler to re-render the component.
    pub fn needs_update(&self) {
        (self.updater)();
    }
}

impl UseKatex {
    /// Compile the formula to HTML.
    ///
    /// Never fails even if the formula is invalid.
    pub fn compile(&self, input: &str) -> LazyNodes {
        let config = self.katex.borrow_mut();
        let out = config.render(input);
        LazyNodes::new(move |cx: NodeFactory| -> VNode {
            cx.element(
                div,
                &[],
                cx.bump().alloc([div.dangerous_inner_html(cx, format_args!("{out}", out = out))]),
                &[],
                None,
            )
        })
    }
}