use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn init_panic_hook() {
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}
#[wasm_bindgen]
pub struct MeCrabWasm {
overlay: crate::dict::OverlayDictionary,
initialized: bool,
}
#[wasm_bindgen]
impl MeCrabWasm {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
Self {
overlay: crate::dict::OverlayDictionary::new(),
initialized: false,
}
}
#[wasm_bindgen(js_name = addWord)]
pub fn add_word(&self, surface: &str, reading: &str, pronunciation: &str, wcost: i16) {
self.overlay
.add_simple(surface, reading, pronunciation, wcost);
}
#[wasm_bindgen(js_name = removeWord)]
pub fn remove_word(&self, surface: &str) -> bool {
self.overlay.remove_word(surface)
}
#[wasm_bindgen(js_name = overlaySize)]
pub fn overlay_size(&self) -> usize {
self.overlay.len()
}
#[wasm_bindgen(js_name = isInitialized)]
pub fn is_initialized(&self) -> bool {
self.initialized
}
#[wasm_bindgen(js_name = getOverlaySurfaces)]
pub fn get_overlay_surfaces(&self) -> String {
let surfaces = self.overlay.surfaces();
format!(
"[{}]",
surfaces
.iter()
.map(|s| format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")))
.collect::<Vec<_>>()
.join(",")
)
}
}
impl Default for MeCrabWasm {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen]
pub fn version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[wasm_bindgen]
pub fn features() -> String {
let features = ["wasm"];
format!(
"[{}]",
features
.iter()
.map(|f| format!("\"{}\"", f))
.collect::<Vec<_>>()
.join(",")
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_wasm_overlay() {
let mecrab = MeCrabWasm::new();
mecrab.add_word("テスト", "テスト", "テスト", 5000);
assert_eq!(mecrab.overlay_size(), 1);
assert!(mecrab.remove_word("テスト"));
assert_eq!(mecrab.overlay_size(), 0);
}
}