chart_js_rs/
lib.rs

1#![allow(non_snake_case)]
2#![doc = include_str!("../README.md")]
3
4pub mod bar;
5pub mod coordinate;
6pub mod doughnut;
7pub mod exports;
8pub mod functions;
9pub mod objects;
10pub mod pie;
11pub mod scatter;
12pub mod traits;
13
14#[doc(hidden)]
15mod utils;
16
17use exports::get_chart;
18use gloo_utils::format::JsValueSerdeExt;
19pub use objects::*;
20use serde::{de::DeserializeOwned, Serialize};
21pub use traits::*;
22pub use utils::*;
23
24pub trait ChartExt<A: Annotation + DeserializeOwned>:
25    DeserializeOwned + Serialize + Default
26{
27    type DS;
28
29    fn new(id: impl AsRef<str>) -> Self {
30        Self::default().id(id.as_ref().into())
31    }
32
33    fn get_id(self) -> String;
34    fn id(self, id: String) -> Self;
35
36    fn get_data(&mut self) -> &mut Self::DS;
37    fn data(mut self, data: impl Into<Self::DS>) -> Self {
38        *self.get_data() = data.into();
39        self
40    }
41
42    fn get_options(&mut self) -> &mut ChartOptions<A>;
43    fn options(mut self, options: impl Into<ChartOptions<A>>) -> Self {
44        *self.get_options() = options.into();
45        self
46    }
47
48    fn into_chart(self) -> Chart {
49        Chart {
50            obj: <::wasm_bindgen::JsValue as JsValueSerdeExt>::from_serde(&self)
51                .expect("Unable to serialize chart."),
52            id: self.get_id(),
53            mutate: false,
54            plugins: String::new(),
55            defaults: String::new(),
56        }
57    }
58
59    fn get_chart_from_id(id: &str) -> Option<Self> {
60        let chart = get_chart(id);
61
62        serde_wasm_bindgen::from_value(chart)
63            .inspect_err(|e| {
64                gloo_console::error!(e.to_string());
65            })
66            .ok()
67    }
68}