Skip to main content

rustolio_web/hooks/
context.rs

1//
2// SPDX-License-Identifier: MPL-2.0
3//
4// Copyright (c) 2026 Tobias Binnewies. All rights reserved.
5//
6// This Source Code Form is subject to the terms of the Mozilla Public
7// License, v. 2.0. If a copy of the MPL was not distributed with this
8// file, You can obtain one at http://mozilla.org/MPL/2.0/.
9//
10
11use 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    /// Panics when there is no context with this type created
36    #[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 {}