Skip to content

Commit

Permalink
Allow using numeric types directly
Browse files Browse the repository at this point in the history
  • Loading branch information
kmicklas committed Aug 20, 2024
1 parent e785990 commit 729728a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
8 changes: 7 additions & 1 deletion examples/tutorial/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@ fn state(model: &Model) -> View!(Model, '_) {
// number, it is easier and more efficient to use [`display`].
display(model.count),
)),
el::p((
"Also count: ",
// In fact, if the value is a standard number type, then we can just
// use it directly.
model.count,
)),
el::p((
"Message: ",
// Previously, we only genereted static strings, which can be used
Expand Down Expand Up @@ -131,7 +137,7 @@ fn local_state() -> View!(Model) {
/// other component in our application), we can no longer call it
/// directly here.
fn display_counter(count: usize) -> View!(Model) {
el::p(("Local count: ", display(count)))
el::p(("Local count: ", count))
}

cx.build((
Expand Down
42 changes: 42 additions & 0 deletions ravel-web/src/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,48 @@ impl Builder<Web> for &'static str {
}
}

macro_rules! make_builder_web_to_string {
($t:ty) => {
impl Builder<Web> for $t {
type State = TextState<Self>;

fn build(self, cx: BuildCx) -> Self::State {
let data = self.to_string();

let node = web_sys::Text::new_with_data(&data).unwrap_throw();
cx.position.insert(&node);

TextState { node, value: self }
}

fn rebuild(self, _: RebuildCx, state: &mut Self::State) {
if self == state.value {
return;
}

state.node.set_data(&self.to_string());
state.value = self.clone();
}
}
};
}

make_builder_web_to_string!(char);
make_builder_web_to_string!(f32);
make_builder_web_to_string!(f64);
make_builder_web_to_string!(i128);
make_builder_web_to_string!(i16);
make_builder_web_to_string!(i32);
make_builder_web_to_string!(i64);
make_builder_web_to_string!(i8);
make_builder_web_to_string!(isize);
make_builder_web_to_string!(u128);
make_builder_web_to_string!(u16);
make_builder_web_to_string!(u32);
make_builder_web_to_string!(u64);
make_builder_web_to_string!(u8);
make_builder_web_to_string!(usize);

/// Displays a value, updating when not equal to the previous value.
pub struct Display<T: ToString + PartialEq + Clone> {
value: T,
Expand Down

0 comments on commit 729728a

Please sign in to comment.