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
//! `SelectionBar`, plus the plural count copy and throttled announcer it shares with `LoadMore`.
// cspell:words subtag CLDR cldr

use std::time::Duration;

use dioxus::prelude::*;

use crate::class::compose;
use crate::time::sleep;

use super::util::format_template;

/// A plural category, as `Intl.PluralRules` names them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SelectionBarPlural {
    /// Zero items, in locales that have the category.
    Zero,
    /// One item.
    One,
    /// Two items.
    Two,
    /// A few items.
    Few,
    /// Many items.
    Many,
    /// Every other count.
    Other,
}

/// The language subtag of a locale, lowercased (`pt-BR` is `pt`).
fn language(locale: &str) -> String {
    locale
        .split(['-', '_'])
        .next()
        .unwrap_or_default()
        .to_ascii_lowercase()
}

/// The plural category of a whole count, following CLDR cardinal rules for common languages.
/// Unknown languages use the English rule.
pub fn selection_bar_plural(count: u64, locale: &str) -> SelectionBarPlural {
    use SelectionBarPlural::{Few, Many, One, Other, Two, Zero};

    let tens = count % 100;
    let units = count % 10;

    match language(locale).as_str() {
        "ja" | "zh" | "ko" | "th" | "vi" | "id" | "ms" | "lo" | "my" | "km" => Other,
        "fr" | "pt" => {
            if count <= 1 {
                One
            } else {
                Other
            }
        }
        "ru" | "uk" | "be" => match (units, tens) {
            (1, t) if t != 11 => One,
            (2..=4, t) if !(12..=14).contains(&t) => Few,
            _ => Many,
        },
        "pl" => match (count, units, tens) {
            (1, _, _) => One,
            (_, 2..=4, t) if !(12..=14).contains(&t) => Few,
            _ => Many,
        },
        "cs" | "sk" => match count {
            1 => One,
            2..=4 => Few,
            _ => Other,
        },
        "ar" => match (count, tens) {
            (0, _) => Zero,
            (1, _) => One,
            (2, _) => Two,
            (_, 3..=10) => Few,
            (_, 11..=99) => Many,
            _ => Other,
        },
        _ => {
            if count == 1 {
                One
            } else {
                Other
            }
        }
    }
}

/// Formats a count with the locale's digit grouping, like `Intl.NumberFormat` for whole numbers
/// in common languages.
pub fn selection_bar_format_count(count: u64, locale: &str) -> String {
    let digits = count.to_string();
    let lang = language(locale);
    let (separator, min_digits) = match lang.as_str() {
        "de" | "it" | "nl" | "da" | "id" | "tr" | "el" | "pt" => (".", 4),
        "es" => (".", 5),
        "fr" => ("\u{202f}", 4),
        "pl" => ("\u{a0}", 5),
        "ru" | "uk" | "cs" | "sk" | "sv" | "fi" | "nb" | "be" => ("\u{a0}", 4),
        _ => (",", 4),
    };

    if digits.len() < min_digits {
        return digits;
    }

    let mut out = String::with_capacity(digits.len() + digits.len() / 3 * 3);

    for (index, character) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index).is_multiple_of(3) {
            out.push_str(separator);
        }

        out.push(character);
    }

    out
}

/// Count copy for a [`SelectionBar`] or `LoadMore`. `{count}` is the formatted count. Forms
/// that are unset fall back to `other`; `zero` applies to 0 even where the locale has no zero
/// category, as in English.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SelectionBarCountLabel {
    /// Form for 0.
    pub zero: Option<String>,
    /// Form for the `one` category.
    pub one: Option<String>,
    /// Form for the `two` category.
    pub two: Option<String>,
    /// Form for the `few` category.
    pub few: Option<String>,
    /// Form for the `many` category.
    pub many: Option<String>,
    /// Form for every other count, and the fallback.
    pub other: Option<String>,
}

impl SelectionBarCountLabel {
    /// One template for every count.
    pub fn new(template: impl Into<String>) -> Self {
        Self {
            other: Some(template.into()),
            ..Self::default()
        }
    }

    /// Separate singular and plural templates.
    pub fn plural(one: impl Into<String>, other: impl Into<String>) -> Self {
        Self {
            one: Some(one.into()),
            other: Some(other.into()),
            ..Self::default()
        }
    }

    fn form(&self, category: SelectionBarPlural) -> Option<&String> {
        match category {
            SelectionBarPlural::Zero => self.zero.as_ref(),
            SelectionBarPlural::One => self.one.as_ref(),
            SelectionBarPlural::Two => self.two.as_ref(),
            SelectionBarPlural::Few => self.few.as_ref(),
            SelectionBarPlural::Many => self.many.as_ref(),
            SelectionBarPlural::Other => self.other.as_ref(),
        }
    }

    /// The copy for `count`, like `formatLumenSelectionCount`. Blank templates fall back to
    /// `{count} selected`.
    pub fn format(&self, count: u64, locale: &str) -> String {
        let exact = if count == 0 { self.zero.as_ref() } else { None };
        let template = exact
            .or_else(|| self.form(selection_bar_plural(count, locale)))
            .or(self.other.as_ref())
            .filter(|template| !template.trim().is_empty())
            .map_or("{count} selected", String::as_str);

        format_template(
            template,
            &[("count", &selection_bar_format_count(count, locale))],
        )
    }
}

impl From<&str> for SelectionBarCountLabel {
    fn from(template: &str) -> Self {
        Self::new(template)
    }
}

impl From<String> for SelectionBarCountLabel {
    fn from(template: String) -> Self {
        Self::new(template)
    }
}

/// A polite live region that writes at most one message per delay; the latest message wins,
/// like `createLumenThrottledAnnouncer`.
#[derive(Clone, Copy)]
pub(crate) struct Announcer {
    pub(crate) text: Signal<String>,
    pending: Signal<Option<String>>,
    waiting: Signal<bool>,
}

impl Announcer {
    pub(crate) fn use_new() -> Self {
        Self {
            text: use_signal(String::new),
            pending: use_signal(|| None),
            waiting: use_signal(|| false),
        }
    }

    /// Queues a message, written after `delay`.
    pub(crate) fn announce(self, message: String, delay: Duration) {
        let mut pending = self.pending;
        let mut waiting = self.waiting;
        let mut text = self.text;

        pending.set(Some(message));

        if *waiting.peek() {
            return;
        }

        waiting.set(true);

        spawn(async move {
            sleep(delay).await;
            waiting.set(false);

            if let Some(message) = pending.write().take() {
                text.set(message);
            }
        });
    }
}

/// Where a [`SelectionBar`] sticks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SelectionBarPlacement {
    /// The bottom of the scroll container.
    #[default]
    Container,
    /// The bottom of the screen.
    Viewport,
}

impl SelectionBarPlacement {
    /// The `data-placement` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Container => "container",
            Self::Viewport => "viewport",
        }
    }
}

/// Props for [`SelectionBar`].
#[derive(Props, Clone, PartialEq)]
pub struct SelectionBarProps {
    /// Selected item count. The bar is hidden, and removed from the accessibility tree, at 0.
    #[props(default)]
    pub count: u64,
    /// Count copy. Defaults to `{count} selected`.
    #[props(default = SelectionBarCountLabel::new("{count} selected"), into)]
    pub label: SelectionBarCountLabel,
    /// Locale for plural rules and number formatting. Defaults to `en`.
    #[props(default = "en".to_string(), into)]
    pub locale: String,
    /// Clears the selection. Renders the clear button when set.
    pub on_clear: Option<EventHandler<()>>,
    /// Escape inside the bar calls `on_clear`.
    #[props(default)]
    pub clear_on_escape: bool,
    /// Accessible name and text of the clear button. Defaults to `Clear selection`.
    #[props(default = "Clear selection".to_string(), into)]
    pub clear_label: String,
    /// Announced when the count returns to 0. Defaults to `Selection cleared`.
    #[props(default = "Selection cleared".to_string(), into)]
    pub cleared_label: String,
    /// Accessible name of the action group. Defaults to `Selection actions`.
    #[props(default = "Selection actions".to_string(), into)]
    pub region_label: String,
    /// Where the bar sticks.
    #[props(default)]
    pub placement: SelectionBarPlacement,
    /// Milliseconds between count announcements. Defaults to 750.
    #[props(default = 750)]
    pub announce_delay: u64,
    /// 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>,
    /// The bulk actions.
    pub children: Element,
}

/// A floating bulk-action bar for a multi-select list.
///
/// It hides at a count of 0, shows the pluralized count, and announces count changes politely
/// (the first render stays silent).
#[component]
pub fn SelectionBar(props: SelectionBarProps) -> Element {
    let count = props.count;
    let text = props.label.format(count, &props.locale);
    let open = count > 0;
    let announcer = Announcer::use_new();
    let mut previous = use_hook(|| CopyValue::new(None::<u64>));
    let cleared = props.cleared_label.clone();

    use_effect(use_reactive(
        (&count, &text, &cleared, &props.announce_delay),
        move |(count, text, cleared, delay)| {
            let before = *previous.peek();
            previous.set(Some(count));

            match before {
                Some(before) if before != count => {
                    let message = if count == 0 { cleared } else { text };
                    announcer.announce(message, Duration::from_millis(delay));
                }
                _ => {}
            }
        },
    ));

    let class = compose([Some("ui-selection-bar"), props.class.as_deref()]);
    let on_clear = props.on_clear;
    let clear_on_escape = props.clear_on_escape;
    let has_actions = super::util::has_content(&props.children);

    rsx! {
        div {
            class,
            "data-count": "{count}",
            "data-placement": props.placement.as_str(),
            "data-slot": "selection-bar",
            "data-state": if open { "open" } else { "closed" },
            "data-ui-owner": "dioxus",
            "data-ui-selection-bar": "",
            ..props.attributes,
            div {
                aria_label: props.region_label,
                class: "ui-selection-bar__panel",
                "data-slot": "selection-bar-panel",
                hidden: !open,
                role: "group",
                onkeydown: move |event| {
                    if !clear_on_escape || event.key() != Key::Escape || event.is_composing() {
                        return;
                    }

                    if let Some(handler) = on_clear {
                        event.prevent_default();
                        handler.call(());
                    }
                },
                p { class: "ui-selection-bar__count", "data-slot": "selection-bar-count", "{text}" }
                if has_actions {
                    div { class: "ui-selection-bar__actions", "data-slot": "selection-bar-actions", {props.children} }
                }
                if let Some(handler) = on_clear {
                    button {
                        class: "ui-button ui-button--ghost ui-button--sm ui-selection-bar__clear",
                        "data-slot": "selection-bar-clear",
                        r#type: "button",
                        onclick: move |_| handler.call(()),
                        span { class: "ui-button__content", "{props.clear_label}" }
                    }
                }
            }
            span {
                aria_atomic: "true",
                aria_live: "polite",
                class: "ui-selection-bar__status",
                "data-slot": "selection-bar-status",
                role: "status",
                "{announcer.text}"
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        SelectionBarCountLabel, SelectionBarPlural, selection_bar_format_count,
        selection_bar_plural,
    };

    #[test]
    fn plural_rules_follow_cldr() {
        assert_eq!(selection_bar_plural(1, "en"), SelectionBarPlural::One);
        assert_eq!(selection_bar_plural(0, "en-US"), SelectionBarPlural::Other);
        assert_eq!(selection_bar_plural(0, "fr"), SelectionBarPlural::One);
        assert_eq!(selection_bar_plural(22, "ru"), SelectionBarPlural::Few);
        assert_eq!(selection_bar_plural(11, "ru"), SelectionBarPlural::Many);
        assert_eq!(selection_bar_plural(21, "ru"), SelectionBarPlural::One);
        assert_eq!(selection_bar_plural(12, "pl"), SelectionBarPlural::Many);
        assert_eq!(selection_bar_plural(3, "pl"), SelectionBarPlural::Few);
        assert_eq!(selection_bar_plural(1, "ja"), SelectionBarPlural::Other);
        assert_eq!(selection_bar_plural(2, "ar"), SelectionBarPlural::Two);
        assert_eq!(selection_bar_plural(105, "ar"), SelectionBarPlural::Few);
    }

    #[test]
    fn counts_group_digits() {
        assert_eq!(selection_bar_format_count(999, "en"), "999");
        assert_eq!(selection_bar_format_count(1234, "en"), "1,234");
        assert_eq!(selection_bar_format_count(1_234_567, "en"), "1,234,567");
        assert_eq!(selection_bar_format_count(1234, "es"), "1234");
        assert_eq!(selection_bar_format_count(12_345, "es"), "12.345");
        assert_eq!(selection_bar_format_count(1234, "de-DE"), "1.234");
        assert_eq!(
            selection_bar_format_count(u64::MAX, "en"),
            "18,446,744,073,709,551,615"
        );
    }

    #[test]
    fn labels_pick_plural_forms() {
        let label = SelectionBarCountLabel::plural("{count} file", "{count} files");
        assert_eq!(label.format(1, "en"), "1 file");
        assert_eq!(label.format(2, "en"), "2 files");
        assert_eq!(label.format(0, "en"), "0 files");
        let zero = SelectionBarCountLabel {
            zero: Some("Nothing".to_string()),
            ..SelectionBarCountLabel::new("{count} selected")
        };
        assert_eq!(zero.format(0, "en"), "Nothing");
        assert_eq!(
            SelectionBarCountLabel::new("  ").format(3, "en"),
            "3 selected"
        );
        assert_eq!(
            SelectionBarCountLabel::default().format(3, "en"),
            "3 selected"
        );
    }
}