Skip to content

Commit

Permalink
Support arrays ([impl ViewSequence; N]) as ViewSequences
Browse files Browse the repository at this point in the history
Adds the blanket impl
`impl<const N: usize, VT: ViewSequence> ViewSequence for [VT; N]`

Allows for example something like this:

```rust
fn my_tab(impl View) -> impl View {..}
h_stack(["Tab 1", "Tab 2", "Tab 3"].map(my_tab))
```
  • Loading branch information
Philipp-M committed Feb 16, 2024
1 parent 9db9497 commit e82ddf5
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 5 deletions.
45 changes: 45 additions & 0 deletions crates/xilem_core/src/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,51 @@ macro_rules! generate_viewsequence_trait {
}
}

impl<T, A, const N: usize, VT: $viewseq<T, A>> $viewseq<T, A> for [VT; N] {
type State = [VT::State; N];

fn build(&self, cx: &mut Cx, elements: &mut Vec<$pod>) -> Self::State {
self.each_ref().map(|vs| vs.build(cx, elements))
}

fn rebuild(
&self,
cx: &mut $cx,
prev: &Self,
state: &mut Self::State,
elements: &mut $crate::VecSplice<$pod>,
) -> $changeflags {
self.iter()
.enumerate()
.map(|(i, vs)| vs.rebuild(cx, &prev[i], &mut state[i], elements))
.fold(ChangeFlags::empty(), |changes_acc, changes| {
changes_acc | changes
})
}

fn message(
&self,
id_path: &[Id],
state: &mut Self::State,
message: Box<dyn std::any::Any>,
app_state: &mut T,
) -> $crate::MessageResult<A> {
let mut result = $crate::MessageResult::Stale(message);
for (child, child_state) in self.iter().zip(state) {
if let $crate::MessageResult::Stale(message) = result {
result = child.message(id_path, child_state, message, app_state);
} else {
break;
}
}
result
}

fn count(&self, _state: &Self::State) -> usize {
N
}
}

/// This trait marks a type a
#[doc = concat!(stringify!($view), ".")]
///
Expand Down
10 changes: 5 additions & 5 deletions examples/hello.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ fn app_logic(data: &mut AppData) -> impl View<AppData> {
println!("clicked");
data.count += 1;
}),
h_stack((
h_stack([
button("decrease", |data: &mut AppData| {
println!("clicked decrease");
data.count -= 1;
Expand All @@ -25,10 +25,10 @@ fn app_logic(data: &mut AppData) -> impl View<AppData> {
println!("clicked reset");
data.count = 0;
}),
switch(data.is_on, |data: &mut AppData, value: bool| {
data.is_on = value
}),
)),
]),
switch(data.is_on, |data: &mut AppData, value: bool| {
data.is_on = value
}),
))
.with_spacing(20.0)
}
Expand Down

0 comments on commit e82ddf5

Please sign in to comment.