dioxus_docs_kit/hooks.rs
1use dioxus::prelude::*;
2
3use crate::DocsContext;
4use crate::components::{DrawerOpen, SearchOpen};
5use crate::registry::DocsRegistry;
6
7/// Signals returned by [`use_docs_providers`] so the consumer's header RSX
8/// can reference them (e.g. to wire up a search button or drawer toggle).
9pub struct DocsProviders {
10 pub search_open: Signal<bool>,
11 pub drawer_open: Signal<bool>,
12}
13
14/// Build a [`DocsContext`] from the current docs path as a plain `String`.
15///
16/// Prefer this over [`DocsContext::new`] when the path comes from your router.
17/// `use_route::<Route>()` returns a plain value, not a signal, so wrapping it
18/// yourself with `use_memo(move || ...)` reads no reactive source: the memo
19/// runs once and never again, freezing the sidebar highlight, tab sync and
20/// mobile-drawer auto-close on the first page visited. (`use_memo` paired with
21/// [`use_reactive!`] is correct, but easy to forget.)
22///
23/// Taking the path by value removes the trap — this hook re-runs with your
24/// layout component on every navigation and rewraps the path reactively.
25///
26/// ```rust,ignore
27/// let route = use_route::<Route>();
28/// let current_path = match route {
29/// Route::DocsPage { slug } => slug.join("/"),
30/// _ => String::new(),
31/// };
32///
33/// let docs_ctx = use_docs_context(current_path, "/docs", Callback::new(move |path: String| {
34/// nav.push(Route::DocsPage { slug: path.split('/').map(String::from).collect() });
35/// }));
36/// ```
37pub fn use_docs_context(
38 current_path: String,
39 base_path: impl Into<String>,
40 navigate: Callback<String>,
41) -> DocsContext {
42 let path = use_memo(use_reactive!(|current_path| current_path));
43 DocsContext::new(path, base_path, navigate)
44}
45
46/// One-call setup for all the context providers that `DocsLayout` and its
47/// children expect.
48///
49/// Call this in your docs layout wrapper **before** rendering `DocsLayout`:
50///
51/// ```rust,ignore
52/// let providers = use_docs_providers(&*DOCS, docs_ctx);
53/// // Use providers.search_open / providers.drawer_open in your header RSX
54/// ```
55///
56/// This replaces the manual calls to:
57/// - `use_context_provider(|| registry)`
58/// - `use_context_provider(|| docs_ctx)`
59/// - `use_signal(|| false)` × 2 + `use_context_provider` for search_open / DrawerOpen
60pub fn use_docs_providers(registry: &'static DocsRegistry, docs_ctx: DocsContext) -> DocsProviders {
61 use_context_provider(|| registry);
62 use_context_provider(|| docs_ctx);
63
64 let search_open = use_signal(|| false);
65 let drawer_open = use_signal(|| false);
66
67 use_context_provider(|| SearchOpen(search_open));
68 use_context_provider(|| DrawerOpen(drawer_open));
69
70 DocsProviders {
71 search_open,
72 drawer_open,
73 }
74}