use crate::protocol::{PropMap, PropValue, TreeNode};
pub struct WidgetBuilder {
pub id: String,
pub type_name: &'static str,
pub props: PropMap,
pub children: Vec<TreeNode>,
}
impl WidgetBuilder {
pub fn new(type_name: &'static str, id: &str) -> Self {
Self {
id: id.to_string(),
type_name,
props: PropMap::new(),
children: Vec::new(),
}
}
pub fn prop(mut self, key: &str, value: impl Into<PropValue>) -> Self {
self.props.insert(key, value.into());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_builder() {
let b = WidgetBuilder::new("star_rating", "stars");
assert_eq!(b.id, "stars");
assert_eq!(b.type_name, "star_rating");
assert!(b.props.is_empty());
}
#[test]
fn prop_chaining() {
let b = WidgetBuilder::new("gauge", "g1")
.prop("value", 0.5f64)
.prop("label", "Speed");
assert_eq!(b.props.len(), 2);
assert_eq!(b.props.get("value").unwrap().as_f64(), Some(0.5));
assert_eq!(b.props.get("label").unwrap().as_str(), Some("Speed"));
}
#[test]
fn prop_overwrites() {
let b = WidgetBuilder::new("test", "t1")
.prop("x", 1.0f64)
.prop("x", 2.0f64);
assert_eq!(b.props.len(), 1);
assert_eq!(b.props.get("x").unwrap().as_f64(), Some(2.0));
}
}