use std::time::Duration;
use dioxus::prelude::*;
use crate::class::compose;
use crate::time::sleep;
use super::util::format_template;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SelectionBarPlural {
Zero,
One,
Two,
Few,
Many,
Other,
}
fn language(locale: &str) -> String {
locale
.split(['-', '_'])
.next()
.unwrap_or_default()
.to_ascii_lowercase()
}
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
}
}
}
}
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
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SelectionBarCountLabel {
pub zero: Option<String>,
pub one: Option<String>,
pub two: Option<String>,
pub few: Option<String>,
pub many: Option<String>,
pub other: Option<String>,
}
impl SelectionBarCountLabel {
pub fn new(template: impl Into<String>) -> Self {
Self {
other: Some(template.into()),
..Self::default()
}
}
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(),
}
}
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)
}
}
#[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),
}
}
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);
}
});
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SelectionBarPlacement {
#[default]
Container,
Viewport,
}
impl SelectionBarPlacement {
pub fn as_str(self) -> &'static str {
match self {
Self::Container => "container",
Self::Viewport => "viewport",
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct SelectionBarProps {
#[props(default)]
pub count: u64,
#[props(default = SelectionBarCountLabel::new("{count} selected"), into)]
pub label: SelectionBarCountLabel,
#[props(default = "en".to_string(), into)]
pub locale: String,
pub on_clear: Option<EventHandler<()>>,
#[props(default)]
pub clear_on_escape: bool,
#[props(default = "Clear selection".to_string(), into)]
pub clear_label: String,
#[props(default = "Selection cleared".to_string(), into)]
pub cleared_label: String,
#[props(default = "Selection actions".to_string(), into)]
pub region_label: String,
#[props(default)]
pub placement: SelectionBarPlacement,
#[props(default = 750)]
pub announce_delay: u64,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[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"
);
}
}