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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
use crate::{
dom_types,
dom_types::{El, Namespace},
routing, util, websys_bridge,
};
use futures::{future, Future};
use std::{cell::RefCell, collections::HashMap, panic, rc::Rc};
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsValue;
use wasm_bindgen_futures::future_to_promise;
use web_sys::{Document, Element, Event, EventTarget, Window};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ShouldRender {
Render,
Skip,
}
impl Default for ShouldRender {
fn default() -> Self {
ShouldRender::Render
}
}
pub enum Effect<Ms> {
Msg(Ms),
FutureNoMsg(Box<dyn Future<Item = (), Error = ()> + 'static>),
FutureMsg(Box<dyn Future<Item = Ms, Error = Ms> + 'static>),
}
impl<Ms> From<Ms> for Effect<Ms> {
fn from(message: Ms) -> Self {
Effect::Msg(message)
}
}
impl<Ms> Effect<Ms> {
/// Apply a function to the message. If the effect is a future, the map function
/// will be called after the future is finished running.
pub fn map<F, Ms2>(self, f: F) -> Effect<Ms2>
where
Ms: 'static,
Ms2: 'static,
F: Fn(Ms) -> Ms2 + 'static,
{
match self {
Effect::Msg(msg) => Effect::Msg(f(msg)),
Effect::FutureNoMsg(fut) => Effect::FutureNoMsg(fut),
Effect::FutureMsg(fut) => Effect::FutureMsg(Box::new(fut.then(move |res| {
let res = res.map(&f).map_err(&f);
future::result(res)
}))),
}
}
}
pub struct Update<Ms> {
should_render: ShouldRender,
effect: Option<Effect<Ms>>,
}
impl<Ms> From<ShouldRender> for Update<Ms> {
fn from(should_render: ShouldRender) -> Self {
Self {
should_render,
effect: None,
}
}
}
impl<Ms> Default for Update<Ms> {
fn default() -> Self {
Self::from(ShouldRender::Render)
}
}
impl<Ms> Update<Ms> {
pub fn with_msg(effect_msg: Ms) -> Self {
Self {
effect: Some(effect_msg.into()),
..Default::default()
}
}
pub fn with_future<F>(future: F) -> Self
where
F: Future<Item = (), Error = ()> + 'static,
{
Self {
effect: Some(Effect::FutureNoMsg(Box::new(future))),
..Default::default()
}
}
pub fn with_future_msg<F>(future: F) -> Self
where
F: Future<Item = Ms, Error = Ms> + 'static,
{
Self {
effect: Some(Effect::FutureMsg(Box::new(future))),
..Default::default()
}
}
/// Modify this Update to skip rendering
pub fn skip(mut self) -> Self {
self.should_render = ShouldRender::Skip;
self
}
/// Force rendering for this Update. Cancels `skip()`.
pub fn render(mut self) -> Self {
self.should_render = ShouldRender::Render;
self
}
/// Apply a function to the message produced by the update effect, if one is present.
/// If the effect is a future, the map function will be called after the future is
/// finished running.
pub fn map<F, Ms2>(self, f: F) -> Update<Ms2>
where
Ms: 'static,
Ms2: 'static,
F: Fn(Ms) -> Ms2 + 'static,
{
let Update {
should_render,
effect,
} = self;
let effect = effect.map(|effect| effect.map(f));
Update {
should_render,
effect,
}
}
}
type UpdateFn<Ms, Mdl> = fn(Ms, &mut Mdl) -> Update<Ms>;
type ViewFn<Ms, Mdl> = fn(&Mdl) -> El<Ms>;
type RoutesFn<Ms> = fn(&crate::routing::Url) -> Ms;
type WindowEvents<Ms, Mdl> = fn(&Mdl) -> Vec<dom_types::Listener<Ms>>;
type MsgListeners<Ms> = Vec<Box<Fn(&Ms)>>;
pub struct Mailbox<Message: 'static> {
func: Rc<Fn(Message)>,
}
impl<Ms> Mailbox<Ms> {
pub fn new(func: impl Fn(Ms) + 'static) -> Self {
Mailbox {
func: Rc::new(func),
}
}
pub fn send(&self, message: Ms) {
(self.func)(message)
}
}
impl<Ms> Clone for Mailbox<Ms> {
fn clone(&self) -> Self {
Mailbox {
func: self.func.clone(),
}
}
}
// TODO: Examine what needs to be ref cells, rcs etc
type StoredPopstate = RefCell<Option<Closure<FnMut(Event)>>>;
/// Used as part of an interior-mutability pattern, ie Rc<RefCell<>>
pub struct AppData<Ms: Clone + 'static, Mdl> {
// Model is in a RefCell here so we can modify it in self.update().
pub model: RefCell<Mdl>,
main_el_vdom: RefCell<Option<El<Ms>>>,
pub popstate_closure: StoredPopstate,
pub routes: RefCell<Option<RoutesFn<Ms>>>,
window_listeners: RefCell<Vec<dom_types::Listener<Ms>>>,
msg_listeners: RefCell<MsgListeners<Ms>>,
}
pub struct AppCfg<Ms: Clone + 'static, Mdl: 'static> {
document: web_sys::Document,
mount_point: web_sys::Element,
pub update: UpdateFn<Ms, Mdl>,
view: ViewFn<Ms, Mdl>,
window_events: Option<WindowEvents<Ms, Mdl>>,
}
pub struct App<Ms: Clone + 'static, Mdl: 'static> {
/// Stateless app configuration
pub cfg: Rc<AppCfg<Ms, Mdl>>,
/// Mutable app state
pub data: Rc<AppData<Ms, Mdl>>,
}
impl<Ms: Clone + 'static, Mdl: 'static> ::std::fmt::Debug for App<Ms, Mdl> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "App")
}
}
fn find_mount_point(id: &str) -> Element {
let window = util::window();
let document = window.document().expect("Can't find the window's document");
// We log an error instead of relying on panic/except due to the panic hook not yet
// being active.
document.get_element_by_id(id).unwrap_or_else(|| {
let text = format!(
concat!(
"Can't find parent div with id={:?} (defaults to \"app\", or can be set with the .mount() method)",
),
id,
);
crate::error(&text);
panic!(text);
})
}
#[derive(Clone)]
pub struct AppBuilder<Ms: Clone + 'static, Mdl: 'static> {
model: Mdl,
update: UpdateFn<Ms, Mdl>,
view: ViewFn<Ms, Mdl>,
parent_div_id: Option<&'static str>,
routes: Option<RoutesFn<Ms>>,
window_events: Option<WindowEvents<Ms, Mdl>>,
}
impl<Ms: Clone, Mdl> AppBuilder<Ms, Mdl> {
pub fn mount(mut self, id: &'static str) -> Self {
self.parent_div_id = Some(id);
self
}
pub fn routes(mut self, routes: RoutesFn<Ms>) -> Self {
self.routes = Some(routes);
self
}
pub fn window_events(mut self, evts: WindowEvents<Ms, Mdl>) -> Self {
self.window_events = Some(evts);
self
}
pub fn finish(self) -> App<Ms, Mdl> {
let parent_div_id = self.parent_div_id.unwrap_or("app");
App::new(
self.model,
self.update,
self.view,
find_mount_point(parent_div_id),
self.routes,
self.window_events,
)
}
}
/// We use a struct instead of series of functions, in order to avoid passing
/// repetitive sequences of parameters.
impl<Ms: Clone, Mdl> App<Ms, Mdl> {
pub fn build(
model: Mdl,
update: UpdateFn<Ms, Mdl>,
view: ViewFn<Ms, Mdl>,
) -> AppBuilder<Ms, Mdl> {
AppBuilder {
model,
update,
view,
parent_div_id: None,
routes: None,
window_events: None,
}
}
fn new(
model: Mdl,
update: UpdateFn<Ms, Mdl>,
view: ViewFn<Ms, Mdl>,
mount_point: Element,
routes: Option<RoutesFn<Ms>>,
window_events: Option<WindowEvents<Ms, Mdl>>,
) -> Self {
let window = util::window();
let document = window.document().expect("Can't find the window's document");
Self {
cfg: Rc::new(AppCfg {
document,
mount_point,
update,
view,
window_events,
}),
data: Rc::new(AppData {
model: RefCell::new(model),
// This is filled for the first time in run()
main_el_vdom: RefCell::new(None),
popstate_closure: RefCell::new(None),
routes: RefCell::new(routes),
window_listeners: RefCell::new(Vec::new()),
msg_listeners: RefCell::new(Vec::new()),
}),
}
}
/// App initialization: Collect its fundamental components, setup, and perform
/// an initial render.
pub fn run(self) -> Self {
// Our initial render. Can't initialize in new due to mailbox() requiring self.
// TODO: maybe have view take an update instead of whole app?
// TODO: There's a lot of DRY between here and update.
// let mut topel_vdom = (app.data.view)(app.clone(), model.clone());
let window = util::window();
let mut topel_vdom = (self.cfg.view)(&self.data.model.borrow());
// TODO: use window events
if self.cfg.window_events.is_some() {
setup_window_listeners(
&util::window(),
&mut Vec::new(),
// TODO:
// Fix this. Bug where if we try to add initial listeners,
// we get many runtime panics. Workaround is to wait until
// app.update, which means an event must be triggered
// prior to window listeners working.
&mut Vec::new(),
// &mut (window_events)(model),
&self.mailbox(),
);
}
let document = window.document().expect("Problem getting document");
setup_input_listeners(&mut topel_vdom);
setup_websys_el_and_children(&document, &mut topel_vdom);
attach_listeners(&mut topel_vdom, &self.mailbox());
// Attach all children: This is where our initial render occurs.
websys_bridge::attach_el_and_children(&mut topel_vdom, &self.cfg.mount_point);
self.data.main_el_vdom.replace(Some(topel_vdom));
// Update the state on page load, based
// on the starting URL. Must be set up on the server as well.
if let Some(routes) = self.data.routes.borrow().clone() {
// ignore clippy re clone() on copy
routing::setup_popstate_listener(&routing::initial(self.clone(), routes), routes);
routing::setup_link_listener(&self, routes);
}
// Allows panic messages to output to the browser console.error.
panic::set_hook(Box::new(console_error_panic_hook::hook));
self
}
/// This runs whenever the state is changed, ie the user-written update function is called.
/// It updates the state, and any DOM elements affected by this change.
/// todo this is where we need to compare against differences and only update nodes affected
/// by the state change.
///
/// We re-create the whole virtual dom each time (Is there a way around this? Probably not without
/// knowing what vars the model holds ahead of time), but only edit the rendered, web_sys dom
/// for things that have been changed.
/// We re-render the virtual DOM on every change, but (attempt to) only change
/// the actual DOM, via web_sys, when we need.
/// The model stored in inner is the old model; updated_model is a newly-calculated one.
pub fn update_inner(
&self,
message: Ms,
) -> Option<Box<dyn Future<Item = (), Error = ()> + 'static>> {
for l in self.data.msg_listeners.borrow().iter() {
(l)(&message)
}
let Update {
should_render,
effect,
} = (self.cfg.update)(message, &mut self.data.model.borrow_mut());
if let Some(window_events) = self.cfg.window_events {
let mut new_listeners = (window_events)(&self.data.model.borrow());
setup_window_listeners(
&util::window(),
&mut self.data.window_listeners.borrow_mut(),
// &mut Vec::new(),
&mut new_listeners,
&self.mailbox(),
);
self.data.window_listeners.replace(new_listeners);
}
if should_render == ShouldRender::Render {
// Create a new vdom: The top element, and all its children. Does not yet
// have associated web_sys elements.
let mut topel_new_vdom = (self.cfg.view)(&self.data.model.borrow());
let mut old_vdom = self
.data
.main_el_vdom
.borrow_mut()
.take()
.expect("missing main_el_vdom");
// Detach all old listeners before patching. We'll re-add them as required during patching.
// We'll get a runtime panic if any are left un-removed.
detach_listeners(&mut old_vdom);
patch(
&self.cfg.document,
old_vdom,
&mut topel_new_vdom,
&self.cfg.mount_point,
None,
&self.mailbox(),
);
// Now that we've re-rendered, replace our stored El with the new one;
// it will be used as the old El next time.
self.data.main_el_vdom.borrow_mut().replace(topel_new_vdom);
}
if let Some(effect) = effect {
match effect {
Effect::Msg(msg) => self.update_inner(msg),
Effect::FutureNoMsg(fut) => Some(fut),
Effect::FutureMsg(fut) => {
let self2 = self.clone();
Some(Box::new(fut.then(move |res| {
// Collapse Ok(Msg) and Err(Msg) to a Msg.
let msg = res.unwrap_or_else(std::convert::identity);
// Get next Some(future)
let fut2 = self2.update_inner(msg);
// We need to return a future anyway, so if we don't have one,
// return a trivial one
fut2.unwrap_or_else(|| Box::new(future::ok(())))
})))
}
}
} else {
None
}
}
pub fn update(&self, message: Ms) {
self.update_inner(message)
.map(|fut| future_to_promise(fut.then(|_res| future::ok(JsValue::UNDEFINED))));
}
pub fn add_message_listener<F>(&self, listener: F)
where
F: Fn(&Ms) + 'static,
{
self.data
.msg_listeners
.borrow_mut()
.push(Box::new(listener));
}
fn mailbox(&self) -> Mailbox<Ms> {
let cloned = self.clone();
Mailbox::new(move |message| {
cloned.update(message);
})
}
}
/// Set up controlled components: Input, Select, and TextArea elements must stay in sync with the
/// model; don't let them get out of sync from typing or other events, which can occur if a change
/// doesn't trigger a re-render, or if something else modifies them using a side effect.
/// Handle controlled inputs: Ie force sync with the model.
fn setup_input_listener<Ms>(el: &mut El<Ms>)
where
Ms: Clone + 'static,
{
if el.tag == dom_types::Tag::Input
|| el.tag == dom_types::Tag::Select
|| el.tag == dom_types::Tag::TextArea
{
let listener = if let Some(checked) = el.attrs.vals.get(&dom_types::At::Checked) {
let checked_bool = match checked.as_ref() {
"true" => true,
"false" => false,
_ => panic!("checked must be true or false."),
};
dom_types::Listener::new_control_check(checked_bool)
} else if let Some(control_val) = el.attrs.vals.get(&dom_types::At::Value) {
dom_types::Listener::new_control(control_val.to_string())
} else {
// If Value is not specified, force the field to be blank.
dom_types::Listener::new_control("".to_string())
};
el.listeners.push(listener); // Add to the El, so we can deattach later.
}
}
// Create the web_sys element; add it to the working tree; store it in its corresponding vdom El.
fn setup_websys_el<Ms>(document: &Document, el: &mut El<Ms>)
where
Ms: Clone + 'static,
{
if el.el_ws.is_none() {
el.el_ws = Some(websys_bridge::make_websys_el(el, document));
}
}
/// Recursively sets up input listeners
fn setup_input_listeners<Ms>(el_vdom: &mut El<Ms>)
where
Ms: Clone + 'static,
{
el_vdom.walk_tree_mut(setup_input_listener);
}
/// Recursively sets up web_sys elements
fn setup_websys_el_and_children<Ms>(document: &Document, el: &mut El<Ms>)
where
Ms: Clone + 'static,
{
el.walk_tree_mut(|el| setup_websys_el(document, el));
}
impl<Ms: Clone, Mdl> Clone for App<Ms, Mdl> {
fn clone(&self) -> Self {
App {
cfg: Rc::clone(&self.cfg),
data: Rc::clone(&self.data),
}
}
}
/// Recursively attach all event-listeners. Run this after creating fresh elements.
fn attach_listeners<Ms: Clone>(el: &mut dom_types::El<Ms>, mailbox: &Mailbox<Ms>) {
el.walk_tree_mut(|el| {
if let Some(el_ws) = el.el_ws.as_ref() {
for listener in &mut el.listeners {
// todo ideally we unify attach as one method
if listener.control_val.is_some() || listener.control_checked.is_some() {
listener.attach_control(&el_ws);
} else {
listener.attach(el_ws, mailbox.clone());
}
}
}
});
}
/// Recursively detach event-listeners. Run this before patching.
fn detach_listeners<Ms: Clone>(el: &mut dom_types::El<Ms>) {
el.walk_tree_mut(|el| {
if let Some(el_ws) = el.el_ws.as_ref() {
for listener in &mut el.listeners {
listener.detach(el_ws);
}
}
});
}
/// We reattach all listeners, as with normal Els, since we have no
/// way of diffing them.
fn setup_window_listeners<Ms: Clone>(
window: &Window,
old: &mut Vec<dom_types::Listener<Ms>>,
new: &mut Vec<dom_types::Listener<Ms>>,
mailbox: &Mailbox<Ms>,
) {
for listener in old {
listener.detach(window);
}
for listener in new {
listener.attach(window, mailbox.clone());
}
}
fn patch<'a, Ms: Clone>(
document: &Document,
mut old: El<Ms>,
new: &'a mut El<Ms>,
parent: &web_sys::Node,
next_node: Option<web_sys::Node>,
mailbox: &Mailbox<Ms>,
) -> Option<&'a web_sys::Node> {
// Old_el_ws is what we're patching, with items from the new vDOM el; or replacing.
// TODO: Current sceme is that if the parent changes, redraw all children...
// TODO: fix this later.
// We make an assumption that most of the page is not dramatically changed
// by each event, to optimize.
// Assume all listeners have been removed from the old el_ws (if any), and the
// old el vdom's elements are still attached.
// take removes the interior value from the Option; otherwise we run into problems
// about not being able to remove from borrowed content.
// We remove it from the old el_vodom now, and at the end... add it to the new one.
// We don't run attach_children() when patching, hence this approach.
if old != *new {
// At this step, we already assume we have the right element - either
// by entering this func directly for the top-level, or recursively after
// analyzing children
// If the tag's different, we must redraw the element and its children; there's
// no way to patch one element type into another.
// TODO: forcing a rerender for differnet listeners is inefficient
// TODO:, but I'm not sure how to patch them.
if new.empty && !old.empty {
let old_el_ws = old
.el_ws
.take()
.expect("old el_ws missing in call to unmount_actions");
parent
.remove_child(&old_el_ws)
.expect("Problem removing old we_el when updating to empty");
if let Some(unmount_actions) = &mut old.hooks.will_unmount {
unmount_actions(&old_el_ws)
}
return None;
// If new and old are empty, we don't need to do anything.
} else if new.empty && old.empty {
return None;
}
// Namespaces can't be patched, since they involve create_element_ns instead of create_element.
// Something about this element itself is different: patch it.
else if old.tag != new.tag
|| old.namespace != new.namespace
|| old.empty != new.empty
|| old.text.is_some() != new.text.is_some()
{
// TODO: DRY here between this and later in func.
let old_el_ws = old.el_ws.take();
if let Some(unmount_actions) = &mut old.hooks.will_unmount {
unmount_actions(
old_el_ws
.as_ref()
.expect("old el_ws missing in call to unmount_actions"),
);
}
// todo: Perhaps some of this next segment should be moved to websys_bridge
setup_websys_el_and_children(document, new);
websys_bridge::attach_children(new);
let new_el_ws = new.el_ws.as_ref().expect("Missing websys el");
if old.empty {
parent
.insert_before(new_el_ws, next_node.as_ref())
.expect("Problem adding element to replace previously empty one");
} else {
parent
.replace_child(
new_el_ws,
&old_el_ws.expect("old el_ws missing in call to replace_child"),
)
.expect("Problem replacing element");
}
// Perform side-effects specified for mounting.
if let Some(mount_actions) = &mut new.hooks.did_mount {
mount_actions(new_el_ws);
}
attach_listeners(new, &mailbox);
// We've re-rendered this child and all children; we're done with this recursion.
return new.el_ws.as_ref();
} else {
// Patch parts of the Element.
let old_el_ws = old
.el_ws
.as_ref()
.expect("missing old el_ws when patching non-empty el")
.clone();
websys_bridge::patch_el_details(&mut old, new, &old_el_ws);
}
}
if old.empty && new.empty {
return None;
}
let old_el_ws = old.el_ws.take().unwrap();
// Before running patch, assume we've removed all listeners from the old element.
// Perform this attachment after we've verified we can patch this element, ie
// it has the same tag - otherwise we'd have to detach after the parent.remove_child step.
// Note that unlike the attach_listeners function, this only attaches for the current
// element.
for listener in &mut new.listeners {
if listener.control_val.is_some() || listener.control_checked.is_some() {
listener.attach_control(&old_el_ws);
} else {
listener.attach(&old_el_ws, mailbox.clone());
}
}
let num_children_in_both = old.children.len().min(new.children.len());
let mut old_children_iter = old.children.into_iter();
let mut new_children_iter = new.children.iter_mut();
let mut last_visited_node: Option<web_sys::Node> = None;
// Not using .zip() here to make sure we don't miss any of the children when one array is
// longer than the other.
for _i in 0..num_children_in_both {
let child_old = old_children_iter.next().unwrap();
let child_new = new_children_iter.next().unwrap();
// If a key's specified, use it to match the child
// There can be multiple optomizations, but assume one key. If there are multiple
// keys, use the first (There should only be one, but no constraints atm).
// if let Some(key) = child_new.key() {
// let _matching = old.children.iter().filter(|c| c.key() == Some(key));
// // todo continue implementation: Patch and re-order.
// }
// match old.children.get(i_new) {
// Some(child_old) => {
// // todo: This approach is still inefficient use of key, since it overwrites
// // todo non-matching keys, preventing them from being found later.
// if let Some(key) = child_new.key() {
// if child_old.key() == Some(key) {
// continue
// }
// }
//
// // Don't compare equality here; we do that at the top of this function
// // in the recursion.
// patch(document, &mut child_old.clone(), child_new, &old_el_ws, &mailbox);
// old_children_patched.push(child_old.id.expect("Can't find child's id"));
// },
// None => {
// // We ran out of old children to patch; create new ones.
// websys_bridge::attach_el_and_children(child_new, &old_el_ws);
// let mut child_new = child_new;
// attach_listeners(&mut child_new, &mailbox);
// }
// }
// Don't compare equality here; we do that at the top of this function
// in the recursion.
if let Some(new_el_ws) = patch(
document,
child_old,
child_new,
&old_el_ws,
match last_visited_node.as_ref() {
Some(node) => node.next_sibling(),
None => old_el_ws.first_child(),
},
&mailbox,
) {
last_visited_node = Some(new_el_ws.clone());
}
}
// Now one of the iterators is entirely consumed, and any items left in one iterator
// don't have any matching items in the other.
while let Some(child_new) = new_children_iter.next() {
// We ran out of old children to patch; create new ones.
setup_websys_el_and_children(document, child_new);
websys_bridge::attach_el_and_children(child_new, &old_el_ws);
attach_listeners(child_new, &mailbox);
}
// // Now pair up children as best we can.
// // If there are the same number of children, assume there's a 1-to-1 mapping,
// // where we will not add or remove any; but patch as needed.
// let avail_old_children = &mut old.children;
// let mut prev_child: Option<web_sys::Node> = None;
// let mut best_match;
//// let mut t;
// for (i_new, child_new) in new.children.iter_mut().enumerate() {
// if avail_old_children.is_empty() {
// // One or more new children has been added, or much content has
// // changed, or we've made a mistake: Attach new children.
// websys_bridge::attach_els(child_new, &old_el_ws);
// let mut child_new = child_new;
// attach_listeners(&mut child_new, &mailbox);
//
// } else {
// // We still have old children to pick a match from. If we pick
// // incorrectly, or there is no "good" match, we'll have some
// // patching and/or attaching (rendering) to do in subsequent recursions.
// let mut scores: Vec<(u32, f32)> = avail_old_children
// .iter()
// .enumerate()
// .map(|(i_old, c_old)| (c_old.id.unwrap(), match_score(c_old, i_old, child_new, i_new)))
// .collect();
//
// // should put highest score at the end.
// scores.sort_by(|b, a| b.1.partial_cmp(&a.1).unwrap());
//
// // Sorting children vice picking the best one makes this easier to handle
// // without irking the borrow checker, despite appearing less counter-intuitive,
// // due to the convenient pop method.
// avail_old_children.sort_by(|b, a| {
// scores
// .iter()
// .find(|s| s.0 == b.id.unwrap())
// .unwrap()
// .1
// .partial_cmp(&scores.iter().find(|s| s.0 == a.id.unwrap()).unwrap().1)
// .unwrap()
// });
//
// best_match = avail_old_children.pop().expect("Problem popping");
// Now purge any existing no-longer-needed children; they're not part of the new vdom.
while let Some(mut child) = old_children_iter.next() {
let child_el_ws = child.el_ws.take().expect("Missing child el_ws");
// TODO: DRY here between this and earlier in func
if let Some(unmount_actions) = &mut child.hooks.will_unmount {
unmount_actions(&child_el_ws)
}
// todo get to the bottom of this
match old_el_ws.remove_child(&child_el_ws) {
Ok(_) => {}
Err(_) => {
crate::log("Minor error patching html element. (remove)");
}
}
}
new.el_ws = Some(old_el_ws);
new.el_ws.as_ref()
}
/// Update app state directly, ie not from a Listener/event.
//pub fn update<Ms>(message: Ms { // todo deal with this.
// let mailbox = Mailbox::new(move |msg| {
// app.update(msg);
// });
// mailbox.send(message);
//}
pub trait _Attrs: PartialEq + ToString {
fn vals(self) -> HashMap<String, String>;
}
pub trait _Style: PartialEq + ToString {
fn vals(self) -> HashMap<String, String>;
}
pub trait _Listener<Ms>: Sized {
fn attach<T: AsRef<EventTarget>>(&mut self, el_ws: &T, mailbox: Mailbox<Ms>);
fn detach<T: AsRef<EventTarget>>(&self, el_ws: &T);
}
/// WIP towards a modular VDOM
/// Assumes dependency on web_sys.
// TODO:: Do we need <Ms> ?
pub trait _DomEl<Ms>: Sized + PartialEq + DomElLifecycle {
type Tg: PartialEq + ToString; // TODO: tostring
type At: _Attrs;
type St: _Style;
type Ls: _Listener<Ms>;
type Tx: PartialEq + ToString + Clone + Default;
// Fields
fn tag(self) -> Self::Tg;
fn attrs(self) -> Self::At;
fn style(self) -> Self::St;
fn listeners(self) -> Vec<Self::Ls>;
fn text(self) -> Option<Self::Tx>;
fn children(self) -> Vec<Self>;
fn websys_el(self) -> Option<web_sys::Element>;
fn id(self) -> Option<u32>;
// TODO: tying to dom_types is temp - defeats the urpose of the trait
fn namespace(self) -> Option<Namespace>;
// Methods
fn empty(self) -> Self;
// setters
fn set_id(&mut self, id: Option<u32>);
fn set_websys_el(&mut self, el: Option<Element>);
}
pub trait DomElLifecycle {
fn did_mount(self) -> Option<Box<FnMut(&Element)>>;
fn did_update(self) -> Option<Box<FnMut(&Element)>>;
fn will_unmount(self) -> Option<Box<FnMut(&Element)>>;
}
#[cfg(test)]
pub mod tests {
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
use super::*;
use crate as seed; // required for macros to work.
use crate::{class, prelude::*};
use wasm_bindgen::JsCast;
use web_sys::{Node, Text};
#[derive(Clone, Debug)]
enum Msg {}
fn call_patch(
doc: &Document,
parent: &Element,
mailbox: &Mailbox<Msg>,
old_vdom: El<Msg>,
mut new_vdom: El<Msg>,
) -> El<Msg> {
patch(&doc, old_vdom, &mut new_vdom, parent, None, mailbox);
new_vdom
}
fn iter_nodelist(list: web_sys::NodeList) -> impl Iterator<Item = Node> {
(0..list.length()).map(move |i| list.item(i).unwrap())
}
fn iter_child_nodes(node: &Node) -> impl Iterator<Item = Node> {
iter_nodelist(node.child_nodes())
}
#[wasm_bindgen_test]
fn el_added() {
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = El::empty(seed::dom_types::Tag::Div);
setup_websys_el(&doc, &mut vdom);
// clone so we can keep using it after vdom is modified
let old_ws = vdom.el_ws.as_ref().unwrap().clone();
parent.append_child(&old_ws).unwrap();
assert_eq!(parent.children().length(), 1);
assert_eq!(old_ws.child_nodes().length(), 0);
vdom = call_patch(&doc, &parent, &mailbox, vdom, div!["text"]);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(old_ws.child_nodes().length(), 1);
assert_eq!(
old_ws.first_child().unwrap().text_content().unwrap(),
"text"
);
call_patch(
&doc,
&parent,
&mailbox,
vdom,
div!["text", "more text", vec![li!["even more text"]]],
);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(old_ws.child_nodes().length(), 3);
assert_eq!(
old_ws
.child_nodes()
.item(0)
.unwrap()
.text_content()
.unwrap(),
"text"
);
assert_eq!(
old_ws
.child_nodes()
.item(1)
.unwrap()
.text_content()
.unwrap(),
"more text"
);
let child3 = old_ws.child_nodes().item(2).unwrap();
assert_eq!(child3.node_name(), "LI");
assert_eq!(child3.text_content().unwrap(), "even more text");
}
#[wasm_bindgen_test]
fn el_removed() {
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = El::empty(seed::dom_types::Tag::Div);
setup_websys_el(&doc, &mut vdom);
// clone so we can keep using it after vdom is modified
let old_ws = vdom.el_ws.as_ref().unwrap().clone();
parent.append_child(&old_ws).unwrap();
// First add some child nodes using the vdom
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
div!["text", "more text", vec![li!["even more text"]]],
);
assert_eq!(parent.children().length(), 1);
assert_eq!(old_ws.child_nodes().length(), 3);
let old_child1 = old_ws.child_nodes().item(0).unwrap();
// Now test that patch function removes the last 2 nodes
call_patch(&doc, &parent, &mailbox, vdom, div!["text"]);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(old_ws.child_nodes().length(), 1);
assert!(old_child1.is_same_node(old_ws.child_nodes().item(0).as_ref()));
}
#[wasm_bindgen_test]
fn el_changed() {
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = El::empty(seed::dom_types::Tag::Div);
setup_websys_el(&doc, &mut vdom);
// clone so we can keep using it after vdom is modified
let old_ws = vdom.el_ws.as_ref().unwrap().clone();
parent.append_child(&old_ws).unwrap();
// First add some child nodes using the vdom
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
div![span!["hello"], ", ", span!["world"]],
);
assert_eq!(parent.child_nodes().length(), 1);
assert_eq!(old_ws.child_nodes().length(), 3);
// Now add some attributes
call_patch(
&doc,
&parent,
&mailbox,
vdom,
div![
span![class!["first"], "hello"],
", ",
span![class!["second"], "world"],
],
);
let child1 = old_ws
.child_nodes()
.item(0)
.unwrap()
.dyn_into::<Element>()
.unwrap();
assert_eq!(child1.get_attribute("class"), Some("first".to_string()));
let child3 = old_ws
.child_nodes()
.item(2)
.unwrap()
.dyn_into::<Element>()
.unwrap();
assert_eq!(child3.get_attribute("class"), Some("second".to_string()));
}
/// Test that if the first child was a seed::empty() and it is changed to a non-empty El,
/// then the new element is inserted at the correct position.
#[wasm_bindgen_test]
fn empty_changed_in_front() {
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = El::empty(seed::dom_types::Tag::Div);
setup_websys_el(&doc, &mut vdom);
// clone so we can keep using it after vdom is modified
let old_ws = vdom.el_ws.as_ref().unwrap().clone();
parent.append_child(&old_ws).unwrap();
assert_eq!(parent.children().length(), 1);
assert_eq!(old_ws.child_nodes().length(), 0);
vdom = call_patch(&doc, &parent, &mailbox, vdom, div![seed::empty(), "b", "c"]);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(
iter_child_nodes(&old_ws)
.map(|node| node.text_content().unwrap())
.collect::<Vec<_>>(),
&["b", "c"],
);
call_patch(&doc, &parent, &mailbox, vdom, div!["a", "b", "c"]);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(
iter_child_nodes(&old_ws)
.map(|node| node.text_content().unwrap())
.collect::<Vec<_>>(),
&["a", "b", "c"],
);
}
/// Test that if a middle child was a seed::empty() and it is changed to a non-empty El,
/// then the new element is inserted at the correct position.
#[wasm_bindgen_test]
fn empty_changed_in_the_middle() {
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = El::empty(seed::dom_types::Tag::Div);
setup_websys_el(&doc, &mut vdom);
// clone so we can keep using it after vdom is modified
let old_ws = vdom.el_ws.as_ref().unwrap().clone();
parent.append_child(&old_ws).unwrap();
assert_eq!(parent.children().length(), 1);
assert_eq!(old_ws.child_nodes().length(), 0);
vdom = call_patch(&doc, &parent, &mailbox, vdom, div!["a", seed::empty(), "c"]);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(
iter_child_nodes(&old_ws)
.map(|node| node.text_content().unwrap())
.collect::<Vec<_>>(),
&["a", "c"],
);
call_patch(&doc, &parent, &mailbox, vdom, div!["a", "b", "c"]);
assert_eq!(parent.children().length(), 1);
assert!(old_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(
iter_child_nodes(&old_ws)
.map(|node| node.text_content().unwrap())
.collect::<Vec<_>>(),
&["a", "b", "c"],
);
}
/// Test that if the old_el passed to patch was itself an empty, it is correctly patched to a non-empty.
#[wasm_bindgen_test]
fn root_empty_changed() {
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = seed::empty();
vdom = call_patch(&doc, &parent, &mailbox, vdom, div!["a", seed::empty(), "c"]);
assert_eq!(parent.children().length(), 1);
let el_ws = vdom.el_ws.as_ref().expect("el_ws missing");
assert!(el_ws.is_same_node(parent.first_child().as_ref()));
assert_eq!(
iter_child_nodes(&el_ws)
.map(|node| node.text_content().unwrap())
.collect::<Vec<_>>(),
&["a", "c"],
);
}
/// Test that an empty->empty transition is handled correctly.
#[wasm_bindgen_test]
fn root_empty_to_empty() {
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let old = seed::empty();
call_patch(&doc, &parent, &mailbox, old, seed::empty());
assert_eq!(parent.children().length(), 0);
}
/// Test that a text Node is correctly patched to an Element and vice versa
#[wasm_bindgen_test]
fn text_to_element_to_text() {
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = seed::empty();
vdom = call_patch(&doc, &parent, &mailbox, vdom, El::new_text("abc"));
assert_eq!(parent.child_nodes().length(), 1);
let text = parent
.first_child()
.unwrap()
.dyn_ref::<Text>()
.expect("not a Text node")
.clone();
assert_eq!(text.text_content().unwrap(), "abc");
// change to a span (that contains a text node and styling).
// span was specifically chosen here because text Els are saved with the span tag.
// (or at least they were when the test was written.)
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
span![style!["color" => "red"], "def"],
);
assert_eq!(parent.child_nodes().length(), 1);
let element = parent
.first_child()
.unwrap()
.dyn_ref::<Element>()
.expect("not an Element node")
.clone();
assert_eq!(&element.tag_name().to_lowercase(), "span");
// change back to a text node
call_patch(&doc, &parent, &mailbox, vdom, El::new_text("abc"));
assert_eq!(parent.child_nodes().length(), 1);
let text = parent
.first_child()
.unwrap()
.dyn_ref::<Text>()
.expect("not a Text node")
.clone();
assert_eq!(text.text_content().unwrap(), "abc");
}
/// Test that the lifecycle hooks are called correctly.
#[wasm_bindgen_test]
fn lifecycle_hooks() {
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
let mailbox = Mailbox::new(|_msg: Msg| {});
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let mut vdom = seed::empty();
let node_ref: Rc<RefCell<Option<Node>>> = Default::default();
let mount_op_counter: Rc<AtomicUsize> = Default::default();
let update_counter: Rc<AtomicUsize> = Default::default();
// A real view() function would recreate these closures on each call.
// We create the closures once and then clone them, which is hopefully close enough.
let did_mount_func = {
let node_ref = node_ref.clone();
let mount_op_counter = mount_op_counter.clone();
move |node: &Node| {
node_ref.borrow_mut().replace(node.clone());
assert_eq!(
mount_op_counter.fetch_add(1, SeqCst),
0,
"did_mount was called more than once"
);
}
};
let did_update_func = {
let update_counter = update_counter.clone();
move |_node: &Node| {
update_counter.fetch_add(1, SeqCst);
}
};
let will_unmount_func = {
let node_ref = node_ref.clone();
move |_node: &Node| {
node_ref.borrow_mut().take();
// If the counter wasn't 1, then either:
// * did_mount wasn't called - we already check this elsewhere
// * did_mount was called more than once - we already check this elsewhere
// * will_unmount was called more than once
assert_eq!(
mount_op_counter.fetch_add(1, SeqCst),
1,
"will_unmount was called more than once"
);
}
};
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
div![
"a",
did_mount(did_mount_func.clone()),
did_update(did_update_func.clone()),
will_unmount(will_unmount_func.clone()),
],
);
assert!(
node_ref.borrow().is_some(),
"did_mount wasn't called and should have been"
);
assert_eq!(
update_counter.load(SeqCst),
0,
"did_update was called and shouldn't have been"
);
let first_child = parent.first_child().unwrap();
assert!(node_ref
.borrow()
.as_ref()
.unwrap()
.is_same_node(Some(&first_child)));
// now modify the element, see if did_update gets called.
vdom = call_patch(
&doc,
&parent,
&mailbox,
vdom,
div![
"a",
attrs! {At::Href => "#"},
did_mount(did_mount_func.clone()),
did_update(did_update_func.clone()),
will_unmount(will_unmount_func.clone()),
],
);
assert!(
node_ref
.borrow()
.as_ref()
.expect("will_unmount was called early")
.is_same_node(Some(&first_child)),
"node reference changed"
);
assert_eq!(
update_counter.load(SeqCst),
1,
"did_update wasn't called and should have been"
);
// and now unmount the element to see if will_unmount gets called.
call_patch(&doc, &parent, &mailbox, vdom, seed::empty());
assert!(node_ref.borrow().is_none(), "will_unmount wasn't called");
}
/// Tests an update() function that repeatedly uses a future with a Msg to modify the model
#[wasm_bindgen_test(async)]
fn update_promises() -> impl Future<Item = (), Error = JsValue> {
struct Model(u32);
#[derive(Clone)]
struct Msg;
fn update(_: Msg, model: &mut Model) -> Update<Msg> {
model.0 += 1;
if model.0 < 100 {
Update::with_future_msg(future::ok(Msg)).skip()
} else {
Skip.into()
}
}
fn view(_: &Model) -> El<Msg> {
div!["test"]
}
let doc = util::document();
let parent = doc.create_element("div").unwrap();
let app = App::new(Model(0), update, view, parent, None, None).run();
let app2 = app.clone();
app.update_inner(Msg)
.unwrap()
.map_err(|_: ()| JsValue::UNDEFINED)
.and_then(move |_| {
assert_eq!(app2.data.model.borrow_mut().0, 100);
Ok(())
})
}
}