use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use wasm_bindgen::prelude::*;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlayheadEvent {
pub event_type: String,
pub midi: Vec<u8>,
pub time: f32,
pub velocity: f32,
pub synth_id: String,
}
type PlayheadCallback = Box<dyn Fn(PlayheadEvent)>;
thread_local! {
static PLAYHEAD_EVENTS: RefCell<Vec<PlayheadEvent>> = RefCell::new(Vec::new());
static PLAYHEAD_CALLBACK: RefCell<Option<js_sys::Function>> = RefCell::new(None);
}
pub fn push_event(event: PlayheadEvent) {
PLAYHEAD_EVENTS.with(|events| {
events.borrow_mut().push(event.clone());
});
PLAYHEAD_CALLBACK.with(|callback| {
if let Some(cb) = callback.borrow().as_ref() {
if let Ok(js_event) = serde_wasm_bindgen::to_value(&event) {
let _ = cb.call1(&JsValue::NULL, &js_event);
}
}
});
}
pub fn register_callback(callback: js_sys::Function) {
PLAYHEAD_CALLBACK.with(|cb| {
*cb.borrow_mut() = Some(callback);
});
}
pub fn unregister_callback() {
PLAYHEAD_CALLBACK.with(|cb| {
*cb.borrow_mut() = None;
});
}
pub fn get_events() -> Vec<PlayheadEvent> {
PLAYHEAD_EVENTS.with(|events| events.borrow().clone())
}
pub fn clear_events() {
PLAYHEAD_EVENTS.with(|events| {
events.borrow_mut().clear();
});
}
pub fn event_count() -> usize {
PLAYHEAD_EVENTS.with(|events| events.borrow().len())
}