Skip to main content

freya_components/theming/
hooks.rs

1use freya_core::prelude::{
2    Readable,
3    State,
4    WritableUtils,
5    provide_context,
6    try_consume_context,
7    use_consume,
8    use_hook,
9};
10
11use crate::theming::component_themes::Theme;
12
13/// Provides a custom [`Theme`].
14/// If a [`Theme`] context already exists, it reuses it instead of creating a new one.
15pub fn use_init_theme(theme_cb: impl FnOnce() -> Theme) -> State<Theme> {
16    use_hook(|| {
17        if let Some(mut existing) = try_consume_context::<State<Theme>>() {
18            existing.set(theme_cb());
19            existing
20        } else {
21            let state = State::create(theme_cb());
22            provide_context(state);
23            state
24        }
25    })
26}
27
28/// Subscribe to [`Theme`] changes.
29pub fn use_theme() -> State<Theme> {
30    use_consume::<State<Theme>>()
31}
32
33/// Subscribe to [`Theme`] changes, default theme will be used if there is no provided [`Theme`].
34///
35/// Primarily used by built-in components that have no control of whether they will inherit a [`Theme`] or not.
36pub fn get_theme_or_default() -> Readable<Theme> {
37    try_consume_context::<State<Theme>>()
38        .map(|v| v.into())
39        .unwrap_or_else(|| Theme::default().into())
40}