Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rationalize macro helper, add support for tick cb's #21

Merged
merged 8 commits into from
Apr 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "chart-js-rs"
version = "0.0.19"
version = "0.0.20"
edition = "2021"
authors = ["Billy Sheppard", "Luis Moreno"]
license = "Apache-2.0"
Expand Down
8 changes: 6 additions & 2 deletions examples/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use chart_js_rs::{
bar::Bar, doughnut::Doughnut, pie::Pie, scatter::Scatter, utils::FnWithArgs, ChartExt,
ChartOptions, ChartScale, Dataset, DatasetDataExt, NoAnnotations, Segment, SinglePointDataset,
XYDataset, XYPoint,
ChartOptions, ChartScale, Dataset, DatasetDataExt, NoAnnotations, ScaleTicks, Segment,
SinglePointDataset, XYDataset, XYPoint,
};
use dominator::{events, html, Dom};
use futures_signals::signal::{Mutable, MutableSignalCloned, Signal, SignalExt};
Expand Down Expand Up @@ -201,6 +201,10 @@ impl Model {
"x".into(),
ChartScale {
r#type: "linear".into(),
ticks: ScaleTicks {
callback: FnWithArgs::new().arg("value").arg("index").body("index % 2 === 0 ? this.getLabelForValue(value) : ''"),
..Default::default()
}.into(),
..Default::default()
},
)])),
Expand Down
4 changes: 4 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,7 @@ impl DatasetDataExt for BTreeSet<XYPoint> {}

pub type MinMaxPoint = [NumberOrDateString; 2];
impl DatasetDataExt for BTreeSet<MinMaxPoint> {}

impl<K, V> DatasetDataExt for BTreeMap<K, V>
where
K: Display + Serialize,
Expand Down Expand Up @@ -893,6 +894,9 @@ pub struct ScaleTicks {
#[serde(skip_serializing_if = "NumberString::is_empty", default)]
pub precision: NumberString,

#[serde(skip_serializing_if = "FnWithArgs::is_empty", default)]
pub callback: FnWithArgs,

#[serde(skip_serializing_if = "Option::is_none")]
pub padding: Option<Padding>,
}
Expand Down
91 changes: 53 additions & 38 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
use js_sys::{Array, Function, Reflect};
use js_sys::{Array, Function, Object, Reflect};
use serde::{Deserialize, Serialize};
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};

use crate::{render_chart, update_chart};

/// Macro to make it easier to rationalize the chart options
///
/// Pass the owning object, and the path to the FnWithArgs
macro_rules! rationalize {
($set:ident, $name:expr) => {
let s = $name.split('.').collect::<Vec<&str>>();
if let Ok(a) = Reflect::get(&$set, &s[0].into()) {
// If the property is undefined, dont try serialize it
if a == JsValue::UNDEFINED {
return;
}

if let Ok(b) = Reflect::get(&a, &s[1].into()) {
Reflect::set(
&a,
&s[1].into(),
&serde_wasm_bindgen::from_value::<FnWithArgs>(b)
.unwrap()
.build(),
)
.unwrap();
}
}
};
}

#[wasm_bindgen]
pub struct Chart(pub(crate) JsValue, pub(crate) String);

Expand All @@ -26,6 +52,19 @@ fn get_path(j: &JsValue, item: &str) -> Option<JsValue> {
Some(k)
}

/// Get values of an object as an array at the given path.
/// See get_path()
fn object_values_at(j: &JsValue, item: &str) -> Option<Array> {
let o = get_path(j, item);
o.and_then(|o| {
if o == JsValue::UNDEFINED {
return None;
} else {
return Some(Object::values(&o.dyn_into().unwrap()));
}
})
}

impl Chart {
pub fn new(v: JsValue, id: String) -> Option<Self> {
v.is_object().then_some(Self(v, id))
Expand All @@ -42,47 +81,23 @@ impl Chart {
update_chart(self.0, &self.1, animate)
}

/// Converts the string-serialized segment functions to a JavaScript function
/// then updates the chart options in the Js representation opf the chart
/// Converts serialized FnWithArgs to JS Function's
/// For new chart options, this will need to be updated
pub fn rationalise_js(&self) {
// Handle data.datasets
Array::from(&get_path(&self.0, "data.datasets").unwrap())
.iter()
.for_each(|dataset| {
let segment = Reflect::get(&dataset, &"segment".into());
if segment.is_ok() {
let segment = segment.unwrap();

let dash = Reflect::get(&segment, &"borderDash".into());
if let Ok(dash) = dash {
if dash == JsValue::UNDEFINED {
return;
}
Reflect::set(
&segment,
&"borderDash".into(),
&serde_wasm_bindgen::from_value::<FnWithArgs>(dash)
.unwrap()
.build(),
)
.unwrap();
}

let color = Reflect::get(&segment, &"borderColor".into());
if let Ok(color) = color {
if color == JsValue::UNDEFINED {
return;
}
Reflect::set(
&segment,
&"borderColor".into(),
&serde_wasm_bindgen::from_value::<FnWithArgs>(color)
.unwrap()
.build(),
)
.unwrap();
}
}
rationalize!(dataset, "segment.borderDash");
rationalize!(dataset, "segment.borderColor");
});

// Handle data.options.scales
object_values_at(&self.0, "options.scales").map(|scales| {
scales.iter().for_each(|scale| {
rationalize!(scale, "ticks.callback");
});
});
}
}

Expand Down
Loading