summaryrefslogtreecommitdiffstats
path: root/web/src/bus.rs
blob: d76466f5cbd84e2a1709a72091d43c8225f40d4a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use crate::Application;

use std::rc::Rc;

#[derive(Clone)]
pub struct Bus<Message> {
    publish: Rc<Box<dyn Fn(Message, &mut dyn dodrio::RootRender)>>,
}

impl<Message> Bus<Message>
where
    Message: 'static,
{
    pub fn new() -> Self {
        Self {
            publish: Rc::new(Box::new(|message, root| {
                let app = root.unwrap_mut::<Application<Message>>();

                app.update(message)
            })),
        }
    }

    pub fn publish(&self, message: Message, root: &mut dyn dodrio::RootRender) {
        (self.publish)(message, root);
    }

    pub fn map<B>(&self, mapper: Rc<Box<dyn Fn(B) -> Message>>) -> Bus<B>
    where
        B: 'static,
    {
        let publish = self.publish.clone();

        Bus {
            publish: Rc::new(Box::new(move |message, root| {
                publish(mapper(message), root)
            })),
        }
    }
}