flav_md_engine/
lib.rs

1//! This is rust implementation of [flav-md](https://github.com/jiko21/flav-md)
2//!
3//! You can parse markdown docs to styled html.
4//!
5use crate::lexer::lexer::lexer::Lexer;
6extern crate wasm_bindgen;
7use wasm_bindgen::prelude::*;
8
9mod lexer;
10mod util;
11
12#[cfg(feature = "wee_alloc")]
13#[global_allocator]
14static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
15
16/// Struct for flav md engine
17#[wasm_bindgen]
18pub struct FlavMd {
19    /// Rendered html by flav md engine
20    html_text: String,
21    /// Style for flav md docs
22    ///
23    /// This param is  passed by [`FlavMd::build`]
24    css_text: String,
25}
26
27/// impl for flav md engine
28#[wasm_bindgen]
29impl FlavMd {
30    /// Generate new flav md engine instance.
31    ///
32    /// In rust (not WebAssembly), using this function is recommended.
33    #[wasm_bindgen(constructor)]
34    pub fn new() -> Self {
35        FlavMd {
36            html_text: "".to_string(),
37            css_text: "".to_string(),
38        }
39    }
40
41    /// Build html text with given markdown and css.
42    pub fn build(&mut self, md_text: String, css_text: String) -> String {
43        let lexer = Lexer::new(md_text.split("\n").map(|s| s.to_string()).collect());
44        self.html_text = lexer.parse().to_html_string();
45        self.css_text = css_text;
46        format!("<style>{}</style>\n{}", self.css_text, self.html_text)
47    }
48}
49
50/// Generate flav md instance
51///
52/// This is mainly for WebAssembly, so if you use in rust project,
53/// consider using [`FlavMd::new()`]
54///
55/// # example
56///
57/// ```
58/// use flav_md_engine::create_flav_md;
59///
60/// let md_text = "# sample".to_string();
61/// let css_text = r#"..flav-md-h1 {
62///     color: red
63/// }"#.to_string();
64///
65/// create_flav_md()
66///     .build(md_text, css_text);
67/// ```
68#[wasm_bindgen]
69pub fn create_flav_md() -> FlavMd {
70    FlavMd::new()
71}
72
73#[cfg(test)]
74mod test {
75    use crate::create_flav_md;
76
77    #[test]
78    fn correctly_build_file() {
79        let html_text = "<h1 class=\"flav-md-text flav-md-h1 flav-md-h\">sample</h1>".to_string();
80        let css_text = r#".flav-md-h1 {
81  color: red;
82}"#
83        .to_string();
84        let expected = format!("<style>{}</style>\n{}", css_text, html_text);
85        let actual = create_flav_md().build("# sample".to_string(), css_text);
86        assert_eq!(actual, expected);
87    }
88}