chart_js_rs/
lib.rs

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