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
//! `SecretValue`: a masked value, such as an API key, with reveal, hide, and copy actions.

use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::time::Duration;

use dioxus::prelude::*;

use super::copy::CopyAction;
use crate::class::compose;
use crate::hooks::use_unique_id;
use crate::{Button, ButtonSize, ButtonVariant, Spinner};

/// What a [`SecretValue`] shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SecretValueState {
    /// The mask.
    #[default]
    Hidden,
    /// Waiting for `load_value`.
    Loading,
    /// The value.
    Revealed,
    /// `load_value` failed.
    Error,
}

impl SecretValueState {
    /// The `data-state` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Hidden => "hidden",
            Self::Loading => "loading",
            Self::Revealed => "revealed",
            Self::Error => "error",
        }
    }
}

/// Text of a [`SecretValue`]. Unset or blank fields keep the English default.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SecretValueLabels {
    /// Visible copy action text; the accessible name appends the field label. Default: "Copy".
    pub copy: Option<String>,
    /// Feedback after a copy. Default: "Copied".
    pub copied: Option<String>,
    /// Feedback after a failed copy. Default: "Could not copy".
    pub copy_error: Option<String>,
    /// Shown when loading fails. Default: "Could not load the value."
    pub error: Option<String>,
    /// Read for the mask and announced after an automatic hide. Default: "Value hidden".
    pub hidden: Option<String>,
    /// Toggle text while revealed. Default: "Hide".
    pub hide: Option<String>,
    /// Announced while loading. Default: "Loading value".
    pub loading: Option<String>,
    /// Retry action text. Default: "Try again".
    pub retry: Option<String>,
    /// Toggle text while hidden. Default: "Show".
    pub show: Option<String>,
}

/// [`SecretValueLabels`] with the defaults filled in.
#[derive(Clone, Debug, PartialEq, Eq)]
struct ResolvedSecretLabels {
    copy: String,
    copied: String,
    copy_error: String,
    error: String,
    hidden: String,
    hide: String,
    loading: String,
    retry: String,
    show: String,
}

impl SecretValueLabels {
    fn resolve(&self) -> ResolvedSecretLabels {
        let pick = |value: &Option<String>, fallback: &str| {
            value
                .clone()
                .filter(|text| !text.trim().is_empty())
                .unwrap_or_else(|| fallback.to_string())
        };

        ResolvedSecretLabels {
            copy: pick(&self.copy, "Copy"),
            copied: pick(&self.copied, "Copied"),
            copy_error: pick(&self.copy_error, "Could not copy"),
            error: pick(&self.error, "Could not load the value."),
            hidden: pick(&self.hidden, "Value hidden"),
            hide: pick(&self.hide, "Hide"),
            loading: pick(&self.loading, "Loading value"),
            retry: pick(&self.retry, "Try again"),
            show: pick(&self.show, "Show"),
        }
    }
}

const DEFAULT_MASK_LENGTH: u32 = 8;
const MAX_MASK_LENGTH: u32 = 64;

/// The mask text. A fixed length keeps the mask from disclosing the secret's length.
pub(crate) fn secret_value_mask(mask: Option<&str>, mask_length: Option<u32>) -> String {
    if let Some(mask) = mask.filter(|mask| !mask.trim().is_empty()) {
        return mask.to_string();
    }

    let length = mask_length
        .filter(|length| *length > 0)
        .map_or(DEFAULT_MASK_LENGTH, |length| length.min(MAX_MASK_LENGTH));

    "\u{2022}".repeat(length as usize)
}

/// A positive, finite auto-hide delay in whole milliseconds; anything else disables it.
pub(crate) fn secret_value_auto_hide(value: Option<f64>) -> Option<Duration> {
    let millis = value.filter(|value| value.is_finite() && *value > 0.0)?;

    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "the delay is positive and rounded; f64 to u64 saturates at u64::MAX"
    )]
    let rounded = millis.round() as u64;

    Some(Duration::from_millis(rounded))
}

/// The future `load_value` returns: the secret, or an error message for `on_load_error`.
pub type SecretValueFuture = Pin<Box<dyn Future<Output = Result<String, String>>>>;

/// Props for [`SecretValue`].
#[derive(Props, Clone, PartialEq)]
pub struct SecretValueProps {
    /// Visible label that names the group.
    #[props(into)]
    pub label: String,
    /// A value already available to the app. It is rendered only while revealed.
    #[props(into)]
    pub value: Option<String>,
    /// Loads the value on reveal, for values that should stay on the server until requested.
    /// Return `Box::pin(async move { ... })`.
    pub load_value: Option<Callback<(), SecretValueFuture>>,
    /// Keeps a loaded value in memory after hiding, so the next reveal skips `load_value`.
    #[props(default)]
    pub cache_on_hide: bool,
    /// Offers a copy action while revealed. On by default.
    #[props(default = true)]
    pub copy: bool,
    /// Hides a revealed value after this many milliseconds.
    pub auto_hide_after: Option<f64>,
    /// Custom mask text.
    #[props(into)]
    pub mask: Option<String>,
    /// Number of mask characters, 1 to 64. Defaults to 8.
    pub mask_length: Option<u32>,
    /// Text of the actions and announcements.
    #[props(default)]
    pub labels: SecretValueLabels,
    /// Receives load failures. Lumen never logs them, because they may contain sensitive output.
    pub on_load_error: Option<EventHandler<String>>,
    /// Called when the state changes.
    pub on_state_change: Option<EventHandler<SecretValueState>>,
    /// Copies through the app instead of the browser clipboard. Use it on Dioxus Native.
    pub on_copy: Option<Callback<String, bool>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
}

/// A masked secret with Show and Hide, an optional copy action, and an optional automatic hide.
///
/// While masked, the value is not in the markup, so neither the accessibility tree nor text
/// selection can reach it.
#[component]
pub fn SecretValue(props: SecretValueProps) -> Element {
    let id = use_unique_id();
    let label_id = format!("{id}-label");
    let display_id = format!("{id}-display");
    let toggle_label_id = format!("{id}-toggle-label");
    let labels = props.labels.resolve();
    let mut state = use_signal(SecretValueState::default);
    let mut loaded = use_signal(|| None::<String>);
    let mut status = use_signal(String::new);
    let mut cache = use_hook(|| CopyValue::new(None::<String>));
    let mut operation = use_signal(|| 0_u64);
    let mut toggle = use_signal(|| None::<Rc<MountedData>>);
    let mut reported = use_signal(SecretValueState::default);
    let auto_hide = secret_value_auto_hide(props.auto_hide_after);
    let cache_on_hide = props.cache_on_hide;
    let (value, load_value, on_load_error) =
        (props.value.clone(), props.load_value, props.on_load_error);
    let on_state_change = props.on_state_change;
    let (hidden_label, loading_label) = (labels.hidden.clone(), labels.loading.clone());
    let current = state();

    let mut hide = move |automatic: bool| {
        operation += 1;

        if !cache_on_hide {
            cache.set(None);
        }

        loaded.set(None);
        status.set(if automatic {
            hidden_label.clone()
        } else {
            String::new()
        });
        state.set(SecretValueState::Hidden);
    };

    let reveal = move || {
        operation += 1;
        let request = *operation.peek();

        status.set(String::new());

        if value.is_some() {
            state.set(SecretValueState::Revealed);
            return;
        }

        if let Some(cached) = cache.read().clone() {
            loaded.set(Some(cached));
            state.set(SecretValueState::Revealed);
            return;
        }

        state.set(SecretValueState::Loading);
        status.set(loading_label.clone());

        spawn(async move {
            let result = match load_value {
                Some(load) => load.call(()).await,
                None => Err("SecretValue needs a value or load_value.".to_string()),
            };

            if *operation.peek() != request {
                return;
            }

            status.set(String::new());

            match result {
                Ok(next) => {
                    if cache_on_hide {
                        cache.set(Some(next.clone()));
                    }

                    loaded.set(Some(next));
                    state.set(SecretValueState::Revealed);
                }
                Err(error) => {
                    state.set(SecretValueState::Error);

                    if let Some(handler) = on_load_error {
                        handler.call(error);
                    }
                }
            }
        });
    };

    use_effect(move || {
        let next = state();

        if *reported.peek() != next {
            reported.set(next);

            if let Some(handler) = on_state_change {
                handler.call(next);
            }
        }
    });

    // Hide automatically after the delay, unless another action happened in between.
    let hide_later = hide.clone();
    use_effect(use_reactive(
        (&current, &auto_hide),
        move |(current, auto_hide)| {
            if current != SecretValueState::Revealed {
                return;
            }

            let Some(delay) = auto_hide else { return };
            let request = *operation.peek();
            let mut hide = hide_later.clone();

            spawn(async move {
                crate::time::sleep(delay).await;

                if *operation.peek() == request && *state.peek() == SecretValueState::Revealed {
                    hide(true);
                }
            });
        },
    ));

    let revealed = current == SecretValueState::Revealed;
    let secret = if revealed {
        props.value.clone().or_else(|| loaded.cloned())
    } else {
        None
    };
    let expanded = current != SecretValueState::Hidden;
    let class = compose([Some("ui-secret-value"), props.class.as_deref()]);
    let copy_label = format!("{} {}", labels.copy, props.label)
        .trim()
        .to_string();
    let mut reveal_from_toggle = reveal.clone();
    let mut reveal_from_retry = reveal.clone();

    rsx! {
        div {
            aria_busy: (current == SecretValueState::Loading).then_some("true"),
            aria_labelledby: label_id.clone(),
            class,
            "data-slot": "secret-value",
            "data-state": current.as_str(),
            "data-ui-owner": "dioxus",
            "data-ui-secret-value": "",
            role: "group",
            ..props.attributes,
            span { class: "ui-secret-value__label", "data-slot": "secret-value-label", id: label_id.clone(), {props.label.clone()} }
            span { class: "ui-secret-value__display", "data-slot": "secret-value-display", id: display_id.clone(),
                span {
                    aria_hidden: "true",
                    class: "ui-secret-value__mask",
                    "data-slot": "secret-value-mask",
                    hidden: revealed,
                    {secret_value_mask(props.mask.as_deref(), props.mask_length)}
                }
                span { class: "ui-sr-only", "data-slot": "secret-value-hidden-text", hidden: revealed, {labels.hidden.clone()} }
                Spinner {
                    hidden: current != SecretValueState::Loading,
                    attributes: vec![Attribute::new("data-slot", "secret-value-spinner", None, false)],
                }
                span { class: "ui-secret-value__text", "data-slot": "secret-value-text", hidden: !revealed,
                    if let Some(secret) = secret.clone() {
                        {secret}
                    }
                }
            }
            span { class: "ui-secret-value__actions", "data-slot": "secret-value-actions",
                button {
                    aria_controls: display_id,
                    aria_expanded: if expanded { "true" } else { "false" },
                    aria_labelledby: format!("{toggle_label_id} {label_id}"),
                    class: "ui-button ui-button--outline ui-button--sm",
                    "data-slot": "button",
                    "data-ui-secret-value-toggle": "",
                    r#type: "button",
                    onmounted: move |event| toggle.set(Some(event.data())),
                    onclick: move |_| {
                        if *state.peek() == SecretValueState::Hidden {
                            reveal_from_toggle();
                        } else {
                            hide(false);
                        }
                    },
                    span { class: "ui-button__content",
                        span { "data-slot": "secret-value-toggle-label", id: toggle_label_id,
                            if expanded { {labels.hide.clone()} } else { {labels.show.clone()} }
                        }
                    }
                }
                if let Some(secret) = secret.filter(|_| props.copy) {
                    span { "data-slot": "secret-value-copy",
                        CopyAction {
                            value: secret,
                            label: copy_label,
                            copied_label: labels.copied.clone(),
                            error_label: labels.copy_error.clone(),
                            class: "",
                            variant_class: "ui-button--outline",
                            on_copy: props.on_copy,
                            {labels.copy.clone()}
                        }
                    }
                }
            }
            span {
                aria_atomic: "true",
                aria_live: "polite",
                class: "ui-sr-only",
                "data-slot": "secret-value-status",
                role: "status",
                {status()}
            }
            div {
                class: "ui-secret-value__error",
                "data-slot": "secret-value-error",
                hidden: current != SecretValueState::Error,
                role: "alert",
                if current == SecretValueState::Error {
                    span { "data-slot": "secret-value-error-message", {labels.error.clone()} }
                    Button {
                        size: ButtonSize::Sm,
                        variant: ButtonVariant::Outline,
                        onclick: move |_| {
                            if let Some(node) = toggle.peek().clone() {
                                spawn(async move {
                                    let _ = node.set_focus(true).await;
                                });
                            }

                            reveal_from_retry();
                        },
                        attributes: vec![Attribute::new("data-ui-secret-value-retry", "", None, false)],
                        {labels.retry.clone()}
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::{SecretValueLabels, secret_value_auto_hide, secret_value_mask};

    #[test]
    fn masks_have_a_fixed_length() {
        assert_eq!(secret_value_mask(None, None), "\u{2022}".repeat(8));
        assert_eq!(secret_value_mask(None, Some(4)), "\u{2022}".repeat(4));
        assert_eq!(secret_value_mask(None, Some(0)), "\u{2022}".repeat(8));
        assert_eq!(secret_value_mask(None, Some(500)), "\u{2022}".repeat(64));
        assert_eq!(secret_value_mask(Some("****"), Some(2)), "****");
        assert_eq!(secret_value_mask(Some("  "), Some(2)), "\u{2022}".repeat(2));
    }

    #[test]
    fn auto_hide_needs_a_positive_delay() {
        assert_eq!(
            secret_value_auto_hide(Some(1500.4)),
            Some(Duration::from_millis(1500))
        );
        assert_eq!(secret_value_auto_hide(Some(0.0)), None);
        assert_eq!(secret_value_auto_hide(Some(-5.0)), None);
        assert_eq!(secret_value_auto_hide(Some(f64::NAN)), None);
        assert_eq!(secret_value_auto_hide(None), None);
    }

    #[test]
    fn labels_ignore_blank_overrides() {
        let labels = SecretValueLabels {
            show: Some("Reveal".into()),
            hide: Some("  ".into()),
            ..SecretValueLabels::default()
        }
        .resolve();

        assert_eq!(labels.show, "Reveal");
        assert_eq!(labels.hide, "Hide");
        assert_eq!(labels.copy_error, "Could not copy");
    }
}