use ts_function::{ts, ts_function};
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
#[ts_function]
pub type XorCallback = fn(a: js_sys::Uint8Array, b: js_sys::Uint8Array);
#[wasm_bindgen(module = "/tests/basic.js")]
extern "C" {
fn get_xor_callback() -> js_sys::Function;
fn get_xor_result() -> js_sys::Uint8Array;
}
#[wasm_bindgen_test]
fn test_example_1_primary_api() {
let js_func = get_xor_callback();
let cb = XorCallback::from(js_func);
let a_bytes: &[u8] = &[0b10101010, 0b11110000, 0b00001111];
let b_bytes: &[u8] = &[0b01010101, 0b11001100, 0b00110011];
let a = js_sys::Uint8Array::from(a_bytes);
let b = js_sys::Uint8Array::from(b_bytes);
cb.call(a, b).unwrap();
let res = get_xor_result();
let res_vec = res.to_vec();
assert_eq!(res_vec, vec![0b11111111, 0b00111100, 0b00111100]);
}
pub struct SafeCallback(pub ::js_sys::Function);
#[ts_function]
impl SafeCallback {
pub fn call(&self, val: f64) {
let result = self.0.call1(
&::wasm_bindgen::JsValue::NULL,
&::wasm_bindgen::JsValue::from_f64(val),
);
if let Err(e) = result {
if let Ok(err_obj) = e.dyn_into::<js_sys::Error>() {
set_handled_error(err_obj.message().into());
}
}
}
}
#[wasm_bindgen(module = "/tests/basic.js")]
extern "C" {
fn get_throwing_callback() -> js_sys::Function;
fn get_handled_error() -> String;
fn set_handled_error(err: String);
}
#[wasm_bindgen_test]
fn test_example_2_escape_hatch() {
set_handled_error("".to_string());
let js_func = get_throwing_callback();
let cb = SafeCallback::from(js_func);
cb.call(42.0);
assert_eq!(get_handled_error(), "JS error with value 42");
}
#[ts_function]
pub type SimpleCb = fn(msg: String);
#[ts]
struct MyCallbacks {
on_event: SimpleCb,
}
#[wasm_bindgen(module = "/tests/basic.js")]
extern "C" {
fn get_simple_cb() -> js_sys::Function;
fn get_state_msg() -> String;
}
#[wasm_bindgen_test]
fn test_example_3_ts_macro_struct() {
let raw_js_obj = js_sys::Object::new();
js_sys::Reflect::set(&raw_js_obj, &"onEvent".into(), &get_simple_cb()).unwrap();
let icallbacks = IMyCallbacks::from(JsValue::from(raw_js_obj));
let callbacks: MyCallbacks = icallbacks.parse();
callbacks
.on_event
.call("Hello from ts_macro!".to_string())
.unwrap();
assert_eq!(get_state_msg(), "Hello from ts_macro!");
}