ratatui_kit/hooks/
use_context.rs

1use std::{
2    any::Any,
3    cell::{Ref, RefMut},
4};
5
6use super::Hooks;
7
8mod private {
9    pub trait Sealed {}
10
11    impl Sealed for crate::hooks::Hooks<'_, '_> {}
12}
13
14pub trait UseContext<'a>: private::Sealed {
15    /// 获取全局/局部上下文,实现依赖注入。适合主题、配置、全局状态等场景。
16    fn use_context<T: Any>(&self) -> Ref<'a, T>;
17    /// 获取可变上下文。
18    fn use_context_mut<T: Any>(&self) -> RefMut<'a, T>;
19    /// 尝试获取只读上下文,返回 Option。
20    fn try_use_context<T: Any>(&self) -> Option<Ref<'a, T>>;
21    /// 尝试获取可变上下文,返回 Option。
22    fn try_use_context_mut<T: Any>(&self) -> Option<RefMut<'a, T>>;
23}
24
25impl<'a> UseContext<'a> for Hooks<'a, '_> {
26    fn use_context<T: Any>(&self) -> Ref<'a, T> {
27        self.context
28            .expect("context not available")
29            .get_context()
30            .expect("context not found")
31    }
32
33    fn use_context_mut<T: Any>(&self) -> RefMut<'a, T> {
34        self.context
35            .expect("context not available")
36            .get_context_mut()
37            .expect("context not found")
38    }
39
40    fn try_use_context<T: Any>(&self) -> Option<Ref<'a, T>> {
41        self.context
42            .and_then(|context_stack| context_stack.get_context())
43    }
44
45    fn try_use_context_mut<T: Any>(&self) -> Option<RefMut<'a, T>> {
46        self.context
47            .and_then(|context_stack| context_stack.get_context_mut())
48    }
49}