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
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;
fn get_type_name(&self) -> Option<&'static str>;
}
struct Context<T: 'static> {
value: T,
#[cfg(debug_assertions)]
type_name: &'static str,
}
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
}
fn get_type_name(&self) -> Option<&'static str> {
#[cfg(debug_assertions)]
return Some(self.type_name);
#[cfg(not(debug_assertions))]
return None;
}
}
pub fn try_use_context<T: Clone + 'static>() -> Option<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 Some(value.clone());
}
}
current = current.unwrap_throw().borrow().parent.0.upgrade();
}
None
}
None => None,
}
})
}
#[track_caller]
pub fn use_context<T: Clone + 'static>() -> T {
try_use_context().expect("context not found for type")
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn create_context_scope<T: 'static, Out>(value: T, f: impl FnOnce() -> Out) -> Out {
let scope = create_scope(|| {});
SCOPES.with(|scopes| {
scope.0.borrow_mut().context = Some(Box::new(Context {
value,
#[cfg(debug_assertions)]
type_name: std::any::type_name::<T>(),
}));
scopes.borrow_mut().push(scope);
let out = f();
let scope = scopes.borrow_mut().pop().unwrap_throw();
on_cleanup(move || drop(scope));
out
})
}