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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
use std::cell::RefCell;
use std::collections::HashSet;
use std::ops::Deref;
use std::rc::Rc;
use yew::agent::{Agent, AgentLink, Context, Discoverer, Dispatcher, HandlerId};
use yew::prelude::*;
pub trait Store: Sized + 'static {
type Input;
type Action;
fn new() -> Self;
fn handle_input(&self, link: AgentLink<StoreWrapper<Self>>, msg: Self::Input);
fn reduce(&mut self, msg: Self::Action);
}
#[derive(Debug)]
pub struct StoreWrapper<S: Store> {
pub handlers: HashSet<HandlerId>,
pub link: AgentLink<Self>,
pub state: Shared<S>,
pub self_dispatcher: Dispatcher<Self>,
}
type Shared<T> = Rc<RefCell<T>>;
#[derive(Debug)]
pub struct ReadOnly<S> {
state: Shared<S>,
}
impl<S> ReadOnly<S> {
pub fn borrow<'a>(&'a self) -> impl Deref<Target = S> + 'a {
self.state.borrow()
}
}
impl<S: Store> Agent for StoreWrapper<S> {
type Reach = Context<Self>;
type Message = S::Action;
type Input = S::Input;
type Output = ReadOnly<S>;
fn create(link: AgentLink<Self>) -> Self {
let state = Rc::new(RefCell::new(S::new()));
let handlers = HashSet::new();
let self_dispatcher = Self::dispatcher();
StoreWrapper {
handlers,
state,
link,
self_dispatcher,
}
}
fn update(&mut self, msg: Self::Message) {
{
self.state.borrow_mut().reduce(msg);
}
for handler in self.handlers.iter() {
self.link.respond(
*handler,
ReadOnly {
state: self.state.clone(),
},
);
}
}
fn connected(&mut self, id: HandlerId) {
self.handlers.insert(id);
}
fn handle_input(&mut self, msg: Self::Input, _id: HandlerId) {
self.state.borrow().handle_input(self.link.clone(), msg);
}
fn disconnected(&mut self, id: HandlerId) {
self.handlers.remove(&id);
}
}
pub trait Bridgeable: Sized + 'static {
type Wrapper: Agent;
fn bridge(
callback: Callback<<Self::Wrapper as Agent>::Output>,
) -> Box<dyn Bridge<Self::Wrapper>>;
}
impl<T> Bridgeable for T
where
T: Store,
{
type Wrapper = StoreWrapper<T>;
fn bridge(
callback: Callback<<Self::Wrapper as Agent>::Output>,
) -> Box<dyn Bridge<Self::Wrapper>> {
<Self::Wrapper as Agent>::Reach::spawn_or_join(Some(callback))
}
}