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
use std::any::{Any, TypeId};
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use crate::*;
pub(super) trait ContextAny {
fn get_type_id(&self) -> TypeId;
fn get_value(&self) -> &dyn Any;
}
struct Context<T: 'static> {
value: T,
}
impl<T: 'static> ContextAny for Context<T> {
fn get_type_id(&self) -> TypeId {
self.value.type_id()
}
fn get_value(&self) -> &dyn Any {
&self.value
}
}
pub fn use_context<T: Clone + 'static>() -> T {
SCOPES.with(|scopes| {
let scopes = scopes.borrow();
let mut current = scopes.last().map(|s| Rc::clone(&s.0));
match current {
Some(_) => {
while let Some(scope) = ¤t {
if let Some(context) = &scope.borrow().context {
if let Some(value) = context.get_value().downcast_ref::<T>() {
return value.clone();
}
}
current = current.unwrap_throw().borrow().parent.0.upgrade();
}
panic!("context not found for type")
}
None => panic!("context not found for type"),
}
})
}
pub fn create_context_scope<T: 'static, Out>(value: T, f: impl FnOnce() -> Out) -> Out {
SCOPES.with(|scopes| {
let scope = ReactiveScope::new();
scope.0.borrow_mut().context = Some(Box::new(Context { value }));
scopes.borrow_mut().push(scope);
let out = f();
let scope = scopes.borrow_mut().pop().unwrap_throw();
on_cleanup(move || drop(scope));
out
})
}