ratatui_kit/hooks/
use_context.rs1use 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 fn use_context<T: Any>(&self) -> Ref<'a, T>;
17 fn use_context_mut<T: Any>(&self) -> RefMut<'a, T>;
19 fn try_use_context<T: Any>(&self) -> Option<Ref<'a, T>>;
21 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}