docx_handlebars/
lib.rs

1#[cfg(target_arch = "wasm32")]
2use wasm_bindgen::prelude::*;
3#[cfg(target_arch = "wasm32")]
4use wasm_bindgen::JsValue;
5
6pub mod errors;
7pub mod imagesize;
8mod template;
9pub mod utils;
10
11// 重新导出常用的类型和函数
12pub use errors::DocxError;
13pub use imagesize::get_image_dimensions;
14
15/// 当 `console_error_panic_hook` 功能启用时,我们可以调用 `set_panic_hook` 函数
16/// 至少一次在初始化过程中,以便在 panic 时获得更好的错误消息。
17pub fn set_panic_hook() {
18    #[cfg(feature = "console_error_panic_hook")]
19    console_error_panic_hook::set_once();
20}
21
22// WASM 平台:导出 WASM 兼容的渲染函数
23#[cfg(target_arch = "wasm32")]
24#[wasm_bindgen]
25pub fn render_template(
26    zip_bytes: Vec<u8>,
27    data_json: &str,
28) -> Result<JsValue, JsValue> {
29    let data: serde_json::Value = serde_json::from_str(data_json)
30            .map_err(|e| JsValue::from_str(&format!("JSON Parse Error: {e}")))?;
31
32    // 调用模板渲染函数
33    let result = template::render_template(zip_bytes, &data)
34        .map_err(|e| JsValue::from_str(&e.to_string()))?;
35
36    // 返回结果
37    Ok(JsValue::from(result))
38}
39
40// WASM 平台:导出工具函数
41#[cfg(target_arch = "wasm32")]
42#[wasm_bindgen]
43pub fn wasm_get_image_dimensions(data: Vec<u8>) -> JsValue {
44    match imagesize::get_image_dimensions(&data) {
45        Some((width, height)) => {
46            let obj = js_sys::Object::new();
47            js_sys::Reflect::set(&obj, &"width".into(), &width.into()).unwrap();
48            js_sys::Reflect::set(&obj, &"height".into(), &height.into()).unwrap();
49            obj.into()
50        }
51        None => JsValue::NULL,
52    }
53}
54
55// 非 WASM 平台:直接导出原生 Rust 函数
56#[cfg(not(target_arch = "wasm32"))]
57pub use template::render_template;