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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

mod parser;
mod render;

use std::rc::Rc;

use wasm_bindgen::prelude::*;

pub use crate::parser::*;
pub use crate::render::*;

#[inline]
fn to_html(
    input: &str,
    parser_options: &mrml::prelude::parser::ParserOptions,
    render_options: &mrml::prelude::render::RenderOptions,
) -> Result<String, ToHtmlError> {
    let element = mrml::parse_with_options(input, parser_options)?;
    let html = element.render(render_options)?;
    Ok(html)
}

#[cfg(feature = "async")]
#[inline]
async fn to_html_async(
    input: &str,
    parser_options: std::rc::Rc<mrml::prelude::parser::AsyncParserOptions>,
    render_options: &mrml::prelude::render::RenderOptions,
) -> Result<String, ToHtmlError> {
    let element = mrml::async_parse_with_options(input, parser_options).await?;
    let html = element.render(render_options)?;
    Ok(html)
}

#[derive(Debug, Default)]
#[wasm_bindgen]
pub struct Engine {
    parser: Rc<mrml::prelude::parser::ParserOptions>,
    #[cfg(feature = "async")]
    async_parser: Rc<mrml::prelude::parser::AsyncParserOptions>,
    render: mrml::prelude::render::RenderOptions,
}

#[wasm_bindgen]
impl Engine {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Self {
        Self::default()
    }

    /// Defines the parsing options.
    #[allow(clippy::arc_with_non_send_sync)]
    #[wasm_bindgen(js_name = "setParserOptions")]
    pub fn set_parser_options(&mut self, value: ParserOptions) {
        self.parser = Rc::new(value.into());
    }

    /// Defines the async parsing options.
    #[cfg(feature = "async")]
    #[allow(clippy::arc_with_non_send_sync)]
    #[wasm_bindgen(js_name = "setAsyncParserOptions")]
    pub fn set_async_parser_options(&mut self, value: AsyncParserOptions) {
        self.async_parser = Rc::new(value.into());
    }

    /// Defines the rendering options.
    #[wasm_bindgen(js_name = "setRenderOptions")]
    pub fn set_render_options(&mut self, value: RenderOptions) {
        self.render = value.into();
    }

    /// Renders the mjml input into html.
    #[wasm_bindgen(js_name = "toHtml")]
    pub fn to_html(&self, input: &str) -> ToHtmlResult {
        match to_html(input, &self.parser, &self.render) {
            Ok(content) => ToHtmlResult::Success { content },
            Err(error) => ToHtmlResult::Error(error),
        }
    }

    /// Renders the mjml input into html.
    #[cfg(feature = "async")]
    #[wasm_bindgen(js_name = "toHtmlAsync")]
    pub async fn to_html_async(&self, input: &str) -> ToHtmlResult {
        match to_html_async(input, self.async_parser.clone(), &self.render).await {
            Ok(content) => ToHtmlResult::Success { content },
            Err(error) => ToHtmlResult::Error(error),
        }
    }
}

#[derive(Debug, serde::Deserialize, serde::Serialize, tsify::Tsify)]
#[serde(rename_all = "camelCase", tag = "origin")]
#[tsify(into_wasm_abi)]
pub enum ToHtmlError {
    Parser { message: String },
    Render { message: String },
}

impl From<mrml::prelude::parser::Error> for ToHtmlError {
    fn from(value: mrml::prelude::parser::Error) -> Self {
        ToHtmlError::Parser {
            message: value.to_string(),
        }
    }
}

impl From<mrml::prelude::render::Error> for ToHtmlError {
    fn from(value: mrml::prelude::render::Error) -> Self {
        ToHtmlError::Render {
            message: value.to_string(),
        }
    }
}

#[derive(Debug, serde::Serialize, tsify::Tsify)]
#[serde(rename_all = "camelCase", tag = "type")]
#[tsify(into_wasm_abi)]
pub enum ToHtmlResult {
    Success { content: String },
    Error(ToHtmlError),
}

impl ToHtmlResult {
    pub fn into_success(self) -> String {
        match self {
            Self::Success { content } => content,
            Self::Error(inner) => panic!("unexpected error {:?}", inner),
        }
    }
}

impl From<ToHtmlResult> for JsValue {
    fn from(value: ToHtmlResult) -> Self {
        serde_wasm_bindgen::to_value(&value).unwrap()
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::iter::FromIterator;

    use wasm_bindgen_test::wasm_bindgen_test;

    use crate::{Engine, ToHtmlResult};

    #[wasm_bindgen_test]
    fn it_should_render() {
        let template = "<mjml><mj-body><mj-text>Hello World</mj-text></mj-body></mjml>";
        let opts = Engine::new();
        let result = opts.to_html(template);
        assert!(matches!(result, ToHtmlResult::Success { .. }));
    }

    #[wasm_bindgen_test]
    fn it_should_error() {
        let template = "<mjml><mj-body><mj-text>Hello World";
        let opts = Engine::new();
        let result = opts.to_html(template);
        assert!(matches!(result, ToHtmlResult::Error(_)));
    }

    #[wasm_bindgen_test]
    fn it_should_render_with_include() {
        let template = "<mjml><mj-body><mj-include path=\"/hello-world.mjml\" /></mj-body></mjml>";
        let mut opts = Engine::new();
        opts.set_parser_options(crate::ParserOptions {
            include_loader: crate::parser::IncludeLoaderOptions::Memory(
                crate::parser::MemoryIncludeLoaderOptions {
                    content: HashMap::from_iter([(
                        "/hello-world.mjml".to_string(),
                        "<mj-text>Hello World</mj-text>".to_string(),
                    )]),
                },
            ),
        });
        let result = opts.to_html(template);
        assert!(matches!(result, ToHtmlResult::Success { .. }));
    }
}

#[cfg(all(test, feature = "async"))]
mod async_tests {
    use std::collections::HashMap;
    use std::iter::FromIterator;

    use wasm_bindgen_test::wasm_bindgen_test;

    use crate::{Engine, ToHtmlResult};

    #[wasm_bindgen_test]
    async fn it_should_render() {
        let template = "<mjml><mj-body><mj-text>Hello World</mj-text></mj-body></mjml>";
        let opts = Engine::new();
        let result = opts.to_html_async(template).await;
        assert!(matches!(result, ToHtmlResult::Success { .. }));
    }

    #[wasm_bindgen_test]
    async fn it_should_error() {
        let template = "<mjml><mj-body><mj-text>Hello World";
        let opts = Engine::new();
        let result = opts.to_html_async(template).await;
        assert!(matches!(result, ToHtmlResult::Error(_)));
    }

    #[wasm_bindgen_test]
    async fn it_should_render_with_include() {
        let template = "<mjml><mj-body><mj-include path=\"/hello-world.mjml\" /></mj-body></mjml>";
        let mut opts = Engine::new();
        opts.set_async_parser_options(crate::AsyncParserOptions {
            include_loader: crate::parser::AsyncIncludeLoaderOptions::Memory(
                crate::parser::MemoryIncludeLoaderOptions {
                    content: HashMap::from_iter([(
                        "/hello-world.mjml".to_string(),
                        "<mj-text>Hello World</mj-text>".to_string(),
                    )]),
                },
            ),
        });
        let result = opts.to_html_async(template).await;
        assert!(matches!(result, ToHtmlResult::Success { .. }));
    }
}