lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! `Code` and `CodeTabs`: inline code, highlighted code blocks with a copy action, and tabbed code
//! examples.
// cspell:words figcaption

use std::cell::RefCell;
use std::collections::HashMap;

use dioxus::prelude::*;

use super::code_tokens::tokenize_code;
use super::copy::{CopyFeedback, CopyState, use_copy_feedback};
use crate::class::compose;
use crate::icons::{icon_svg, lucide};
use crate::{Tabs, TabsList, TabsPanel, TabsTrigger, Textarea};

/// Inline code or a code block.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum CodeVariant {
    /// An inline `<code>` element.
    #[default]
    Inline,
    /// A `<figure>` with an optional header, copy action, and highlighted `<pre>`.
    Block,
}

/// Header style of a block [`Code()`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum CodeAppearance {
    /// Window dots and an icon-only copy button.
    #[default]
    Default,
    /// A code symbol and a labelled copy button, for editorial pages.
    Editorial,
}

/// Syntax color theme of a [`Code()`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum CodeTheme {
    /// Follows the active Lumen theme.
    #[default]
    Auto,
    /// Lumen's syntax colors.
    Lumen,
    /// The santi020k syntax colors.
    Santi020k,
}

impl CodeTheme {
    /// The `data-code-theme` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Lumen => "lumen",
            Self::Santi020k => "santi020k",
        }
    }
}

/// Props for [`Code()`].
#[derive(Props, Clone, PartialEq)]
pub struct CodeProps {
    /// Inline code or a block.
    #[props(default)]
    pub variant: CodeVariant,
    /// Source text. Blocks tokenize it for highlighting; without it, `children` render as is.
    #[props(into)]
    pub code: Option<String>,
    /// Language used for highlighting and shown in the block header, such as `ts` or `bash`.
    #[props(into)]
    pub language: Option<String>,
    /// Text shown in the block header, such as a file name.
    #[props(into)]
    pub label: Option<String>,
    /// Adds a copy button to the block header.
    #[props(default)]
    pub copy: bool,
    /// Header style of a block.
    #[props(default)]
    pub appearance: CodeAppearance,
    /// Syntax color theme.
    #[props(default)]
    pub theme: CodeTheme,
    /// Wraps long lines instead of scrolling the block.
    #[props(default)]
    pub wrap: bool,
    /// Renders `children` as already highlighted markup, such as a `pre` from a build-time
    /// highlighter.
    #[props(default)]
    pub highlighted: bool,
    /// Accessible name of the scrollable code region. Defaults to "Code example".
    #[props(into)]
    pub code_label: Option<String>,
    /// Accessible name of the copy button. Defaults to "Copy code to clipboard".
    #[props(into)]
    pub copy_label: Option<String>,
    /// Name and announcement after a copy. Defaults to "Code copied to clipboard".
    #[props(into)]
    pub copied_label: Option<String>,
    /// Name and announcement after a failed copy.
    #[props(into)]
    pub error_label: Option<String>,
    /// Shows a read-only text area with the code after a failed copy, under this label.
    #[props(into)]
    pub recovery_label: Option<String>,
    /// Copies through the app instead of the browser clipboard. Called with the text; returns
    /// whether the copy succeeded. Use it on Dioxus Native.
    pub on_copy: Option<Callback<String, bool>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other global attribute, set on the `<code>` or `<figure>`.
    #[props(extends = GlobalAttributes)]
    pub attributes: Vec<Attribute>,
    /// Code content when `code` is not set.
    pub children: Element,
}

/// Resolved copy and region labels.
#[derive(Clone, PartialEq)]
struct CodeLabels {
    code: String,
    copy: String,
    copied: String,
    error: String,
    recovery: Option<String>,
}

impl CodeLabels {
    fn resolve(props: &CodeProps) -> Self {
        Self {
            code: props
                .code_label
                .clone()
                .unwrap_or_else(|| "Code example".into()),
            copy: props
                .copy_label
                .clone()
                .unwrap_or_else(|| "Copy code to clipboard".into()),
            copied: props
                .copied_label
                .clone()
                .unwrap_or_else(|| "Code copied to clipboard".into()),
            error: props
                .error_label
                .clone()
                .unwrap_or_else(|| "Could not copy code. Select and copy it manually.".into()),
            recovery: props.recovery_label.clone(),
        }
    }
}

/// Reads the text of the code block that holds the clicked copy button. A pointer click finds
/// the button under the pointer; keyboard activation uses the focused button.
const READ_CODE_SCRIPT: &str = "const [x, y] = await dioxus.recv();\
const start = (x || y) ? document.elementFromPoint(x, y) : document.activeElement;\
const root = start && start.closest ? start.closest('[data-ui-code]') : null;\
const content = root ? root.querySelector('pre code, code') : null;\
return content ? (content.innerText ?? content.textContent ?? null) : null;";

async fn read_code_text(x: f64, y: f64) -> Option<String> {
    let eval = document::eval(READ_CODE_SCRIPT);

    eval.send((x, y)).ok()?;
    eval.join::<Option<String>>().await.ok().flatten()
}

fn render_tokens(code: &str, language: Option<&str>) -> Element {
    let tokens = tokenize_code(code, language.unwrap_or(""));

    rsx! {
        for token in tokens {
            if let Some(kind) = token.kind {
                span { class: kind.class_name(), {token.value} }
            } else {
                {token.value}
            }
        }
    }
}

#[derive(Props, Clone, PartialEq)]
struct CodeCopyButtonProps {
    editorial: bool,
    code: Option<String>,
    labels: CodeLabels,
    on_copy: Option<Callback<String, bool>>,
}

#[component]
fn CodeCopyButton(props: CodeCopyButtonProps) -> Element {
    let feedback: CopyFeedback = use_copy_feedback(props.code.as_deref().unwrap_or(""));
    let state = feedback.state();
    let recovery = feedback.recovery();
    let labels = props.labels.clone();
    let accessible = match state {
        CopyState::Idle => labels.copy.clone(),
        CopyState::Copied => labels.copied.clone(),
        CopyState::Error => labels.error.clone(),
    };
    let status = match (state, &recovery, &labels.recovery) {
        (CopyState::Idle, _, _) => String::new(),
        (CopyState::Error, Some(_), Some(label)) => format!("{accessible} {label}"),
        _ => accessible.clone(),
    };
    let class = compose([
        Some("ui-code__copy"),
        (state == CopyState::Copied).then_some("ui-code__copy--copied"),
    ]);
    let (code, on_copy, keep_recovery) =
        (props.code.clone(), props.on_copy, labels.recovery.is_some());

    rsx! {
        button {
            aria_label: accessible.clone(),
            class,
            "data-state": state.as_str(),
            "data-ui-code-copy": "true",
            title: accessible.clone(),
            r#type: "button",
            onclick: move |event: MouseEvent| {
                let code = code.clone();
                let point = event.client_coordinates();

                spawn(async move {
                    let text = match code {
                        Some(code) => Some(code),
                        None => read_code_text(point.x, point.y).await,
                    };

                    feedback.copy(text, on_copy, keep_recovery);
                });
            },
            {icon_svg(&lucide::COPY, "ui-code__copy-icon")}
            {icon_svg(&lucide::CHECK, "ui-code__check-icon")}
            if props.editorial {
                span { class: "ui-code__copy-text", {accessible.clone()} }
            }
        }
        span { aria_live: "polite", class: "ui-sr-only", role: "status", {status} }
        if let (Some(label), Some(value)) = (labels.recovery.clone(), recovery) {
            label { class: "ui-code__recovery",
                span { {label.clone()} }
                Textarea { aria_label: label, readonly: true, rows: 3, value }
            }
        }
    }
}

/// Inline code, or a code block with syntax highlighting, a header, and an optional copy button.
///
/// Highlighting uses the same tokenizer as `lumen-core`, for JavaScript, TypeScript, JSON, Bash,
/// Lua, Markdown, HTML and other markup, SQL, and YAML.
#[component]
pub fn Code(props: CodeProps) -> Element {
    let labels = CodeLabels::resolve(&props);

    if props.variant == CodeVariant::Inline {
        let class = compose([Some("ui-code ui-code--inline"), props.class.as_deref()]);

        return rsx! {
            code {
                class,
                "data-code-theme": props.theme.as_str(),
                "data-language": props.language.clone(),
                "data-slot": "code",
                ..props.attributes,
                if let Some(code) = props.code.clone() {
                    {code}
                } else {
                    {props.children}
                }
            }
        };
    }

    let editorial = props.appearance == CodeAppearance::Editorial;
    let class = compose([
        Some("ui-code ui-code--block"),
        editorial.then_some("ui-code--editorial"),
        props.wrap.then_some("ui-code--wrap"),
        props.class.as_deref(),
    ]);
    let has_header = props.copy || props.label.is_some() || props.language.is_some();
    let region = !props.wrap;
    let body = match props.code.as_deref() {
        Some(code) => render_tokens(code, props.language.as_deref()),
        None => props.children.clone(),
    };

    rsx! {
        figure {
            class,
            "data-code-theme": props.theme.as_str(),
            "data-language": props.language.clone(),
            "data-slot": "code",
            "data-ui-code": "true",
            "data-ui-owner": "dioxus",
            ..props.attributes,
            if has_header {
                figcaption { class: "ui-code__header",
                    if editorial {
                        span { aria_hidden: "true", class: "ui-code__symbol",
                            {icon_svg(&lucide::CODE_XML, "ui-code__symbol-icon")}
                        }
                    } else {
                        span { aria_hidden: "true", class: "ui-code__dots",
                            span { class: "ui-code__dot ui-code__dot--red" }
                            span { class: "ui-code__dot ui-code__dot--yellow" }
                            span { class: "ui-code__dot ui-code__dot--green" }
                        }
                    }
                    span { class: "ui-code__meta",
                        if let Some(language) = props.language.clone() {
                            span { class: "ui-code__language", {language} }
                        }
                        if let Some(label) = props.label.clone() {
                            span { class: "ui-code__label", {label} }
                        }
                    }
                    if props.copy {
                        CodeCopyButton {
                            editorial,
                            code: props.code.clone(),
                            labels: labels.clone(),
                            on_copy: props.on_copy,
                        }
                    }
                }
            }
            if props.highlighted {
                div { {props.children} }
            } else {
                pre {
                    aria_label: region.then(|| labels.code.clone()),
                    role: region.then_some("region"),
                    tabindex: region.then_some("0"),
                    code { {body} }
                }
            }
        }
    }
}

/// One tab of a [`CodeTabs`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CodeTabsItem {
    /// Unique value of the tab.
    pub value: String,
    /// Tab label.
    pub label: String,
    /// Code shown in the panel.
    pub code: String,
    /// Highlighting language.
    pub language: Option<String>,
}

impl CodeTabsItem {
    /// A tab whose value and label are both `label`.
    pub fn new(label: impl Into<String>, code: impl Into<String>) -> Self {
        let label = label.into();

        Self {
            value: label.clone(),
            label,
            code: code.into(),
            language: None,
        }
    }

    /// Sets the highlighting language.
    #[must_use]
    pub fn language(mut self, language: impl Into<String>) -> Self {
        self.language = Some(language.into());
        self
    }
}

thread_local! {
    /// The last selection per storage key, for tabs mounted later in the same app.
    static CODE_TABS_STORE: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
}

/// The latest selection change: `(storage key, value, origin instance)`.
static CODE_TABS_SYNC: GlobalSignal<Option<(String, String, u64)>> = Signal::global(|| None);

fn stored_code_tab(key: &str) -> Option<String> {
    CODE_TABS_STORE.with(|store| store.borrow().get(key).cloned())
}

fn store_code_tab(key: &str, value: &str) {
    CODE_TABS_STORE.with(|store| {
        store
            .borrow_mut()
            .insert(key.to_string(), value.to_string());
    });
}

/// Writes the selection to `localStorage` on the web and desktop, like lumen-react.
const STORE_SCRIPT: &str = "const [key, value] = await dioxus.recv();\
try { localStorage.setItem(key, value); } catch (error) {} return true;";

/// Props for [`CodeTabs`].
#[derive(Props, Clone, PartialEq)]
pub struct CodeTabsProps {
    /// The tabs.
    #[props(default)]
    pub items: Vec<CodeTabsItem>,
    /// The tab selected first. Defaults to the first item.
    #[props(into)]
    pub initial_value: Option<String>,
    /// Shares the selection between `CodeTabs` with the same key, for example a package manager
    /// choice repeated across a page.
    #[props(into)]
    pub storage_key: Option<String>,
    /// Accessible name of the tab list. Defaults to "Code examples".
    #[props(default = "Code examples".to_string(), into)]
    pub aria_label: String,
    /// Adds a copy button to every panel. On by default.
    #[props(default = true)]
    pub copy: bool,
    /// Wraps long lines. On by default.
    #[props(default = true)]
    pub wrap: bool,
    /// Syntax color theme.
    #[props(default)]
    pub theme: CodeTheme,
    /// Accessible name of each scrollable code region.
    #[props(into)]
    pub code_label: Option<String>,
    /// Accessible name of the copy buttons.
    #[props(into)]
    pub copy_label: Option<String>,
    /// Name and announcement after a copy.
    #[props(into)]
    pub copied_label: Option<String>,
    /// Name and announcement after a failed copy.
    #[props(into)]
    pub error_label: Option<String>,
    /// Shows the code in a read-only text area after a failed copy, under this label.
    #[props(into)]
    pub recovery_label: Option<String>,
    /// Called with the newly selected tab value.
    pub on_value_change: Option<EventHandler<String>>,
    /// Copies through the app instead of the browser clipboard.
    pub on_copy: Option<Callback<String, bool>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
}

/// Tabbed code examples, such as the same install command for several package managers.
///
/// Tabs with the same `storage_key` stay in sync inside the app; on the web and desktop the
/// choice is also written to `localStorage` under that key.
#[component]
pub fn CodeTabs(props: CodeTabsProps) -> Element {
    let instance = use_hook(|| {
        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
        NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    });
    let items = props.items.clone();
    let has = |value: &str| items.iter().any(|item| item.value == value);
    let fallback = props
        .initial_value
        .clone()
        .or_else(|| items.first().map(|item| item.value.clone()))
        .unwrap_or_default();
    let mut selected = use_signal(|| {
        props
            .storage_key
            .as_deref()
            .and_then(stored_code_tab)
            .filter(|value| has(value))
            .unwrap_or_else(|| fallback.clone())
    });
    let mut generation = use_signal(|| 0_u64);
    let mut sync_config = use_hook(|| CopyValue::new((None::<String>, Vec::<String>::new())));

    sync_config.set((
        props.storage_key.clone(),
        items.iter().map(|item| item.value.clone()).collect(),
    ));

    // Follow selections made by other CodeTabs that share the storage key. The tabs remount with
    // the new selection, because `Tabs` keeps its own state.
    use_effect(move || {
        let Some((changed_key, value, origin)) = CODE_TABS_SYNC.read().clone() else {
            return;
        };
        let (key, values) = sync_config.read().clone();

        if key.as_deref() == Some(changed_key.as_str())
            && origin != instance
            && *selected.peek() != value
            && values.contains(&value)
        {
            selected.set(value);
            generation += 1;
        }
    });

    let storage_key = props.storage_key.clone();
    let on_value_change = props.on_value_change;
    let class = compose([Some("ui-code-tabs"), props.class.as_deref()]);
    let current = selected.peek().clone();
    let mut attributes = vec![Attribute::new("data-slot", "code-tabs", None, false)];

    if let Some(key) = storage_key.clone() {
        attributes.push(Attribute::new("data-storage-key", key, None, false));
    }

    attributes.extend(props.attributes.iter().cloned());

    rsx! {
        Tabs {
            key: "{generation}",
            class,
            default_value: current,
            on_value_change: move |value: String| {
                selected.set(value.clone());

                if let Some(key) = storage_key.clone() {
                    store_code_tab(&key, &value);
                    *CODE_TABS_SYNC.write() = Some((key.clone(), value.clone(), instance));
                    let eval = document::eval(STORE_SCRIPT);
                    let _ = eval.send((key, value.clone()));
                }

                if let Some(handler) = on_value_change {
                    handler.call(value);
                }
            },
            attributes,
            TabsList { aria_label: props.aria_label.clone(), class: "ui-code-tabs__list",
                for item in props.items.iter() {
                    TabsTrigger {
                        key: "{item.value}",
                        class: "ui-code-tabs__tab",
                        value: item.value.clone(),
                        {item.label.clone()}
                    }
                }
            }
            for item in props.items.iter() {
                TabsPanel {
                    key: "{item.value}",
                    class: "ui-code-tabs__panel",
                    value: item.value.clone(),
                    Code {
                        variant: CodeVariant::Block,
                        code: item.code.clone(),
                        language: item.language.clone(),
                        copy: props.copy,
                        wrap: props.wrap,
                        theme: props.theme,
                        code_label: props.code_label.clone(),
                        copy_label: props.copy_label.clone(),
                        copied_label: props.copied_label.clone(),
                        error_label: props.error_label.clone(),
                        recovery_label: props.recovery_label.clone(),
                        on_copy: props.on_copy,
                    }
                }
            }
        }
    }
}