Skip to main content

lumen_dioxus/content/
code.rs

1//! `Code` and `CodeTabs`: inline code, highlighted code blocks with a copy action, and tabbed code
2//! examples.
3// cspell:words figcaption
4
5use std::cell::RefCell;
6use std::collections::HashMap;
7
8use dioxus::prelude::*;
9
10use super::code_tokens::tokenize_code;
11use super::copy::{CopyFeedback, CopyState, use_copy_feedback};
12use crate::class::compose;
13use crate::icons::{icon_svg, lucide};
14use crate::{Tabs, TabsList, TabsPanel, TabsTrigger, Textarea};
15
16/// Inline code or a code block.
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
18#[non_exhaustive]
19pub enum CodeVariant {
20    /// An inline `<code>` element.
21    #[default]
22    Inline,
23    /// A `<figure>` with an optional header, copy action, and highlighted `<pre>`.
24    Block,
25}
26
27/// Header style of a block [`Code()`].
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum CodeAppearance {
31    /// Window dots and an icon-only copy button.
32    #[default]
33    Default,
34    /// A code symbol and a labelled copy button, for editorial pages.
35    Editorial,
36}
37
38/// Syntax color theme of a [`Code()`].
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum CodeTheme {
42    /// Follows the active Lumen theme.
43    #[default]
44    Auto,
45    /// Lumen's syntax colors.
46    Lumen,
47    /// The santi020k syntax colors.
48    Santi020k,
49}
50
51impl CodeTheme {
52    /// The `data-code-theme` value.
53    pub fn as_str(self) -> &'static str {
54        match self {
55            Self::Auto => "auto",
56            Self::Lumen => "lumen",
57            Self::Santi020k => "santi020k",
58        }
59    }
60}
61
62/// Props for [`Code()`].
63#[derive(Props, Clone, PartialEq)]
64pub struct CodeProps {
65    /// Inline code or a block.
66    #[props(default)]
67    pub variant: CodeVariant,
68    /// Source text. Blocks tokenize it for highlighting; without it, `children` render as is.
69    #[props(into)]
70    pub code: Option<String>,
71    /// Language used for highlighting and shown in the block header, such as `ts` or `bash`.
72    #[props(into)]
73    pub language: Option<String>,
74    /// Text shown in the block header, such as a file name.
75    #[props(into)]
76    pub label: Option<String>,
77    /// Adds a copy button to the block header.
78    #[props(default)]
79    pub copy: bool,
80    /// Header style of a block.
81    #[props(default)]
82    pub appearance: CodeAppearance,
83    /// Syntax color theme.
84    #[props(default)]
85    pub theme: CodeTheme,
86    /// Wraps long lines instead of scrolling the block.
87    #[props(default)]
88    pub wrap: bool,
89    /// Renders `children` as already highlighted markup, such as a `pre` from a build-time
90    /// highlighter.
91    #[props(default)]
92    pub highlighted: bool,
93    /// Accessible name of the scrollable code region. Defaults to "Code example".
94    #[props(into)]
95    pub code_label: Option<String>,
96    /// Accessible name of the copy button. Defaults to "Copy code to clipboard".
97    #[props(into)]
98    pub copy_label: Option<String>,
99    /// Name and announcement after a copy. Defaults to "Code copied to clipboard".
100    #[props(into)]
101    pub copied_label: Option<String>,
102    /// Name and announcement after a failed copy.
103    #[props(into)]
104    pub error_label: Option<String>,
105    /// Shows a read-only text area with the code after a failed copy, under this label.
106    #[props(into)]
107    pub recovery_label: Option<String>,
108    /// Copies through the app instead of the browser clipboard. Called with the text; returns
109    /// whether the copy succeeded. Use it on Dioxus Native.
110    pub on_copy: Option<Callback<String, bool>>,
111    /// Extra classes appended after the Lumen classes.
112    #[props(into)]
113    pub class: Option<String>,
114    /// Any other global attribute, set on the `<code>` or `<figure>`.
115    #[props(extends = GlobalAttributes)]
116    pub attributes: Vec<Attribute>,
117    /// Code content when `code` is not set.
118    pub children: Element,
119}
120
121/// Resolved copy and region labels.
122#[derive(Clone, PartialEq)]
123struct CodeLabels {
124    code: String,
125    copy: String,
126    copied: String,
127    error: String,
128    recovery: Option<String>,
129}
130
131impl CodeLabels {
132    fn resolve(props: &CodeProps) -> Self {
133        Self {
134            code: props
135                .code_label
136                .clone()
137                .unwrap_or_else(|| "Code example".into()),
138            copy: props
139                .copy_label
140                .clone()
141                .unwrap_or_else(|| "Copy code to clipboard".into()),
142            copied: props
143                .copied_label
144                .clone()
145                .unwrap_or_else(|| "Code copied to clipboard".into()),
146            error: props
147                .error_label
148                .clone()
149                .unwrap_or_else(|| "Could not copy code. Select and copy it manually.".into()),
150            recovery: props.recovery_label.clone(),
151        }
152    }
153}
154
155/// Reads the text of the code block that holds the clicked copy button. A pointer click finds
156/// the button under the pointer; keyboard activation uses the focused button.
157const READ_CODE_SCRIPT: &str = "const [x, y] = await dioxus.recv();\
158const start = (x || y) ? document.elementFromPoint(x, y) : document.activeElement;\
159const root = start && start.closest ? start.closest('[data-ui-code]') : null;\
160const content = root ? root.querySelector('pre code, code') : null;\
161return content ? (content.innerText ?? content.textContent ?? null) : null;";
162
163async fn read_code_text(x: f64, y: f64) -> Option<String> {
164    let eval = document::eval(READ_CODE_SCRIPT);
165
166    eval.send((x, y)).ok()?;
167    eval.join::<Option<String>>().await.ok().flatten()
168}
169
170fn render_tokens(code: &str, language: Option<&str>) -> Element {
171    let tokens = tokenize_code(code, language.unwrap_or(""));
172
173    rsx! {
174        for token in tokens {
175            if let Some(kind) = token.kind {
176                span { class: kind.class_name(), {token.value} }
177            } else {
178                {token.value}
179            }
180        }
181    }
182}
183
184#[derive(Props, Clone, PartialEq)]
185struct CodeCopyButtonProps {
186    editorial: bool,
187    code: Option<String>,
188    labels: CodeLabels,
189    on_copy: Option<Callback<String, bool>>,
190}
191
192#[component]
193fn CodeCopyButton(props: CodeCopyButtonProps) -> Element {
194    let feedback: CopyFeedback = use_copy_feedback(props.code.as_deref().unwrap_or(""));
195    let state = feedback.state();
196    let recovery = feedback.recovery();
197    let labels = props.labels.clone();
198    let accessible = match state {
199        CopyState::Idle => labels.copy.clone(),
200        CopyState::Copied => labels.copied.clone(),
201        CopyState::Error => labels.error.clone(),
202    };
203    let status = match (state, &recovery, &labels.recovery) {
204        (CopyState::Idle, _, _) => String::new(),
205        (CopyState::Error, Some(_), Some(label)) => format!("{accessible} {label}"),
206        _ => accessible.clone(),
207    };
208    let class = compose([
209        Some("ui-code__copy"),
210        (state == CopyState::Copied).then_some("ui-code__copy--copied"),
211    ]);
212    let (code, on_copy, keep_recovery) =
213        (props.code.clone(), props.on_copy, labels.recovery.is_some());
214
215    rsx! {
216        button {
217            aria_label: accessible.clone(),
218            class,
219            "data-state": state.as_str(),
220            "data-ui-code-copy": "true",
221            title: accessible.clone(),
222            r#type: "button",
223            onclick: move |event: MouseEvent| {
224                let code = code.clone();
225                let point = event.client_coordinates();
226
227                spawn(async move {
228                    let text = match code {
229                        Some(code) => Some(code),
230                        None => read_code_text(point.x, point.y).await,
231                    };
232
233                    feedback.copy(text, on_copy, keep_recovery);
234                });
235            },
236            {icon_svg(&lucide::COPY, "ui-code__copy-icon")}
237            {icon_svg(&lucide::CHECK, "ui-code__check-icon")}
238            if props.editorial {
239                span { class: "ui-code__copy-text", {accessible.clone()} }
240            }
241        }
242        span { aria_live: "polite", class: "ui-sr-only", role: "status", {status} }
243        if let (Some(label), Some(value)) = (labels.recovery.clone(), recovery) {
244            label { class: "ui-code__recovery",
245                span { {label.clone()} }
246                Textarea { aria_label: label, readonly: true, rows: 3, value }
247            }
248        }
249    }
250}
251
252/// Inline code, or a code block with syntax highlighting, a header, and an optional copy button.
253///
254/// Highlighting uses the same tokenizer as `lumen-core`, for JavaScript, TypeScript, JSON, Bash,
255/// Lua, Markdown, HTML and other markup, SQL, and YAML.
256#[component]
257pub fn Code(props: CodeProps) -> Element {
258    let labels = CodeLabels::resolve(&props);
259
260    if props.variant == CodeVariant::Inline {
261        let class = compose([Some("ui-code ui-code--inline"), props.class.as_deref()]);
262
263        return rsx! {
264            code {
265                class,
266                "data-code-theme": props.theme.as_str(),
267                "data-language": props.language.clone(),
268                "data-slot": "code",
269                ..props.attributes,
270                if let Some(code) = props.code.clone() {
271                    {code}
272                } else {
273                    {props.children}
274                }
275            }
276        };
277    }
278
279    let editorial = props.appearance == CodeAppearance::Editorial;
280    let class = compose([
281        Some("ui-code ui-code--block"),
282        editorial.then_some("ui-code--editorial"),
283        props.wrap.then_some("ui-code--wrap"),
284        props.class.as_deref(),
285    ]);
286    let has_header = props.copy || props.label.is_some() || props.language.is_some();
287    let region = !props.wrap;
288    let body = match props.code.as_deref() {
289        Some(code) => render_tokens(code, props.language.as_deref()),
290        None => props.children.clone(),
291    };
292
293    rsx! {
294        figure {
295            class,
296            "data-code-theme": props.theme.as_str(),
297            "data-language": props.language.clone(),
298            "data-slot": "code",
299            "data-ui-code": "true",
300            "data-ui-owner": "dioxus",
301            ..props.attributes,
302            if has_header {
303                figcaption { class: "ui-code__header",
304                    if editorial {
305                        span { aria_hidden: "true", class: "ui-code__symbol",
306                            {icon_svg(&lucide::CODE_XML, "ui-code__symbol-icon")}
307                        }
308                    } else {
309                        span { aria_hidden: "true", class: "ui-code__dots",
310                            span { class: "ui-code__dot ui-code__dot--red" }
311                            span { class: "ui-code__dot ui-code__dot--yellow" }
312                            span { class: "ui-code__dot ui-code__dot--green" }
313                        }
314                    }
315                    span { class: "ui-code__meta",
316                        if let Some(language) = props.language.clone() {
317                            span { class: "ui-code__language", {language} }
318                        }
319                        if let Some(label) = props.label.clone() {
320                            span { class: "ui-code__label", {label} }
321                        }
322                    }
323                    if props.copy {
324                        CodeCopyButton {
325                            editorial,
326                            code: props.code.clone(),
327                            labels: labels.clone(),
328                            on_copy: props.on_copy,
329                        }
330                    }
331                }
332            }
333            if props.highlighted {
334                div { {props.children} }
335            } else {
336                pre {
337                    aria_label: region.then(|| labels.code.clone()),
338                    role: region.then_some("region"),
339                    tabindex: region.then_some("0"),
340                    code { {body} }
341                }
342            }
343        }
344    }
345}
346
347/// One tab of a [`CodeTabs`].
348#[derive(Clone, Debug, Default, PartialEq, Eq)]
349pub struct CodeTabsItem {
350    /// Unique value of the tab.
351    pub value: String,
352    /// Tab label.
353    pub label: String,
354    /// Code shown in the panel.
355    pub code: String,
356    /// Highlighting language.
357    pub language: Option<String>,
358}
359
360impl CodeTabsItem {
361    /// A tab whose value and label are both `label`.
362    pub fn new(label: impl Into<String>, code: impl Into<String>) -> Self {
363        let label = label.into();
364
365        Self {
366            value: label.clone(),
367            label,
368            code: code.into(),
369            language: None,
370        }
371    }
372
373    /// Sets the highlighting language.
374    #[must_use]
375    pub fn language(mut self, language: impl Into<String>) -> Self {
376        self.language = Some(language.into());
377        self
378    }
379}
380
381thread_local! {
382    /// The last selection per storage key, for tabs mounted later in the same app.
383    static CODE_TABS_STORE: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
384}
385
386/// The latest selection change: `(storage key, value, origin instance)`.
387static CODE_TABS_SYNC: GlobalSignal<Option<(String, String, u64)>> = Signal::global(|| None);
388
389fn stored_code_tab(key: &str) -> Option<String> {
390    CODE_TABS_STORE.with(|store| store.borrow().get(key).cloned())
391}
392
393fn store_code_tab(key: &str, value: &str) {
394    CODE_TABS_STORE.with(|store| {
395        store
396            .borrow_mut()
397            .insert(key.to_string(), value.to_string());
398    });
399}
400
401/// Writes the selection to `localStorage` on the web and desktop, like lumen-react.
402const STORE_SCRIPT: &str = "const [key, value] = await dioxus.recv();\
403try { localStorage.setItem(key, value); } catch (error) {} return true;";
404
405/// Props for [`CodeTabs`].
406#[derive(Props, Clone, PartialEq)]
407pub struct CodeTabsProps {
408    /// The tabs.
409    #[props(default)]
410    pub items: Vec<CodeTabsItem>,
411    /// The tab selected first. Defaults to the first item.
412    #[props(into)]
413    pub initial_value: Option<String>,
414    /// Shares the selection between `CodeTabs` with the same key, for example a package manager
415    /// choice repeated across a page.
416    #[props(into)]
417    pub storage_key: Option<String>,
418    /// Accessible name of the tab list. Defaults to "Code examples".
419    #[props(default = "Code examples".to_string(), into)]
420    pub aria_label: String,
421    /// Adds a copy button to every panel. On by default.
422    #[props(default = true)]
423    pub copy: bool,
424    /// Wraps long lines. On by default.
425    #[props(default = true)]
426    pub wrap: bool,
427    /// Syntax color theme.
428    #[props(default)]
429    pub theme: CodeTheme,
430    /// Accessible name of each scrollable code region.
431    #[props(into)]
432    pub code_label: Option<String>,
433    /// Accessible name of the copy buttons.
434    #[props(into)]
435    pub copy_label: Option<String>,
436    /// Name and announcement after a copy.
437    #[props(into)]
438    pub copied_label: Option<String>,
439    /// Name and announcement after a failed copy.
440    #[props(into)]
441    pub error_label: Option<String>,
442    /// Shows the code in a read-only text area after a failed copy, under this label.
443    #[props(into)]
444    pub recovery_label: Option<String>,
445    /// Called with the newly selected tab value.
446    pub on_value_change: Option<EventHandler<String>>,
447    /// Copies through the app instead of the browser clipboard.
448    pub on_copy: Option<Callback<String, bool>>,
449    /// Extra classes appended after the Lumen classes.
450    #[props(into)]
451    pub class: Option<String>,
452    /// Any other `<div>` or global attribute.
453    #[props(extends = GlobalAttributes, extends = div)]
454    pub attributes: Vec<Attribute>,
455}
456
457/// Tabbed code examples, such as the same install command for several package managers.
458///
459/// Tabs with the same `storage_key` stay in sync inside the app; on the web and desktop the
460/// choice is also written to `localStorage` under that key.
461#[component]
462pub fn CodeTabs(props: CodeTabsProps) -> Element {
463    let instance = use_hook(|| {
464        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
465        NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
466    });
467    let items = props.items.clone();
468    let has = |value: &str| items.iter().any(|item| item.value == value);
469    let fallback = props
470        .initial_value
471        .clone()
472        .or_else(|| items.first().map(|item| item.value.clone()))
473        .unwrap_or_default();
474    let mut selected = use_signal(|| {
475        props
476            .storage_key
477            .as_deref()
478            .and_then(stored_code_tab)
479            .filter(|value| has(value))
480            .unwrap_or_else(|| fallback.clone())
481    });
482    let mut generation = use_signal(|| 0_u64);
483    let mut sync_config = use_hook(|| CopyValue::new((None::<String>, Vec::<String>::new())));
484
485    sync_config.set((
486        props.storage_key.clone(),
487        items.iter().map(|item| item.value.clone()).collect(),
488    ));
489
490    // Follow selections made by other CodeTabs that share the storage key. The tabs remount with
491    // the new selection, because `Tabs` keeps its own state.
492    use_effect(move || {
493        let Some((changed_key, value, origin)) = CODE_TABS_SYNC.read().clone() else {
494            return;
495        };
496        let (key, values) = sync_config.read().clone();
497
498        if key.as_deref() == Some(changed_key.as_str())
499            && origin != instance
500            && *selected.peek() != value
501            && values.contains(&value)
502        {
503            selected.set(value);
504            generation += 1;
505        }
506    });
507
508    let storage_key = props.storage_key.clone();
509    let on_value_change = props.on_value_change;
510    let class = compose([Some("ui-code-tabs"), props.class.as_deref()]);
511    let current = selected.peek().clone();
512    let mut attributes = vec![Attribute::new("data-slot", "code-tabs", None, false)];
513
514    if let Some(key) = storage_key.clone() {
515        attributes.push(Attribute::new("data-storage-key", key, None, false));
516    }
517
518    attributes.extend(props.attributes.iter().cloned());
519
520    rsx! {
521        Tabs {
522            key: "{generation}",
523            class,
524            default_value: current,
525            on_value_change: move |value: String| {
526                selected.set(value.clone());
527
528                if let Some(key) = storage_key.clone() {
529                    store_code_tab(&key, &value);
530                    *CODE_TABS_SYNC.write() = Some((key.clone(), value.clone(), instance));
531                    let eval = document::eval(STORE_SCRIPT);
532                    let _ = eval.send((key, value.clone()));
533                }
534
535                if let Some(handler) = on_value_change {
536                    handler.call(value);
537                }
538            },
539            attributes,
540            TabsList { aria_label: props.aria_label.clone(), class: "ui-code-tabs__list",
541                for item in props.items.iter() {
542                    TabsTrigger {
543                        key: "{item.value}",
544                        class: "ui-code-tabs__tab",
545                        value: item.value.clone(),
546                        {item.label.clone()}
547                    }
548                }
549            }
550            for item in props.items.iter() {
551                TabsPanel {
552                    key: "{item.value}",
553                    class: "ui-code-tabs__panel",
554                    value: item.value.clone(),
555                    Code {
556                        variant: CodeVariant::Block,
557                        code: item.code.clone(),
558                        language: item.language.clone(),
559                        copy: props.copy,
560                        wrap: props.wrap,
561                        theme: props.theme,
562                        code_label: props.code_label.clone(),
563                        copy_label: props.copy_label.clone(),
564                        copied_label: props.copied_label.clone(),
565                        error_label: props.error_label.clone(),
566                        recovery_label: props.recovery_label.clone(),
567                        on_copy: props.on_copy,
568                    }
569                }
570            }
571        }
572    }
573}