dioxus_katex/katex/
mod.rs

1use std::{
2    cell::{Ref, RefCell, RefMut},
3    fmt::{Debug, Formatter},
4    rc::Rc,
5    sync::Arc,
6};
7
8use dioxus::prelude::*;
9use dioxus_elements::GlobalAttributes;
10
11use katex_wasmbind::KaTeXOptions;
12
13pub mod builder;
14
15/// A hook which keeping the context of KaTeX formula.
16pub struct UseKatex {
17    katex: Rc<RefCell<KaTeXOptions>>,
18    updater: Arc<dyn Fn() + 'static>,
19}
20
21impl UseKatex {
22    /// Get all config of KaTeX formula.
23    pub fn get_config(&self) -> Ref<'_, KaTeXOptions> {
24        self.katex.borrow()
25    }
26    /// Get the mutable reference of all config.
27    pub fn get_config_mut(&self) -> RefMut<'_, KaTeXOptions> {
28        self.katex.borrow_mut()
29    }
30    /// Set the formula to inline mode.
31    pub fn set_inline_mode(&self) {
32        self.get_config_mut().display_mode = false;
33        self.needs_update();
34    }
35    /// Set the formula to display mode.
36    pub fn set_display_mode(&self) {
37        self.get_config_mut().display_mode = true;
38        self.needs_update();
39    }
40    /// Notify the scheduler to re-render the component.
41    pub fn needs_update(&self) {
42        (self.updater)();
43    }
44}
45
46impl UseKatex {
47    /// Compile the formula to HTML.
48    ///
49    /// Never fails even if the formula is invalid.
50    pub fn compile(&self, input: &str) -> LazyNodes {
51        let config = self.katex.borrow_mut();
52        let out = config.render(input);
53        rsx! {
54            div {
55                dangerous_inner_html: "{out}"
56            }
57        }
58    }
59}