yuankunzhang / charming

A visualization library for Rust
Apache License 2.0
1.85k stars 74 forks source link

Minimal support for Events and Actions #115

Open LukaOber opened 2 weeks ago

LukaOber commented 2 weeks ago

For a project, I need to get the data index of a selected point in leptos. Echarts supports this Echarts Event and Action, but I am not familiar enough with wasm to implement this myself.

Using wasm_bindgen it should be possible to allow this functionality.

If someone could provide me with a minimal working PR, I would be able to extend the functionality.

chart.on('click', function(params) {
  console.log(params.name);
});

Code that would generate something like this, just hardcoded in the wasm_renderer.rs file, would be great.

Later on, we would need to figure out how we can support both html and wasm.

@yuankunzhang would you be able to tackle this?

LukaOber commented 2 weeks ago

Nevermind, figured it out by "stealing" some ideas from #67. I will test it out a bit and open up a minimal PR soon-ish.

Almaju commented 2 weeks ago

A hacky way to do it while waiting for the PR:

// The function to call on click
let closure = Closure::wrap(Box::new(|_| {
    info!("clicked");
}) as Box<dyn FnMut(JsValue)>);
let js_function: &js_sys::Function = closure.as_ref().unchecked_ref();

// The chart
let chart = renderer.render("chart", ...).unwrap();
let js_value: JsValue = chart.into();

// The `on` method
let on = js_sys::Reflect::get(&js_value, &"on".into())
    .expect("Object should have 'on' method")
    .dyn_into::<js_sys::Function>()
    .expect("'on' should be a function");

// The call
on.call2(&js_value, &"click".into(), js_function)
    .expect("Failed to call 'on' method");

Would be nice to have access to the on method on the bindings though. :)