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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use std::cell::RefCell;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::marker::PhantomData;
use stdweb::web::{Element, EventListenerHandle, INode, Node};
use stdweb::web::html_element::SelectElement;
use virtual_dom::{Listener, VDiff, VNode};
use callback::Callback;
use scheduler::{Scheduler, Runnable, BoxedRunnable};
use {Shared, Hidden};
pub type ShouldRender = bool;
pub trait Component<CTX>: Sized + 'static {
type Message: 'static;
type Properties: Clone + PartialEq + Default;
fn create(props: Self::Properties, context: &mut Env<CTX, Self>) -> Self;
fn update(&mut self, msg: Self::Message, context: &mut Env<CTX, Self>) -> ShouldRender;
fn change(&mut self, _: Self::Properties, _context: &mut Env<CTX, Self>) -> ShouldRender {
unimplemented!("you should implement `change` method for a component with properties")
}
fn destroy(&mut self, _context: &mut Env<CTX, Self>) { }
}
pub trait Renderable<CTX, COMP: Component<CTX>> {
fn view(&self) -> Html<CTX, COMP>;
}
pub(crate) enum ComponentUpdate<CTX, COMP: Component<CTX>> {
Create,
Message(COMP::Message),
Properties(COMP::Properties),
Destroy,
}
pub struct Env<'a, CTX: 'a, COMP: Component<CTX>> {
context: &'a mut CTX,
activator: &'a mut Activator<CTX, COMP>,
}
impl<'a, CTX: 'a, COMP: Component<CTX>> Deref for Env<'a, CTX, COMP> {
type Target = CTX;
fn deref(&self) -> &CTX {
&self.context
}
}
impl<'a, CTX: 'a, COMP: Component<CTX>> DerefMut for Env<'a, CTX, COMP> {
fn deref_mut(&mut self) -> &mut CTX {
&mut self.context
}
}
impl<'a, CTX: 'static, COMP: Component<CTX>> Env<'a, CTX, COMP> {
pub fn send_back<F, IN>(&mut self, function: F) -> Callback<IN>
where
F: Fn(IN) -> COMP::Message + 'static,
{
let activator = self.activator.clone();
let closure = move |input| {
let output = function(input);
activator.clone().send_message(output);
};
closure.into()
}
}
pub struct Activator<CTX, COMP: Component<CTX>> {
runnable: Shared<Option<Shared<BoxedRunnable<CTX>>>>,
scheduler: Scheduler<CTX>,
_comp: PhantomData<COMP>,
}
impl<CTX, COMP: Component<CTX>> Clone for Activator<CTX, COMP> {
fn clone(&self) -> Self {
Activator {
runnable: self.runnable.clone(),
scheduler: self.scheduler.clone(),
_comp: PhantomData,
}
}
}
impl<CTX, COMP: Component<CTX>> Activator<CTX, COMP> {
pub(crate) fn send(&mut self, update: ComponentUpdate<CTX, COMP>) {
let msg = Box::into_raw(Box::new(update)) as *mut Hidden;
let runnable = self.runnable.borrow().as_ref()
.cloned()
.expect("runnable was not set");
self.scheduler.put_and_try_run((runnable, msg));
}
pub fn send_message(&mut self, message: COMP::Message) {
let update = ComponentUpdate::Message(message);
self.send(update);
}
pub fn scheduler(&self) -> Scheduler<CTX> {
self.scheduler.clone()
}
}
pub(crate) struct Scope<CTX, COMP: Component<CTX>> {
env: Activator<CTX, COMP>,
}
pub type NodeCell = Rc<RefCell<Option<Node>>>;
impl<CTX, COMP> Scope<CTX, COMP>
where
CTX: 'static,
COMP: Component<CTX> + Renderable<CTX, COMP>,
{
pub(crate) fn new(scheduler: Scheduler<CTX>) -> Self {
let runnable = Rc::new(RefCell::new(None));
let _comp = PhantomData;
let env = Activator { runnable, scheduler, _comp };
Scope { env }
}
pub(crate) fn activator(&self) -> Activator<CTX, COMP> {
self.env.clone()
}
pub fn mount_in_place(
self,
element: Element,
ancestor: Option<VNode<CTX, COMP>>,
occupied: Option<NodeCell>,
init_props: Option<COMP::Properties>,
) -> Activator<CTX, COMP> {
let runnable = ScopeRunnable {
env: self.env.clone(),
component: None,
last_frame: None,
element,
ancestor,
occupied,
init_props,
destroyed: false,
};
let mut activator = self.env.clone();
let runnable = Box::new(runnable) as BoxedRunnable<CTX>;
let runnable = Rc::new(RefCell::new(runnable));
*activator.runnable.borrow_mut() = Some(runnable);
activator.send(ComponentUpdate::Create);
activator
}
}
struct ScopeRunnable<CTX, COMP: Component<CTX>> {
env: Activator<CTX, COMP>,
component: Option<COMP>,
last_frame: Option<VNode<CTX, COMP>>,
element: Element,
ancestor: Option<VNode<CTX, COMP>>,
occupied: Option<NodeCell>,
init_props: Option<COMP::Properties>,
destroyed: bool,
}
impl<CTX, COMP> Runnable<CTX> for ScopeRunnable<CTX, COMP>
where
CTX: 'static,
COMP: Component<CTX> + Renderable<CTX, COMP>,
{
fn run<'a>(&mut self, context: &'a mut CTX, msg: *mut Hidden) {
if self.destroyed {
return;
}
let mut should_update = false;
let upd = unsafe { *Box::from_raw(msg as *mut ComponentUpdate<CTX, COMP>) };
let env = self.env.clone();
let mut context = Env {
context: context,
activator: &mut self.env,
};
match upd {
ComponentUpdate::Create => {
let props = self.init_props.take().unwrap_or_default();
self.component = Some(COMP::create(props, &mut context));
let current_frame = self.component.as_ref().unwrap().view();
self.last_frame = Some(current_frame);
let node = self.last_frame.as_mut()
.unwrap()
.apply(self.element.as_node(), None, self.ancestor.take(), &env);
if let Some(ref mut cell) = self.occupied {
*cell.borrow_mut() = node;
}
}
ComponentUpdate::Message(msg) => {
should_update |= self.component.as_mut().unwrap().update(msg, &mut context);
}
ComponentUpdate::Properties(props) => {
should_update |= self.component.as_mut().unwrap().change(props, &mut context);
}
ComponentUpdate::Destroy => {
self.component.as_mut().unwrap().destroy(&mut context);
self.destroyed = true;
}
}
if should_update {
let mut next_frame = self.component.as_ref().unwrap().view();
let node =
next_frame.apply(self.element.as_node(), None, self.last_frame.take(), &env);
if let Some(ref mut cell) = self.occupied {
*cell.borrow_mut() = node;
}
self.last_frame = Some(next_frame);
}
}
}
pub type Html<CTX, MSG> = VNode<CTX, MSG>;
macro_rules! impl_action {
($($action:ident($event:ident : $type:ident) -> $ret:ty => $convert:expr)*) => {$(
pub mod $action {
use stdweb::web::{IEventTarget, Element};
use stdweb::web::event::{IEvent, $type};
use super::*;
pub struct Wrapper<F>(Option<F>);
pub type Event = $ret;
impl<F, MSG> From<F> for Wrapper<F>
where
MSG: 'static,
F: Fn($ret) -> MSG + 'static,
{
fn from(handler: F) -> Self {
Wrapper(Some(handler))
}
}
impl<T, CTX: 'static, COMP: Component<CTX>> Listener<CTX, COMP> for Wrapper<T>
where
T: Fn($ret) -> COMP::Message + 'static,
{
fn kind(&self) -> &'static str {
stringify!($action)
}
fn attach(&mut self, element: &Element, mut activator: Activator<CTX, COMP>)
-> EventListenerHandle {
let handler = self.0.take().expect("tried to attach listener twice");
let this = element.clone();
let listener = move |event: $type| {
debug!("Event handler: {}", stringify!($type));
event.stop_propagation();
let handy_event: $ret = $convert(&this, event);
let msg = handler(handy_event);
activator.send_message(msg);
};
element.add_event_listener(listener)
}
}
}
)*};
}
impl_action! {
onclick(event: ClickEvent) -> ClickEvent => |_, event| { event }
ondoubleclick(event: DoubleClickEvent) -> DoubleClickEvent => |_, event| { event }
onkeypress(event: KeyPressEvent) -> KeyPressEvent => |_, event| { event }
onkeydown(event: KeyDownEvent) -> KeyDownEvent => |_, event| { event }
onkeyup(event: KeyUpEvent) -> KeyUpEvent => |_, event| { event }
onmousemove(event: MouseMoveEvent) -> MouseMoveEvent => |_, event| { event }
onmousedown(event: MouseDownEvent) -> MouseDownEvent => |_, event| { event }
onmouseup(event: MouseUpEvent) -> MouseUpEvent => |_, event| { event }
onmouseover(event: MouseOverEvent) -> MouseOverEvent => |_, event| { event }
onmouseout(event: MouseOutEvent) -> MouseOutEvent => |_, event| { event }
onblur(event: BlurEvent) -> BlurEvent => |_, event| { event }
oninput(event: InputEvent) -> InputData => |this: &Element, _| {
use stdweb::web::html_element::{InputElement, TextAreaElement};
use stdweb::unstable::TryInto;
let value = match this.clone().try_into() {
Ok(input) => {
let input: InputElement = input;
input.raw_value()
}
Err(_e) => {
match this.clone().try_into() {
Ok(tae) => {
let tae: TextAreaElement = tae;
tae.value()
}
Err(_e) => {
panic!("only an InputElement or TextAreaElement can have an oninput event listener");
}
}
}
};
InputData { value }
}
onchange(event: ChangeEvent) -> ChangeData => |this: &Element, _| {
use stdweb::web::html_element::{InputElement, TextAreaElement, SelectElement};
use stdweb::unstable::TryInto;
match this.node_name().as_ref() {
"INPUT" => {
let input: InputElement = this.clone().try_into().unwrap();
ChangeData::Value(input.raw_value())
}
"TEXTAREA" => {
let tae: TextAreaElement = this.clone().try_into().unwrap();
ChangeData::Value(tae.value())
}
"SELECT" => {
let se: SelectElement = this.clone().try_into().unwrap();
ChangeData::Select(se)
}
_ => {
panic!("only an InputElement, TextAreaElement or SelectElement can have an onchange event listener");
}
}
}
}
#[derive(Debug)]
pub struct InputData {
pub value: String,
}
#[derive(Debug)]
pub enum ChangeData {
Value(String),
Select(SelectElement),
}
#[derive(Debug)]
pub struct Href {
link: String,
}
impl From<String> for Href {
fn from(link: String) -> Self {
Href { link }
}
}
impl<'a> From<&'a str> for Href {
fn from(link: &'a str) -> Self {
Href {
link: link.to_owned(),
}
}
}
impl ToString for Href {
fn to_string(&self) -> String {
self.link.to_owned()
}
}