Skip to main content

orbital_core_components/code/
mod.rs

1use leptos::{either::EitherOf3, prelude::*};
2use orbital_macros::component_doc;
3use orbital_style::inject_style;
4
5const CODE_CSS: &str = include_str!("code.css");
6
7/// Monospace code block for CLI commands, API identifiers, and short config samples.
8///
9/// Pass `text` for plain content. Pass `inner_html` only when you control the markup (for example pre-highlighted output from a trusted highlighter) — do not pass unsanitized user input to `inner_html`.
10///
11/// # When to use
12///
13/// - Single-line or multi-line code snippets in docs and settings panels - Inline monospace copy inside prose (wrap in a short `text` value)
14///
15/// # Examples
16///
17/// ## Code snippet
18/// A plain code block with a distinct code surface color from the theme.
19/// <!-- default -->
20/// <!-- preview -->
21/// ```rust
22/// view! {
23///     <div data-testid="code-preview">
24///         <Code text="cargo leptos watch".to_string() />
25///     </div>
26/// }
27/// ```
28///
29/// ## Multi-line block
30/// Multi-line plain text for shell commands or config samples.
31/// <!-- preview -->
32/// ```rust
33/// view! {
34///     <div data-testid="code-multiline">
35///         <Code text="cargo leptos build --release\ncargo leptos serve".to_string() />
36///     </div>
37/// }
38/// ```
39#[component_doc(
40    category = "Typography",
41    preview_slug = "code",
42    preview_label = "Code",
43    preview_icon = icondata::AiCodeOutlined,
44)]
45#[component]
46pub fn Code(
47    /// Extra CSS class names merged onto the root `<code>` element.
48    #[prop(optional, into)]
49    class: MaybeProp<String>,
50    /// Plain-text snippet rendered inside `<pre>`.
51    #[prop(optional, into)]
52    text: Option<String>,
53    /// Pre-rendered markup for syntax highlighting; takes precedence over `text`.
54    #[prop(optional, into)]
55    inner_html: Option<String>,
56) -> impl IntoView {
57    inject_style("orbital-code", CODE_CSS);
58
59    let root_class = Memo::new(move |_| {
60        let extra = class.get().unwrap_or_default();
61        if extra.is_empty() {
62            "orbital-code".to_string()
63        } else {
64            format!("orbital-code {extra}")
65        }
66    });
67
68    view! {
69        <code class=root_class>
70            {if let Some(inner_html) = inner_html {
71                EitherOf3::A(view! { <pre inner_html=inner_html></pre> })
72            } else if let Some(text) = text {
73                EitherOf3::B(view! { <pre>{text}</pre> })
74            } else {
75                EitherOf3::C(())
76            }}
77        </code>
78    }
79}