counter_list/
counter_list.rs

1use rui::*;
2
3fn main() {
4    rui(state(Counters::default, |counters, cx| {
5        vstack((
6            list(cx[counters].ids(), move |&i| {
7                with_cx(move |cx| {
8                    let count = bind(counters, CounterLens(i));
9                    hstack((
10                        format!("{}", count.get(cx)).padding(Auto),
11                        button("increment", move |cx| {
12                            *count.get_mut(cx) += 1;
13                        })
14                        .padding(Auto),
15                        button("decrement", move |cx| {
16                            *count.get_mut(cx) -= 1;
17                        })
18                        .padding(Auto),
19                        button("remove", move |cx| cx[counters].remove_counter(i)).padding(Auto),
20                    ))
21                })
22            }),
23            format!("total: {}", cx[counters].sum_counters()).padding(Auto),
24            button("add counter", move |cx| cx[counters].add_counter()).padding(Auto),
25        ))
26    }));
27}
28
29#[derive(Default, Debug)]
30struct Counters {
31    counters: Vec<Option<i32>>,
32}
33
34impl Counters {
35    fn ids(&self) -> Vec<usize> {
36        let mut ids = vec![];
37        for i in 0..self.counters.len() {
38            if let Some(_) = self.counters[i] {
39                ids.push(i);
40            }
41        }
42        ids
43    }
44    fn add_counter(&mut self) {
45        self.counters.push(Some(0));
46    }
47    fn remove_counter(&mut self, id: usize) {
48        self.counters[id] = None;
49    }
50    fn sum_counters(&self) -> i32 {
51        let mut sum = 0;
52        for c in &self.counters {
53            if let Some(x) = c {
54                sum += x
55            }
56        }
57        sum
58    }
59}
60
61#[derive(Copy, Clone, Debug)]
62struct CounterLens(usize);
63
64impl Lens<Counters, i32> for CounterLens {
65    fn focus<'a>(&self, data: &'a Counters) -> &'a i32 {
66        data.counters[self.0].as_ref().unwrap()
67    }
68
69    fn focus_mut<'a>(&self, data: &'a mut Counters) -> &'a mut i32 {
70        data.counters[self.0].as_mut().unwrap()
71    }
72}