Skip to main content

dioxus_docs_kit/
lib.rs

1//! # dioxus-docs-kit
2//!
3//! Reusable documentation site shell and blog engine for Dioxus applications.
4//!
5//! Provides a complete docs layout with sidebar navigation, search modal,
6//! page navigation, OpenAPI API reference pages, and mobile drawer.
7//! Also includes a full blog engine with post listing, tag filtering,
8//! search, reading time, and MDX rendering.
9//!
10//! ## Quick Start — Docs
11//!
12//! ```rust,ignore
13//! use dioxus::prelude::*;
14//! use dioxus_docs_kit::{DocsConfig, DocsRegistry, DocsContext, DocsLayout, DocsPageContent};
15//! use std::sync::LazyLock;
16//!
17//! static DOCS: LazyLock<DocsRegistry> = LazyLock::new(|| {
18//!     DocsConfig::new(include_str!("../docs/_nav.json"), doc_content_map())
19//!         .with_default_path("getting-started/introduction")
20//!         .build()
21//! });
22//! ```
23//!
24//! ## Quick Start — Blog
25//!
26//! ```rust,ignore
27//! use dioxus::prelude::*;
28//! use dioxus_docs_kit::{BlogConfig, BlogRegistry, BlogContext, BlogLayout, BlogList, BlogPostView};
29//! use std::sync::LazyLock;
30//!
31//! dioxus_docs_kit::blog_content_map!();
32//!
33//! static BLOG: LazyLock<BlogRegistry> = LazyLock::new(|| {
34//!     BlogConfig::new(include_str!("../blog/_blog.json"), blog_content_map())
35//!         .with_posts_per_page(9)
36//!         .build()
37//! });
38//! ```
39
40// The tree-sitter C grammars pulled in via `dioxus-code` (for syntax
41// highlighting) reference the libc global `stderr`. Its definition lives in
42// `arborium-sysroot`'s C shim, but that shim links as a plain static archive
43// whose `stdio.o` member only gets pulled in when `stderr` is undefined as the
44// linker reaches it — and on some host toolchains (notably Homebrew LLVM on
45// macOS) it isn't, so the wasm link fails with `undefined symbol: stderr`.
46//
47// We define `stderr` here in the *library* so every consumer that links
48// `dioxus-docs-kit` gets the symbol — defining it only in the docs-kit binary
49// (`src/main.rs`) leaves library consumers (their own app binaries) to hit the
50// same link error. A strong definition preempts the sysroot's lazy archive
51// member, so where the shim already links cleanly its `stdio.o` simply isn't
52// pulled and there is never a duplicate symbol. `fprintf` is a no-op macro in
53// the shim's headers, so `stderr` is referenced but never dereferenced at
54// runtime. `#[used]` keeps the symbol from being dropped from the rlib before
55// it can satisfy the cross-crate reference at final link.
56//
57// This is only needed when the `highlight` feature is enabled, since that is what
58// links the tree-sitter C code (via `dioxus-code`) that references `stderr`.
59#[cfg(all(target_arch = "wasm32", feature = "highlight"))]
60mod wasm_sysroot_stderr {
61    use core::ffi::c_void;
62    static mut DUMMY_FILE: u8 = 0;
63    #[used]
64    #[unsafe(no_mangle)]
65    static mut stderr: *mut c_void = &raw mut DUMMY_FILE as *mut c_void;
66}
67
68pub mod blog;
69pub mod components;
70pub mod config;
71pub mod error;
72pub mod hooks;
73pub mod registry;
74pub(crate) mod search;
75#[cfg(feature = "server")]
76pub mod server;
77
78use dioxus::prelude::*;
79
80/// Precompiled stylesheet covering every class the kit's components emit
81/// (Tailwind utilities, DaisyUI dark/light themes, typography prose, and the
82/// `--dk-*` token surface from `theme.css`).
83///
84/// Link it to run the kit without any Tailwind/Bun setup of your own:
85///
86/// ```rust,ignore
87/// rsx! {
88///     document::Stylesheet { href: dioxus_docs_kit::DOCS_KIT_CSS }
89/// }
90/// ```
91///
92/// If your app already runs its own Tailwind build, skip this and use the
93/// `safelist.html` approach from the README instead — the precompiled sheet
94/// only contains the kit's classes, not yours.
95pub const DOCS_KIT_CSS: Asset = asset!("/assets/docs-kit.css");
96
97// ============================================================================
98// Docs context
99// ============================================================================
100
101/// Navigation bridge that decouples library components from the consumer's Route enum.
102///
103/// The consumer creates this in their docs layout wrapper and provides it via `use_context_provider`.
104#[derive(Clone)]
105#[non_exhaustive]
106pub struct DocsContext {
107    /// Current docs page path (e.g. "getting-started/introduction").
108    pub current_path: ReadSignal<String>,
109    /// Base URL path for docs (e.g. "/docs").
110    pub base_path: String,
111    /// Callback to navigate to a docs page by content path.
112    pub navigate: Callback<String>,
113    /// Optional full site URL (e.g. `https://example.com`). Used as the canonical
114    /// host for emitted `<link rel="canonical">` and `og:url` tags. Independent
115    /// of [`auto_meta`](Self::auto_meta) — set it whenever you want kit helpers
116    /// (sitemap generation, canonical URLs) to know the public origin, even if
117    /// you suppress automatic meta emission.
118    pub site_url: Option<String>,
119    /// When true, the kit emits per-page `<title>`, `<meta name="description">`,
120    /// Open Graph and Twitter Card tags from frontmatter. Set to `false` if your
121    /// app manages its own `<head>` (e.g. brand-specific OG images, structured
122    /// data) and the kit's emissions would conflict. Title and description tags
123    /// always emit when this is on; canonical and `og:url` only emit when
124    /// [`site_url`](Self::site_url) is also set.
125    pub auto_meta: bool,
126    /// When true, [`DocsPageMeta`] emits a
127    /// `<link rel="alternate" type="text/markdown">` pointing at the page's raw
128    /// Markdown source (`<base_path>/<path>.md`), a discoverability hint for AI
129    /// crawlers and "view as Markdown" tooling. Enable this only if your server
130    /// actually serves those `.md` URLs (see `server::SeoRouter` behind the
131    /// `server` feature). Emitted only for MDX pages (OpenAPI endpoint pages
132    /// have no Markdown source), and only when [`auto_meta`](Self::auto_meta)
133    /// is also on.
134    pub markdown_alternate: bool,
135}
136
137impl DocsContext {
138    /// Create a context from the three required fields.
139    ///
140    /// The meta fields default to `site_url: None`, `auto_meta: true`,
141    /// `markdown_alternate: false`; override them with the `with_*` setters.
142    /// Prefer this over a struct literal — new fields get sensible defaults
143    /// here instead of breaking your build.
144    pub fn new(
145        current_path: impl Into<ReadSignal<String>>,
146        base_path: impl Into<String>,
147        navigate: Callback<String>,
148    ) -> Self {
149        Self {
150            current_path: current_path.into(),
151            base_path: base_path.into(),
152            navigate,
153            site_url: None,
154            auto_meta: true,
155            markdown_alternate: false,
156        }
157    }
158
159    /// Set the public site origin (e.g. `"https://example.com"`).
160    pub fn with_site_url(mut self, site_url: impl Into<String>) -> Self {
161        self.site_url = Some(site_url.into());
162        self
163    }
164
165    /// Enable or disable automatic per-page meta emission (default: on).
166    pub fn with_auto_meta(mut self, auto_meta: bool) -> Self {
167        self.auto_meta = auto_meta;
168        self
169    }
170
171    /// Emit `<link rel="alternate" type="text/markdown">` tags (default: off).
172    pub fn with_markdown_alternate(mut self, markdown_alternate: bool) -> Self {
173        self.markdown_alternate = markdown_alternate;
174        self
175    }
176}
177
178// ============================================================================
179// Blog context
180// ============================================================================
181
182/// Navigation bridge for blog pages, decoupled from the consumer's Route enum.
183///
184/// The consumer creates this in their blog layout wrapper and provides it via `use_context_provider`.
185#[derive(Clone)]
186#[non_exhaustive]
187pub struct BlogContext {
188    /// Current blog post slug (empty on the list/index page).
189    pub current_slug: ReadSignal<String>,
190    /// Base URL path for the blog (e.g. "/blog").
191    pub base_path: String,
192    /// Callback to navigate to a blog post by slug (empty string = blog index).
193    pub navigate: Callback<String>,
194    /// Optional full site URL (e.g. `https://example.com`). Used as the canonical
195    /// host for emitted `<link rel="canonical">`, `og:url`, and JSON-LD URLs.
196    /// Independent of [`auto_meta`](Self::auto_meta) — set it whenever you want
197    /// kit helpers (sitemap/RSS, canonical URLs) to know the public origin, even
198    /// if you suppress automatic meta emission.
199    pub site_url: Option<String>,
200    /// When true, the kit emits per-page `<title>`, `<meta name="description">`,
201    /// Open Graph, Twitter Card, and Article JSON-LD tags from frontmatter. Set
202    /// to `false` if your app manages its own `<head>` (e.g. brand-specific OG
203    /// images, structured data) and the kit's emissions would conflict. Title
204    /// and description tags always emit when this is on; canonical, `og:url`,
205    /// and JSON-LD `@id` only emit when [`site_url`](Self::site_url) is also set.
206    pub auto_meta: bool,
207    /// When true, [`BlogPostMeta`] emits a
208    /// `<link rel="alternate" type="text/markdown">` pointing at the post's raw
209    /// Markdown source (`<base_path>/<slug>.md`), a discoverability hint for AI
210    /// crawlers and "view as Markdown" tooling. Enable this only if your server
211    /// actually serves those `.md` URLs (see `server::SeoRouter` behind the
212    /// `server` feature). Emitted only when [`auto_meta`](Self::auto_meta) is
213    /// also on.
214    pub markdown_alternate: bool,
215}
216
217impl BlogContext {
218    /// Create a context from the three required fields.
219    ///
220    /// The meta fields default to `site_url: None`, `auto_meta: true`,
221    /// `markdown_alternate: false`; override them with the `with_*` setters.
222    /// Prefer this over a struct literal — new fields get sensible defaults
223    /// here instead of breaking your build.
224    pub fn new(
225        current_slug: impl Into<ReadSignal<String>>,
226        base_path: impl Into<String>,
227        navigate: Callback<String>,
228    ) -> Self {
229        Self {
230            current_slug: current_slug.into(),
231            base_path: base_path.into(),
232            navigate,
233            site_url: None,
234            auto_meta: true,
235            markdown_alternate: false,
236        }
237    }
238
239    /// Set the public site origin (e.g. `"https://example.com"`).
240    pub fn with_site_url(mut self, site_url: impl Into<String>) -> Self {
241        self.site_url = Some(site_url.into());
242        self
243    }
244
245    /// Enable or disable automatic per-page meta emission (default: on).
246    pub fn with_auto_meta(mut self, auto_meta: bool) -> Self {
247        self.auto_meta = auto_meta;
248        self
249    }
250
251    /// Emit `<link rel="alternate" type="text/markdown">` tags (default: off).
252    pub fn with_markdown_alternate(mut self, markdown_alternate: bool) -> Self {
253        self.markdown_alternate = markdown_alternate;
254        self
255    }
256}
257
258// ============================================================================
259// Docs re-exports
260// ============================================================================
261
262#[cfg(feature = "highlight")]
263pub use config::CodeThemeConfig;
264pub use config::{DocsConfig, ThemeConfig};
265pub use error::DocsKitError;
266pub use registry::DocsRegistry;
267pub use registry::{ApiEndpointEntry, NavConfig, NavGroup, SearchEntry};
268
269pub use components::{
270    ActiveTab, CopyPageButton, CurrentTheme, DocsLayout, DocsPageContent, DocsPageMeta,
271    DocsPageNav, DocsSidebar, DocsVariant, DrawerOpen, LayoutOffsets, MobileDrawer, SearchButton,
272    SearchModal, SearchOpen, ThemeToggle, use_theme_provider,
273};
274
275pub use hooks::{DocsProviders, use_docs_context, use_docs_providers};
276
277pub use dioxus_mdx::{
278    ApiOperation, ApiTag, DocContent, DocTableOfContents, EndpointPage, HttpMethod, OpenApiSpec,
279    ParsedDoc, extract_headers,
280};
281
282#[cfg(feature = "highlight")]
283pub use dioxus_mdx::CodeThemeOverride;
284
285#[cfg(feature = "highlight")]
286pub use dioxus_code::{Code, CodeTheme, Language, SourceCode, Theme};
287
288#[cfg(feature = "mermaid")]
289pub use dioxus_mdx::MermaidDiagram;
290
291// ============================================================================
292// Blog re-exports
293// ============================================================================
294
295pub use blog::hooks::{ActiveTag, CurrentPage};
296pub use blog::types::{Author, BlogFrontmatter, BlogPost, BlogSearchEntry};
297pub use blog::{BlogConfig, BlogProviders, BlogRegistry, use_blog_providers};
298
299pub use components::{
300    AuthorInfo, BlogCard, BlogIndexMeta, BlogLayout, BlogList, BlogMobileDrawer, BlogPostMeta,
301    BlogPostNav, BlogPostView, BlogSearchButton, BlogSearchModal, BlogThemeToggle,
302    ReadingProgressBar, ReadingTimeBadge, RelatedPosts, TagFilter,
303};
304
305// ============================================================================
306// Macros
307// ============================================================================
308
309/// Generates a `doc_content_map()` function that returns a
310/// `HashMap<&'static str, &'static str>` from the build-script output.
311///
312/// Place this at module level in your `main.rs`:
313///
314/// ```rust,ignore
315/// dioxus_docs_kit::doc_content_map!();
316/// ```
317///
318/// Requires `dioxus-docs-kit-build` in `[build-dependencies]` and a `build.rs`
319/// that calls `dioxus_docs_kit_build::generate_content_map("docs/_nav.json")`.
320#[macro_export]
321macro_rules! doc_content_map {
322    () => {
323        fn doc_content_map() -> ::std::collections::HashMap<&'static str, &'static str> {
324            include!(concat!(env!("OUT_DIR"), "/doc_content_generated.rs"))
325        }
326    };
327}
328
329/// Generates a `blog_content_map()` function that returns a
330/// `HashMap<&'static str, &'static str>` from the build-script output.
331///
332/// Place this at module level in your `main.rs`:
333///
334/// ```rust,ignore
335/// dioxus_docs_kit::blog_content_map!();
336/// ```
337///
338/// Requires `dioxus-docs-kit-build` in `[build-dependencies]` and a `build.rs`
339/// that calls `dioxus_docs_kit_build::generate_blog_content_map("blog/_blog.json")`.
340#[macro_export]
341macro_rules! blog_content_map {
342    () => {
343        fn blog_content_map() -> ::std::collections::HashMap<&'static str, &'static str> {
344            include!(concat!(env!("OUT_DIR"), "/blog_content_generated.rs"))
345        }
346    };
347}