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>;
16 fn use_context_mut<T: Any>(&self) -> RefMut<'a, T>;
17
18 fn try_use_context<T: Any>(&self) -> Option<Ref<'a, T>>;
19 fn try_use_context_mut<T: Any>(&self) -> Option<RefMut<'a, T>>;
20}
21
22impl<'a> UseContext<'a> for Hooks<'a, '_> {
23 fn use_context<T: Any>(&self) -> Ref<'a, T> {
24 self.context
25 .expect("context not available")
26 .get_context()
27 .expect("context not found")
28 }
29
30 fn use_context_mut<T: Any>(&self) -> RefMut<'a, T> {
31 self.context
32 .expect("context not available")
33 .get_context_mut()
34 .expect("context not found")
35 }
36
37 fn try_use_context<T: Any>(&self) -> Option<Ref<'a, T>> {
38 self.context
39 .and_then(|context_stack| context_stack.get_context())
40 }
41
42 fn try_use_context_mut<T: Any>(&self) -> Option<RefMut<'a, T>> {
43 self.context
44 .and_then(|context_stack| context_stack.get_context_mut())
45 }
46}