Skip to main content

dioxus_docs_kit/components/
shared.rs

1//! Hooks and components shared between the docs and blog surfaces.
2
3use dioxus::prelude::*;
4use dioxus_free_icons::Icon;
5use dioxus_free_icons::icons::ld_icons::{LdMoon, LdSun};
6
7use super::docs_layout::CurrentTheme;
8use crate::config::ThemeConfig;
9
10/// Provide the [`CurrentTheme`] context and apply the persisted theme on mount.
11///
12/// Reads the stored preference from localStorage (falling back to the config's
13/// default theme), sets `data-theme` on `<html>`, and keeps the returned signal
14/// in sync. Called by `DocsLayout`/`BlogLayout`; call it yourself when you
15/// render kit components (e.g. [`ThemeToggle`](super::ThemeToggle)) outside
16/// those layouts, e.g. in a landing-page navbar.
17pub fn use_theme_provider(theme: Option<ThemeConfig>) -> Signal<String> {
18    let theme_default = theme
19        .as_ref()
20        .map(|t| t.default_theme.clone())
21        .unwrap_or_default();
22    let storage_key = theme
23        .as_ref()
24        .map(|t| t.storage_key.clone())
25        .unwrap_or_default();
26    let has_theme = theme.is_some();
27
28    let mut current_theme = use_signal(|| theme_default.clone());
29    use_context_provider(|| CurrentTheme(current_theme));
30
31    // On mount: read stored preference and apply data-theme
32    use_effect(move || {
33        if !has_theme {
34            return;
35        }
36        let key = storage_key.clone();
37        let fallback = theme_default.clone();
38        spawn(async move {
39            let mut eval = document::eval(&format!(
40                r#"
41                let theme = null;
42                try {{ theme = localStorage.getItem('{key}'); }} catch(e) {{}}
43                theme = theme || '{fallback}';
44                document.documentElement.setAttribute('data-theme', theme);
45                dioxus.send(theme);
46                "#
47            ));
48            if let Ok(stored) = eval.recv::<String>().await {
49                current_theme.set(stored);
50            }
51        });
52    });
53
54    current_theme
55}
56
57/// Register a document-level Cmd/Ctrl+K listener that toggles `search_open`.
58///
59/// The handler is stored on `window` and any previous one is removed before
60/// registering, so layout remounts never accumulate listeners.
61pub(crate) fn use_search_hotkey(mut search_open: Signal<bool>) {
62    use_effect(move || {
63        spawn(async move {
64            let mut eval = document::eval(
65                r#"
66                if (window.__dkSearchHotkey) {
67                    document.removeEventListener('keydown', window.__dkSearchHotkey);
68                }
69                window.__dkSearchHotkey = (e) => {
70                    if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
71                        e.preventDefault();
72                        dioxus.send(true);
73                    }
74                };
75                document.addEventListener('keydown', window.__dkSearchHotkey);
76                while (true) { await new Promise(r => setTimeout(r, 1000000)); }
77                "#,
78            );
79            loop {
80                if (eval.recv::<bool>().await).is_ok() {
81                    search_open.toggle();
82                }
83            }
84        });
85    });
86}
87
88/// Light/dark theme toggle button shared by [`ThemeToggle`](super::ThemeToggle)
89/// and [`BlogThemeToggle`](super::blog::BlogThemeToggle).
90///
91/// Renders nothing if `theme` has no `toggle_themes` configured.
92#[component]
93pub(crate) fn ThemeToggleButton(theme: Option<ThemeConfig>) -> Element {
94    let toggle = match theme.as_ref().and_then(|t| t.toggle_themes.as_ref()) {
95        Some(t) => t.clone(),
96        None => return rsx! {},
97    };
98
99    let storage_key = theme
100        .as_ref()
101        .map(|t| t.storage_key.clone())
102        .unwrap_or_default();
103
104    let CurrentTheme(mut current_theme) = use_context::<CurrentTheme>();
105
106    let (light, dark) = toggle;
107    let is_dark = current_theme() == dark;
108
109    rsx! {
110        button {
111            class: "btn btn-ghost btn-sm btn-square",
112            title: if is_dark { "Switch to light mode" } else { "Switch to dark mode" },
113            onclick: move |_| {
114                let new_theme = if (current_theme)() == dark { light.clone() } else { dark.clone() };
115                current_theme.set(new_theme.clone());
116                let key = storage_key.clone();
117                spawn(async move {
118                    let _ = document::eval(&format!(
119                        r#"document.documentElement.setAttribute('data-theme', '{new_theme}');
120                        try {{ localStorage.setItem('{key}', '{new_theme}'); }} catch(e) {{}}"#
121                    ));
122                });
123            },
124            if is_dark {
125                Icon { class: "size-5", icon: LdSun }
126            } else {
127                Icon { class: "size-5", icon: LdMoon }
128            }
129        }
130    }
131}