rustolio_web/hooks/
context.rs1use std::any::{self};
12
13use super::{Scope, Signal, SignalBase, SignalGetter, SignalSetter, SignalUpdater};
14
15#[derive(Debug, PartialEq, Eq)]
16pub struct Context<T>(Signal<T>);
17impl<T> Clone for Context<T> {
18 fn clone(&self) -> Self {
19 *self
20 }
21}
22impl<T> Copy for Context<T> {}
23
24impl<T> Context<T>
25where
26 T: 'static,
27{
28 pub fn new(initial: T) -> Self {
29 let id = any::TypeId::of::<T>();
30 let signal = Signal::new(initial);
31 Scope::register_context(id, signal.slot);
32 Self(signal)
33 }
34
35 #[track_caller]
37 pub fn receive() -> Self {
38 let id = any::TypeId::of::<T>();
39 Self(Signal::from_slot(
40 Scope::receive_context(id).expect("Cannot receive Context without creating it first"),
41 ))
42 }
43}
44
45impl<T> SignalBase<T> for Context<T> {
46 fn base(&self) -> Signal<T> {
47 self.0
48 }
49}
50impl<T> SignalGetter<T> for Context<T> where T: Clone + 'static {}
51impl<T> SignalSetter<T> for Context<T> where T: PartialEq + 'static {}
52impl<T> SignalUpdater<T> for Context<T> where T: 'static {}