forked from fitzgen/dodrio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
226 lines (201 loc) · 7.09 KB
/
main.rs
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
//! Test suite for the Web and headless browsers.
#![cfg(all(feature = "xxx-unstable-internal-use-only", target_arch = "wasm32"))]
use bumpalo::Bump;
use dodrio::{
Attribute, CachedSet, ElementNode, Node, NodeKind, Render, RenderContext, TextNode, Vdom,
};
use fxhash::FxHashMap;
use log::*;
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
pub mod cached;
pub mod events;
pub mod js_api;
pub mod keyed;
pub mod render;
pub fn window() -> web_sys::Window {
web_sys::window().expect("no global `window` exists")
}
pub fn document() -> web_sys::Document {
window()
.document()
.expect("should have a document on window")
}
pub fn create_element(tag: &str) -> web_sys::Element {
init_logging();
document()
.create_element(tag)
.expect("should create element OK")
}
/// Ensure that logs go to the devtools console.
pub fn init_logging() {
use std::sync::Once;
static START: Once = Once::new();
START.call_once(|| {
console_log::init_with_level(Level::Trace).expect("could not initialize console_log");
});
}
/// Assert that the `container` contains the physical DOM tree that matches
/// `r`'s rendered virtual DOM.
pub fn assert_rendered<R: for<'a> Render<'a>>(container: &web_sys::Element, r: &R) {
init_logging();
let cached_set = &RefCell::new(CachedSet::default());
let bump = &Bump::new();
let templates = &mut FxHashMap::default();
let cx = &mut RenderContext::new(bump, cached_set, templates);
let node = r.render(cx);
let child = container
.first_child()
.expect("container does not have anything rendered into it?");
let cached_set = cached_set.borrow();
check_node(&cached_set, &child, &node);
fn stringify_actual_node(n: &web_sys::Node) -> String {
if let Some(el) = n.dyn_ref::<web_sys::Element>() {
el.outer_html()
} else {
format!("#text({:?})", n.text_content())
}
}
fn check_node(cached_set: &CachedSet, actual: &web_sys::Node, expected: &Node) {
debug!("check_render:");
debug!(" actual = {}", stringify_actual_node(&actual));
debug!(" expected = {:#?}", expected);
match expected.kind {
NodeKind::Text(TextNode { text }) => {
assert_eq!(
actual.node_name().to_uppercase(),
"#TEXT",
"actual.node_name() == #TEXT"
);
assert_eq!(
actual.text_content().unwrap_or_default(),
text,
"actual.text_content() == expected.text()"
);
}
NodeKind::Element(&ElementNode {
tag_name,
attributes,
children,
namespace,
..
}) => {
assert_eq!(
actual.node_name().to_uppercase(),
tag_name.to_uppercase(),
"actual.node_name() == expected.tag_name()"
);
let actual = actual
.dyn_ref::<web_sys::Element>()
.expect("`actual` should be an `Element`");
check_attributes(actual.attributes(), attributes);
check_children(cached_set, actual.child_nodes(), children);
if let Some(namespace) = namespace {
assert_eq!(actual.namespace_uri(), Some(namespace.into()))
}
}
NodeKind::Cached(ref c) => {
let (expected, _template) = cached_set.get(c.id);
check_node(cached_set, actual, &expected);
}
}
}
fn check_attributes(actual: web_sys::NamedNodeMap, expected: &[Attribute]) {
assert_eq!(
actual.length(),
expected.len() as u32,
"actual's number of attributes == expected's number of attributes"
);
for attr in expected {
let actual_attr = actual
.get_named_item(attr.name())
.expect(&format!("should have attribute \"{}\"", attr.name()));
assert_eq!(
actual_attr.value(),
attr.value(),
"actual attr value == expected attr value for attr \"{}\"",
attr.name()
);
}
}
fn check_children(cached_set: &CachedSet, actual: web_sys::NodeList, expected: &[Node]) {
assert_eq!(
actual.length(),
expected.len() as u32,
"actual children length == expected children length"
);
for (i, child) in expected.iter().enumerate() {
let actual_child = actual.item(i as u32).unwrap();
check_node(cached_set, &actual_child, child);
}
}
}
/// Use the function `F` to render.
pub struct RenderFn<F>(F)
where
F: for<'a> Fn(&mut RenderContext<'a>) -> Node<'a>;
impl<'a, F> Render<'a> for RenderFn<F>
where
F: for<'b> Fn(&mut RenderContext<'b>) -> Node<'b>,
{
fn render(&self, cx: &mut RenderContext<'a>) -> Node<'a> {
(self.0)(cx)
}
}
/// Assert that if we start by rendering the `before` virtual DOM tree into a
/// physical DOM tree, and then diff it with the `after` virtual DOM tree, then
/// the physical DOM tree correctly matches `after`.
pub async fn assert_before_after<R, S>(before: R, after: S) -> Result<(), JsValue>
where
R: 'static + for<'a> Render<'a>,
S: 'static + for<'a> Render<'a>,
{
let container = create_element("div");
let before = Rc::new(before);
let after = Rc::new(after);
debug!("====== Rendering the *before* DOM into the physical DOM ======");
let vdom1 = Rc::new(Vdom::new(&container, before.clone()));
let _vdom2 = vdom1.clone();
debug!("====== Checking the *before* DOM against the physical DOM ======");
assert_rendered(&container, &before);
debug!("====== Rendering the *after* DOM into the physical DOM ======");
let weak = vdom1.weak();
weak.set_component(Box::new(after.clone()))
.await
.map_err(|e| e.to_string())?;
debug!("====== Checking the *after* DOM against the physical DOM ======");
assert_rendered(&container, &after);
Ok(())
}
/// A helper macro for declaring a bunch of `assert_before_after` tests.
#[macro_export]
macro_rules! before_after {
( $(
$name:ident {
before($before_bump:ident) {
$( $before:tt )*
}
after($after_bump:ident) {
$( $after:tt )*
}
}
)* ) => {
$(
#[wasm_bindgen_test]
async fn $name() {
use crate::{assert_before_after, RenderFn};
log::debug!("############### {} ###############", stringify!($name));
assert_before_after(
RenderFn(|$before_bump| { $( $before )* }),
RenderFn(|$after_bump| { $( $after )* })
)
.await
.unwrap()
}
)*
}
}