-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
vlist.rs
289 lines (250 loc) · 8.33 KB
/
vlist.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
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
//! This module contains fragments implementation.
use std::ops::{Deref, DerefMut};
use super::{Key, VNode};
#[derive(Clone, Copy, Debug, PartialEq)]
enum FullyKeyedState {
KnownFullyKeyed,
KnownMissingKeys,
Unknown,
}
/// This struct represents a fragment of the Virtual DOM tree.
#[derive(Clone, Debug)]
pub struct VList {
/// The list of child [VNode]s
pub(crate) children: Vec<VNode>,
/// All [VNode]s in the VList have keys
fully_keyed: FullyKeyedState,
pub key: Option<Key>,
}
impl PartialEq for VList {
fn eq(&self, other: &Self) -> bool {
self.children == other.children && self.key == other.key
}
}
impl Default for VList {
fn default() -> Self {
Self::new()
}
}
impl Deref for VList {
type Target = Vec<VNode>;
fn deref(&self) -> &Self::Target {
&self.children
}
}
impl DerefMut for VList {
fn deref_mut(&mut self) -> &mut Self::Target {
self.fully_keyed = FullyKeyedState::Unknown;
&mut self.children
}
}
impl VList {
/// Creates a new empty [VList] instance.
pub const fn new() -> Self {
Self {
children: Vec::new(),
key: None,
fully_keyed: FullyKeyedState::KnownFullyKeyed,
}
}
/// Creates a new [VList] instance with children.
pub fn with_children(children: Vec<VNode>, key: Option<Key>) -> Self {
let mut vlist = VList {
fully_keyed: FullyKeyedState::Unknown,
children,
key,
};
vlist.fully_keyed = if vlist.fully_keyed() {
FullyKeyedState::KnownFullyKeyed
} else {
FullyKeyedState::KnownMissingKeys
};
vlist
}
/// Add [VNode] child.
pub fn add_child(&mut self, child: VNode) {
if self.fully_keyed == FullyKeyedState::KnownFullyKeyed && !child.has_key() {
self.fully_keyed = FullyKeyedState::KnownMissingKeys;
}
self.children.push(child);
}
/// Add multiple [VNode] children.
pub fn add_children(&mut self, children: impl IntoIterator<Item = VNode>) {
let it = children.into_iter();
let bound = it.size_hint();
self.children.reserve(bound.1.unwrap_or(bound.0));
for ch in it {
self.add_child(ch);
}
}
/// Recheck, if the all the children have keys.
///
/// You can run this, after modifying the child list through the [DerefMut] implementation of
/// [VList], to precompute an internally kept flag, which speeds up reconciliation later.
pub fn recheck_fully_keyed(&mut self) {
self.fully_keyed = if self.fully_keyed() {
FullyKeyedState::KnownFullyKeyed
} else {
FullyKeyedState::KnownMissingKeys
};
}
pub(crate) fn fully_keyed(&self) -> bool {
match self.fully_keyed {
FullyKeyedState::KnownFullyKeyed => true,
FullyKeyedState::KnownMissingKeys => false,
FullyKeyedState::Unknown => self.children.iter().all(|c| c.has_key()),
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::virtual_dom::{VTag, VText};
#[test]
fn mutably_change_children() {
let mut vlist = VList::new();
assert_eq!(
vlist.fully_keyed,
FullyKeyedState::KnownFullyKeyed,
"should start fully keyed"
);
// add a child that is keyed
vlist.add_child(VNode::VTag({
let mut tag = VTag::new("a");
tag.key = Some(42u32.into());
tag.into()
}));
assert_eq!(
vlist.fully_keyed,
FullyKeyedState::KnownFullyKeyed,
"should still be fully keyed"
);
assert_eq!(vlist.len(), 1, "should contain 1 child");
// now add a child that is not keyed
vlist.add_child(VNode::VText(VText::new("lorem ipsum")));
assert_eq!(
vlist.fully_keyed,
FullyKeyedState::KnownMissingKeys,
"should not be fully keyed, text tags have no key"
);
let _: &mut [VNode] = &mut vlist; // Use deref mut
assert_eq!(
vlist.fully_keyed,
FullyKeyedState::Unknown,
"key state should be unknown, since it was potentially modified through children"
);
}
}
#[cfg(feature = "ssr")]
mod feat_ssr {
use futures::stream::{FuturesUnordered, StreamExt};
use futures::{future, FutureExt};
use super::*;
use crate::html::AnyScope;
use crate::platform::io::{self, BufWriter};
impl VList {
pub(crate) async fn render_into_stream(
&self,
w: &mut BufWriter,
parent_scope: &AnyScope,
hydratable: bool,
) {
match &self.children[..] {
[] => {}
[child] => {
child.render_into_stream(w, parent_scope, hydratable).await;
}
[first_child, rest_children @ ..] => {
let buf_capacity = w.capacity();
let mut child_streams = Vec::with_capacity(self.children.len() - 1);
// Concurrently render rest children into a separate buffer.
let rest_child_furs = rest_children.iter().map(|child| {
let (mut w, r) = io::buffer(buf_capacity);
child_streams.push(r);
async move {
child
.render_into_stream(&mut w, parent_scope, hydratable)
.await;
}
});
// Concurrently resolve all child futures.
let resolve_fur = if rest_children.len() <= 30 {
// 30 is selected by join_all to be deemed small.
let rest_child_furs = future::join_all(rest_child_furs);
async move {
rest_child_furs.await;
}
.left_future()
} else {
let mut rest_child_furs: FuturesUnordered<_> = rest_child_furs.collect();
async move { while rest_child_furs.next().await.is_some() {} }
.right_future()
};
let transfer_fur = async move {
// Render first child to parent buffer directly.
first_child
.render_into_stream(w, parent_scope, hydratable)
.await;
// Transfer results to parent writer.
for mut r in child_streams {
while let Some(next_chunk) = r.next().await {
w.write(next_chunk.into());
}
}
};
future::join(resolve_fur, transfer_fur).await;
}
}
}
}
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(feature = "ssr")]
#[cfg(test)]
mod ssr_tests {
use tokio::test;
use crate::prelude::*;
use crate::ServerRenderer;
#[test]
async fn test_text_back_to_back() {
#[function_component]
fn Comp() -> Html {
let s = "world";
html! { <div>{"Hello "}{s}{"!"}</div> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, "<div>Hello world!</div>");
}
#[test]
async fn test_fragment() {
#[derive(PartialEq, Properties, Debug)]
struct ChildProps {
name: String,
}
#[function_component]
fn Child(props: &ChildProps) -> Html {
html! { <div>{"Hello, "}{&props.name}{"!"}</div> }
}
#[function_component]
fn Comp() -> Html {
html! {
<>
<Child name="Jane" />
<Child name="John" />
<Child name="Josh" />
</>
}
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(
s,
"<div>Hello, Jane!</div><div>Hello, John!</div><div>Hello, Josh!</div>"
);
}
}