-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
scope.rs
421 lines (378 loc) · 12.2 KB
/
scope.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
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
use super::{Callback, Component, NodeRef, Renderable};
use crate::scheduler::{scheduler, ComponentRunnableType, Runnable, Shared};
use crate::virtual_dom::{VDiff, VNode};
use cfg_if::cfg_if;
use std::any::{Any, TypeId};
use std::cell::{Ref, RefCell};
use std::fmt;
use std::ops::Deref;
use std::rc::Rc;
cfg_if! {
if #[cfg(feature = "std_web")] {
use stdweb::web::Element;
} else if #[cfg(feature = "web_sys")] {
use web_sys::Element;
}
}
/// Updates for a `Component` instance. Used by scope sender.
pub(crate) enum ComponentUpdate<COMP: Component> {
/// Force update
Force,
/// Wraps messages for a component.
Message(COMP::Message),
/// Wraps batch of messages for a component.
MessageBatch(Vec<COMP::Message>),
/// Wraps properties and new node ref for a component.
Properties(COMP::Properties, NodeRef),
}
/// Untyped scope used for accessing parent scope
#[derive(Debug, Clone)]
pub struct AnyScope {
pub(crate) type_id: TypeId,
pub(crate) parent: Option<Rc<AnyScope>>,
pub(crate) state: Rc<dyn Any>,
}
impl<COMP: Component> From<Scope<COMP>> for AnyScope {
fn from(scope: Scope<COMP>) -> Self {
AnyScope {
type_id: TypeId::of::<COMP>(),
parent: scope.parent,
state: Rc::new(scope.state),
}
}
}
impl AnyScope {
/// Returns the parent scope
pub fn get_parent(&self) -> Option<&AnyScope> {
self.parent.as_deref()
}
/// Returns the type of the linked component
pub fn get_type_id(&self) -> &TypeId {
&self.type_id
}
/// Attempts to downcast into a typed scope
pub fn downcast<COMP: Component>(self) -> Scope<COMP> {
Scope {
parent: self.parent,
state: self
.state
.downcast_ref::<Shared<Option<ComponentState<COMP>>>>()
.expect("unexpected component type")
.clone(),
}
}
}
/// A context which allows sending messages to a component.
pub struct Scope<COMP: Component> {
parent: Option<Rc<AnyScope>>,
state: Shared<Option<ComponentState<COMP>>>,
}
impl<COMP: Component> fmt::Debug for Scope<COMP> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Scope<_>")
}
}
impl<COMP: Component> Clone for Scope<COMP> {
fn clone(&self) -> Self {
Scope {
parent: self.parent.clone(),
state: self.state.clone(),
}
}
}
impl<COMP: Component> Scope<COMP> {
/// Returns the parent scope
pub fn get_parent(&self) -> Option<&AnyScope> {
self.parent.as_deref()
}
/// Returns the linked component if available
pub fn get_component(&self) -> Option<impl Deref<Target = COMP> + '_> {
self.state.try_borrow().ok().and_then(|state_ref| {
state_ref.as_ref()?;
Some(Ref::map(state_ref, |state| {
state.as_ref().unwrap().component.as_ref()
}))
})
}
pub(crate) fn new(parent: Option<AnyScope>) -> Self {
let parent = parent.map(Rc::new);
let state = Rc::new(RefCell::new(None));
Scope { parent, state }
}
/// Mounts a component with `props` to the specified `element` in the DOM.
pub(crate) fn mount_in_place(
self,
element: Element,
ancestor: Option<VNode>,
node_ref: NodeRef,
props: COMP::Properties,
) -> Scope<COMP> {
*self.state.borrow_mut() = Some(ComponentState::new(
element,
ancestor,
node_ref,
self.clone(),
props,
));
self.update(ComponentUpdate::Force, true);
self
}
/// Schedules a task to send an update to a component
pub(crate) fn update(&self, update: ComponentUpdate<COMP>, first_update: bool) {
let update = UpdateComponent {
state: self.state.clone(),
update,
};
scheduler().push_comp(ComponentRunnableType::Update, Box::new(update));
self.rendered(first_update);
}
/// Schedules a task to call the rendered method on a component
pub(crate) fn rendered(&self, first_render: bool) {
let state = self.state.clone();
let rendered = RenderedComponent {
state,
first_render,
};
scheduler().push_comp(ComponentRunnableType::Rendered, Box::new(rendered));
}
/// Schedules a task to destroy a component
pub(crate) fn destroy(&mut self) {
let state = self.state.clone();
let destroy = DestroyComponent { state };
scheduler().push_comp(ComponentRunnableType::Destroy, Box::new(destroy));
}
/// Send a message to the component
pub fn send_message<T>(&self, msg: T)
where
T: Into<COMP::Message>,
{
self.update(ComponentUpdate::Message(msg.into()), false);
}
/// Send a batch of messages to the component.
///
/// This is useful for reducing re-renders of the components because the messages are handled
/// together and the view function is called only once if needed.
pub fn send_message_batch(&self, messages: Vec<COMP::Message>) {
self.update(ComponentUpdate::MessageBatch(messages), false);
}
/// Creates a `Callback` which will send a message to the linked component's
/// update method when invoked.
pub fn callback<F, IN, M>(&self, function: F) -> Callback<IN>
where
M: Into<COMP::Message>,
F: Fn(IN) -> M + 'static,
{
let scope = self.clone();
let closure = move |input| {
let output = function(input);
scope.send_message(output);
};
closure.into()
}
/// Creates a `Callback` from a FnOnce which will send a message to the linked
/// component's update method when invoked.
pub fn callback_once<F, IN, M>(&self, function: F) -> Callback<IN>
where
M: Into<COMP::Message>,
F: FnOnce(IN) -> M + 'static,
{
let scope = self.clone();
let closure = move |input| {
let output = function(input);
scope.send_message(output);
};
Callback::once(closure)
}
/// Creates a `Callback` which will send a batch of messages back to the linked
/// component's update method when invoked.
pub fn batch_callback<F, IN>(&self, function: F) -> Callback<IN>
where
F: Fn(IN) -> Vec<COMP::Message> + 'static,
{
let scope = self.clone();
let closure = move |input| {
let messages = function(input);
scope.send_message_batch(messages);
};
closure.into()
}
}
struct ComponentState<COMP: Component> {
element: Element,
node_ref: NodeRef,
scope: Scope<COMP>,
component: Box<COMP>,
last_root: Option<VNode>,
rendered: bool,
}
impl<COMP: Component> ComponentState<COMP> {
fn new(
element: Element,
ancestor: Option<VNode>,
node_ref: NodeRef,
scope: Scope<COMP>,
props: COMP::Properties,
) -> Self {
let component = Box::new(COMP::create(props, scope.clone()));
Self {
element,
node_ref,
scope,
component,
last_root: ancestor,
rendered: false,
}
}
}
struct UpdateComponent<COMP>
where
COMP: Component,
{
state: Shared<Option<ComponentState<COMP>>>,
update: ComponentUpdate<COMP>,
}
impl<COMP> Runnable for UpdateComponent<COMP>
where
COMP: Component,
{
fn run(self: Box<Self>) {
if let Some(mut state) = self.state.borrow_mut().as_mut() {
let should_update = match self.update {
ComponentUpdate::Force => true,
ComponentUpdate::Message(message) => state.component.update(message),
ComponentUpdate::MessageBatch(messages) => messages
.into_iter()
.fold(false, |acc, msg| state.component.update(msg) || acc),
ComponentUpdate::Properties(props, node_ref) => {
// When components are updated, they receive a new node ref that
// must be linked to previous one.
node_ref.link(state.node_ref.clone());
state.component.change(props)
}
};
if should_update {
state.rendered = false;
let mut root = state.component.render();
let last_root = state.last_root.take();
if let Some(node) =
root.apply(&state.scope.clone().into(), &state.element, None, last_root)
{
state.node_ref.set(Some(node));
} else if let VNode::VComp(child) = &root {
// If the root VNode is a VComp, we won't have access to the rendered DOM node
// because components render asynchronously. In order to bubble up the DOM node
// from the VComp, we need to link the currently rendering component with its
// root child component.
state.node_ref.link(child.node_ref.clone());
}
state.last_root = Some(root);
};
}
}
}
struct RenderedComponent<COMP>
where
COMP: Component,
{
state: Shared<Option<ComponentState<COMP>>>,
first_render: bool,
}
impl<COMP> Runnable for RenderedComponent<COMP>
where
COMP: Component,
{
fn run(self: Box<Self>) {
if let Some(mut state) = self.state.borrow_mut().as_mut() {
if !state.rendered {
state.rendered = true;
state.component.rendered(self.first_render);
}
}
}
}
struct DestroyComponent<COMP>
where
COMP: Component,
{
state: Shared<Option<ComponentState<COMP>>>,
}
impl<COMP> Runnable for DestroyComponent<COMP>
where
COMP: Component,
{
fn run(self: Box<Self>) {
if let Some(mut state) = self.state.borrow_mut().take() {
drop(state.component);
if let Some(last_frame) = &mut state.last_root {
last_frame.detach(&state.element);
}
}
}
}
#[cfg(test)]
mod tests {
use crate::html::*;
use crate::Properties;
use std::ops::Deref;
#[cfg(feature = "wasm_test")]
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
#[cfg(feature = "wasm_test")]
wasm_bindgen_test_configure!(run_in_browser);
#[derive(Clone, Properties)]
struct Props {
lifecycle: Rc<RefCell<Vec<String>>>,
}
struct Comp {
props: Props,
}
impl Component for Comp {
type Message = ();
type Properties = Props;
fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self {
props.lifecycle.borrow_mut().push("create".into());
Comp { props }
}
fn rendered(&mut self, first_render: bool) {
self.props
.lifecycle
.borrow_mut()
.push(format!("rendered({})", first_render));
}
fn update(&mut self, _: Self::Message) -> ShouldRender {
self.props.lifecycle.borrow_mut().push("update".into());
false
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
self.props.lifecycle.borrow_mut().push("change".into());
false
}
fn view(&self) -> Html {
self.props.lifecycle.borrow_mut().push("view".into());
html! {}
}
}
impl Drop for Comp {
fn drop(&mut self) {
self.props.lifecycle.borrow_mut().push("drop".into());
}
}
#[test]
fn text_mount_in_place() {
let document = crate::utils::document();
let lifecycle: Rc<RefCell<Vec<String>>> = Rc::default();
let props = Props {
lifecycle: lifecycle.clone(),
};
let scope = Scope::<Comp>::new(None);
let el = document.create_element("div").unwrap();
scope.mount_in_place(el, None, NodeRef::default(), props);
assert_eq!(
lifecycle.borrow_mut().deref(),
&vec![
"create".to_string(),
"view".to_string(),
"rendered(true)".to_string()
]
);
}
}