dioxus_prism/prism/
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 prism_wasmbind::PrismLanguage;
10
11use crate::PrismOptions;
12
13pub mod builder;
14
15/// A hook which keeping the context of KaTeX formula.
16pub struct UsePrism {
17    prism: Rc<RefCell<PrismOptions>>,
18    updater: Arc<dyn Fn() + 'static>,
19}
20
21impl UsePrism {
22    /// Get all config of KaTeX formula.
23    pub fn get_config(&self) -> Ref<'_, PrismOptions> {
24        self.prism.borrow()
25    }
26    /// Get all config of KaTeX formula.
27    pub fn get_language(&self) -> String {
28        self.get_config().language.to_string()
29    }
30    /// Get all config of KaTeX formula.
31    pub fn set_language(&self, language: &str) {
32        self.get_config_mut().language = match language {
33            "javascript" => PrismLanguage::JavaScript,
34            "rust" => PrismLanguage::Rust,
35            "html" | "markup" => PrismLanguage::HTML,
36            "css" => PrismLanguage::Css,
37            _ => return,
38        };
39        self.needs_update()
40    }
41    /// Get the mutable reference of all config.
42    pub fn get_config_mut(&self) -> RefMut<'_, PrismOptions> {
43        self.prism.borrow_mut()
44    }
45    /// Notify the scheduler to re-render the component.
46    pub fn needs_update(&self) {
47        (self.updater)();
48    }
49}
50
51impl UsePrism {
52    /// Compile the formula to HTML.
53    ///
54    /// Never fails even if the formula is invalid.
55    pub fn render(&self, input: &str) -> LazyNodes {
56        let config = self.prism.borrow_mut();
57        let out = config.render(input);
58        rsx! {
59            pre {
60                dangerous_inner_html: "{out}"
61            }
62        }
63    }
64}