Additional WASM translation layer cleanup

This commit is contained in:
Keavon Chambers 2021-08-31 01:40:11 -07:00
parent 12585c5084
commit 8b012f9831
5 changed files with 34 additions and 74 deletions

View file

@ -1,7 +1,6 @@
pub mod document;
mod shims;
pub mod utils;
pub mod window;
pub mod wrappers;
use editor::{message_prelude::*, Editor};
@ -9,7 +8,7 @@ use std::cell::RefCell;
use utils::WasmLog;
use wasm_bindgen::prelude::*;
// the thread_local macro provides a way to initialize static variables with non-constant functions
// The thread_local macro provides a way to initialize static variables with non-constant functions
thread_local! {
pub static EDITOR_STATE: RefCell<Editor> = RefCell::new(Editor::new());
}
@ -22,24 +21,27 @@ pub fn init() {
log::set_max_level(log::LevelFilter::Debug);
}
pub fn handle_responses(responses: Vec<FrontendMessage>) {
for response in responses.into_iter() {
handle_response(response)
// Sends FrontendMessages to JavaScript
pub fn dispatch<T: Into<Message>>(message: T) {
let messages = EDITOR_STATE.with(|state| state.borrow_mut().handle_message(message.into()));
for message in messages.into_iter() {
let message_type = message.to_discriminant().local_name();
let message_data = JsValue::from_serde(&message).expect("Failed to serialize response");
let _ = handleResponse(message_type, message_data).map_err(|error| {
log::error!(
"While handling FrontendMessage \"{:?}\", JavaScript threw an error: {:?}",
message.to_discriminant().local_name(),
error
)
});
}
}
// The JavaScript function to call into
#[wasm_bindgen(module = "/../src/utilities/response-handler-binding.ts")]
extern "C" {
#[wasm_bindgen(catch)]
fn handleResponse(responseType: String, responseData: JsValue) -> Result<(), JsValue>;
}
fn handle_response(response: FrontendMessage) {
let response_type = response.to_discriminant().local_name();
send_response(response_type, response);
}
fn send_response(response_type: String, response_data: FrontendMessage) {
let response_data = JsValue::from_serde(&response_data).expect("Failed to serialize response");
let _ = handleResponse(response_type, response_data).map_err(|error| log::error!("javascript threw an error: {:?}", error));
}