Skip to main content

lumen_dioxus/navigation/
selection_bar.rs

1//! `SelectionBar`, plus the plural count copy and throttled announcer it shares with `LoadMore`.
2// cspell:words subtag CLDR cldr
3
4use std::time::Duration;
5
6use dioxus::prelude::*;
7
8use crate::class::compose;
9use crate::time::sleep;
10
11use super::util::format_template;
12
13/// A plural category, as `Intl.PluralRules` names them.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum SelectionBarPlural {
17    /// Zero items, in locales that have the category.
18    Zero,
19    /// One item.
20    One,
21    /// Two items.
22    Two,
23    /// A few items.
24    Few,
25    /// Many items.
26    Many,
27    /// Every other count.
28    Other,
29}
30
31/// The language subtag of a locale, lowercased (`pt-BR` is `pt`).
32fn language(locale: &str) -> String {
33    locale
34        .split(['-', '_'])
35        .next()
36        .unwrap_or_default()
37        .to_ascii_lowercase()
38}
39
40/// The plural category of a whole count, following CLDR cardinal rules for common languages.
41/// Unknown languages use the English rule.
42pub fn selection_bar_plural(count: u64, locale: &str) -> SelectionBarPlural {
43    use SelectionBarPlural::{Few, Many, One, Other, Two, Zero};
44
45    let tens = count % 100;
46    let units = count % 10;
47
48    match language(locale).as_str() {
49        "ja" | "zh" | "ko" | "th" | "vi" | "id" | "ms" | "lo" | "my" | "km" => Other,
50        "fr" | "pt" => {
51            if count <= 1 {
52                One
53            } else {
54                Other
55            }
56        }
57        "ru" | "uk" | "be" => match (units, tens) {
58            (1, t) if t != 11 => One,
59            (2..=4, t) if !(12..=14).contains(&t) => Few,
60            _ => Many,
61        },
62        "pl" => match (count, units, tens) {
63            (1, _, _) => One,
64            (_, 2..=4, t) if !(12..=14).contains(&t) => Few,
65            _ => Many,
66        },
67        "cs" | "sk" => match count {
68            1 => One,
69            2..=4 => Few,
70            _ => Other,
71        },
72        "ar" => match (count, tens) {
73            (0, _) => Zero,
74            (1, _) => One,
75            (2, _) => Two,
76            (_, 3..=10) => Few,
77            (_, 11..=99) => Many,
78            _ => Other,
79        },
80        _ => {
81            if count == 1 {
82                One
83            } else {
84                Other
85            }
86        }
87    }
88}
89
90/// Formats a count with the locale's digit grouping, like `Intl.NumberFormat` for whole numbers
91/// in common languages.
92pub fn selection_bar_format_count(count: u64, locale: &str) -> String {
93    let digits = count.to_string();
94    let lang = language(locale);
95    let (separator, min_digits) = match lang.as_str() {
96        "de" | "it" | "nl" | "da" | "id" | "tr" | "el" | "pt" => (".", 4),
97        "es" => (".", 5),
98        "fr" => ("\u{202f}", 4),
99        "pl" => ("\u{a0}", 5),
100        "ru" | "uk" | "cs" | "sk" | "sv" | "fi" | "nb" | "be" => ("\u{a0}", 4),
101        _ => (",", 4),
102    };
103
104    if digits.len() < min_digits {
105        return digits;
106    }
107
108    let mut out = String::with_capacity(digits.len() + digits.len() / 3 * 3);
109
110    for (index, character) in digits.chars().enumerate() {
111        if index > 0 && (digits.len() - index).is_multiple_of(3) {
112            out.push_str(separator);
113        }
114
115        out.push(character);
116    }
117
118    out
119}
120
121/// Count copy for a [`SelectionBar`] or `LoadMore`. `{count}` is the formatted count. Forms
122/// that are unset fall back to `other`; `zero` applies to 0 even where the locale has no zero
123/// category, as in English.
124#[derive(Clone, Debug, Default, PartialEq, Eq)]
125pub struct SelectionBarCountLabel {
126    /// Form for 0.
127    pub zero: Option<String>,
128    /// Form for the `one` category.
129    pub one: Option<String>,
130    /// Form for the `two` category.
131    pub two: Option<String>,
132    /// Form for the `few` category.
133    pub few: Option<String>,
134    /// Form for the `many` category.
135    pub many: Option<String>,
136    /// Form for every other count, and the fallback.
137    pub other: Option<String>,
138}
139
140impl SelectionBarCountLabel {
141    /// One template for every count.
142    pub fn new(template: impl Into<String>) -> Self {
143        Self {
144            other: Some(template.into()),
145            ..Self::default()
146        }
147    }
148
149    /// Separate singular and plural templates.
150    pub fn plural(one: impl Into<String>, other: impl Into<String>) -> Self {
151        Self {
152            one: Some(one.into()),
153            other: Some(other.into()),
154            ..Self::default()
155        }
156    }
157
158    fn form(&self, category: SelectionBarPlural) -> Option<&String> {
159        match category {
160            SelectionBarPlural::Zero => self.zero.as_ref(),
161            SelectionBarPlural::One => self.one.as_ref(),
162            SelectionBarPlural::Two => self.two.as_ref(),
163            SelectionBarPlural::Few => self.few.as_ref(),
164            SelectionBarPlural::Many => self.many.as_ref(),
165            SelectionBarPlural::Other => self.other.as_ref(),
166        }
167    }
168
169    /// The copy for `count`, like `formatLumenSelectionCount`. Blank templates fall back to
170    /// `{count} selected`.
171    pub fn format(&self, count: u64, locale: &str) -> String {
172        let exact = if count == 0 { self.zero.as_ref() } else { None };
173        let template = exact
174            .or_else(|| self.form(selection_bar_plural(count, locale)))
175            .or(self.other.as_ref())
176            .filter(|template| !template.trim().is_empty())
177            .map_or("{count} selected", String::as_str);
178
179        format_template(
180            template,
181            &[("count", &selection_bar_format_count(count, locale))],
182        )
183    }
184}
185
186impl From<&str> for SelectionBarCountLabel {
187    fn from(template: &str) -> Self {
188        Self::new(template)
189    }
190}
191
192impl From<String> for SelectionBarCountLabel {
193    fn from(template: String) -> Self {
194        Self::new(template)
195    }
196}
197
198/// A polite live region that writes at most one message per delay; the latest message wins,
199/// like `createLumenThrottledAnnouncer`.
200#[derive(Clone, Copy)]
201pub(crate) struct Announcer {
202    pub(crate) text: Signal<String>,
203    pending: Signal<Option<String>>,
204    waiting: Signal<bool>,
205}
206
207impl Announcer {
208    pub(crate) fn use_new() -> Self {
209        Self {
210            text: use_signal(String::new),
211            pending: use_signal(|| None),
212            waiting: use_signal(|| false),
213        }
214    }
215
216    /// Queues a message, written after `delay`.
217    pub(crate) fn announce(self, message: String, delay: Duration) {
218        let mut pending = self.pending;
219        let mut waiting = self.waiting;
220        let mut text = self.text;
221
222        pending.set(Some(message));
223
224        if *waiting.peek() {
225            return;
226        }
227
228        waiting.set(true);
229
230        spawn(async move {
231            sleep(delay).await;
232            waiting.set(false);
233
234            if let Some(message) = pending.write().take() {
235                text.set(message);
236            }
237        });
238    }
239}
240
241/// Where a [`SelectionBar`] sticks.
242#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
243#[non_exhaustive]
244pub enum SelectionBarPlacement {
245    /// The bottom of the scroll container.
246    #[default]
247    Container,
248    /// The bottom of the screen.
249    Viewport,
250}
251
252impl SelectionBarPlacement {
253    /// The `data-placement` value.
254    pub fn as_str(self) -> &'static str {
255        match self {
256            Self::Container => "container",
257            Self::Viewport => "viewport",
258        }
259    }
260}
261
262/// Props for [`SelectionBar`].
263#[derive(Props, Clone, PartialEq)]
264pub struct SelectionBarProps {
265    /// Selected item count. The bar is hidden, and removed from the accessibility tree, at 0.
266    #[props(default)]
267    pub count: u64,
268    /// Count copy. Defaults to `{count} selected`.
269    #[props(default = SelectionBarCountLabel::new("{count} selected"), into)]
270    pub label: SelectionBarCountLabel,
271    /// Locale for plural rules and number formatting. Defaults to `en`.
272    #[props(default = "en".to_string(), into)]
273    pub locale: String,
274    /// Clears the selection. Renders the clear button when set.
275    pub on_clear: Option<EventHandler<()>>,
276    /// Escape inside the bar calls `on_clear`.
277    #[props(default)]
278    pub clear_on_escape: bool,
279    /// Accessible name and text of the clear button. Defaults to `Clear selection`.
280    #[props(default = "Clear selection".to_string(), into)]
281    pub clear_label: String,
282    /// Announced when the count returns to 0. Defaults to `Selection cleared`.
283    #[props(default = "Selection cleared".to_string(), into)]
284    pub cleared_label: String,
285    /// Accessible name of the action group. Defaults to `Selection actions`.
286    #[props(default = "Selection actions".to_string(), into)]
287    pub region_label: String,
288    /// Where the bar sticks.
289    #[props(default)]
290    pub placement: SelectionBarPlacement,
291    /// Milliseconds between count announcements. Defaults to 750.
292    #[props(default = 750)]
293    pub announce_delay: u64,
294    /// Extra classes appended after the Lumen class.
295    #[props(into)]
296    pub class: Option<String>,
297    /// Any other `<div>` or global attribute.
298    #[props(extends = GlobalAttributes, extends = div)]
299    pub attributes: Vec<Attribute>,
300    /// The bulk actions.
301    pub children: Element,
302}
303
304/// A floating bulk-action bar for a multi-select list.
305///
306/// It hides at a count of 0, shows the pluralized count, and announces count changes politely
307/// (the first render stays silent).
308#[component]
309pub fn SelectionBar(props: SelectionBarProps) -> Element {
310    let count = props.count;
311    let text = props.label.format(count, &props.locale);
312    let open = count > 0;
313    let announcer = Announcer::use_new();
314    let mut previous = use_hook(|| CopyValue::new(None::<u64>));
315    let cleared = props.cleared_label.clone();
316
317    use_effect(use_reactive(
318        (&count, &text, &cleared, &props.announce_delay),
319        move |(count, text, cleared, delay)| {
320            let before = *previous.peek();
321            previous.set(Some(count));
322
323            match before {
324                Some(before) if before != count => {
325                    let message = if count == 0 { cleared } else { text };
326                    announcer.announce(message, Duration::from_millis(delay));
327                }
328                _ => {}
329            }
330        },
331    ));
332
333    let class = compose([Some("ui-selection-bar"), props.class.as_deref()]);
334    let on_clear = props.on_clear;
335    let clear_on_escape = props.clear_on_escape;
336    let has_actions = super::util::has_content(&props.children);
337
338    rsx! {
339        div {
340            class,
341            "data-count": "{count}",
342            "data-placement": props.placement.as_str(),
343            "data-slot": "selection-bar",
344            "data-state": if open { "open" } else { "closed" },
345            "data-ui-owner": "dioxus",
346            "data-ui-selection-bar": "",
347            ..props.attributes,
348            div {
349                aria_label: props.region_label,
350                class: "ui-selection-bar__panel",
351                "data-slot": "selection-bar-panel",
352                hidden: !open,
353                role: "group",
354                onkeydown: move |event| {
355                    if !clear_on_escape || event.key() != Key::Escape || event.is_composing() {
356                        return;
357                    }
358
359                    if let Some(handler) = on_clear {
360                        event.prevent_default();
361                        handler.call(());
362                    }
363                },
364                p { class: "ui-selection-bar__count", "data-slot": "selection-bar-count", "{text}" }
365                if has_actions {
366                    div { class: "ui-selection-bar__actions", "data-slot": "selection-bar-actions", {props.children} }
367                }
368                if let Some(handler) = on_clear {
369                    button {
370                        class: "ui-button ui-button--ghost ui-button--sm ui-selection-bar__clear",
371                        "data-slot": "selection-bar-clear",
372                        r#type: "button",
373                        onclick: move |_| handler.call(()),
374                        span { class: "ui-button__content", "{props.clear_label}" }
375                    }
376                }
377            }
378            span {
379                aria_atomic: "true",
380                aria_live: "polite",
381                class: "ui-selection-bar__status",
382                "data-slot": "selection-bar-status",
383                role: "status",
384                "{announcer.text}"
385            }
386        }
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use super::{
393        SelectionBarCountLabel, SelectionBarPlural, selection_bar_format_count,
394        selection_bar_plural,
395    };
396
397    #[test]
398    fn plural_rules_follow_cldr() {
399        assert_eq!(selection_bar_plural(1, "en"), SelectionBarPlural::One);
400        assert_eq!(selection_bar_plural(0, "en-US"), SelectionBarPlural::Other);
401        assert_eq!(selection_bar_plural(0, "fr"), SelectionBarPlural::One);
402        assert_eq!(selection_bar_plural(22, "ru"), SelectionBarPlural::Few);
403        assert_eq!(selection_bar_plural(11, "ru"), SelectionBarPlural::Many);
404        assert_eq!(selection_bar_plural(21, "ru"), SelectionBarPlural::One);
405        assert_eq!(selection_bar_plural(12, "pl"), SelectionBarPlural::Many);
406        assert_eq!(selection_bar_plural(3, "pl"), SelectionBarPlural::Few);
407        assert_eq!(selection_bar_plural(1, "ja"), SelectionBarPlural::Other);
408        assert_eq!(selection_bar_plural(2, "ar"), SelectionBarPlural::Two);
409        assert_eq!(selection_bar_plural(105, "ar"), SelectionBarPlural::Few);
410    }
411
412    #[test]
413    fn counts_group_digits() {
414        assert_eq!(selection_bar_format_count(999, "en"), "999");
415        assert_eq!(selection_bar_format_count(1234, "en"), "1,234");
416        assert_eq!(selection_bar_format_count(1_234_567, "en"), "1,234,567");
417        assert_eq!(selection_bar_format_count(1234, "es"), "1234");
418        assert_eq!(selection_bar_format_count(12_345, "es"), "12.345");
419        assert_eq!(selection_bar_format_count(1234, "de-DE"), "1.234");
420        assert_eq!(
421            selection_bar_format_count(u64::MAX, "en"),
422            "18,446,744,073,709,551,615"
423        );
424    }
425
426    #[test]
427    fn labels_pick_plural_forms() {
428        let label = SelectionBarCountLabel::plural("{count} file", "{count} files");
429        assert_eq!(label.format(1, "en"), "1 file");
430        assert_eq!(label.format(2, "en"), "2 files");
431        assert_eq!(label.format(0, "en"), "0 files");
432        let zero = SelectionBarCountLabel {
433            zero: Some("Nothing".to_string()),
434            ..SelectionBarCountLabel::new("{count} selected")
435        };
436        assert_eq!(zero.format(0, "en"), "Nothing");
437        assert_eq!(
438            SelectionBarCountLabel::new("  ").format(3, "en"),
439            "3 selected"
440        );
441        assert_eq!(
442            SelectionBarCountLabel::default().format(3, "en"),
443            "3 selected"
444        );
445    }
446}