use std::cell::RefCell;
use std::rc::Rc;
use dioxus::prelude::*;
use super::character_count_graphemes::count_graphemes;
use crate::class::compose;
use crate::hooks::use_unique_id;
const DEFAULT_THRESHOLDS: [u32; 3] = [20, 10, 0];
const MAX_LIMIT: u32 = 1_000_000_000;
const MAX_THRESHOLDS: usize = 12;
const COUNT_TOKEN: &str = "{count}";
const OWNER: &str = "react";
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum CharacterCountState {
#[default]
Within,
Near,
Over,
}
impl CharacterCountState {
pub fn as_str(self) -> &'static str {
match self {
Self::Within => "within",
Self::Near => "near",
Self::Over => "over",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CharacterCountTemplate {
pub one: Option<String>,
pub other: String,
}
impl CharacterCountTemplate {
pub fn new(other: impl Into<String>) -> Self {
Self {
one: None,
other: other.into(),
}
}
#[must_use]
pub fn one(mut self, one: impl Into<String>) -> Self {
self.one = Some(one.into());
self
}
fn default_remaining() -> Self {
Self::new("{count} characters left").one("{count} character left")
}
fn default_over() -> Self {
Self::new("{count} characters over the limit").one("{count} character over the limit")
}
fn resolve(template: Option<&Self>, fallback: fn() -> Self) -> Self {
match template {
Some(template) if template.one.is_some() || !template.other.trim().is_empty() => {
template.clone()
}
_ => fallback(),
}
}
fn format(&self, count: u64) -> String {
let message = if count == 1 {
self.one.as_deref().unwrap_or(&self.other)
} else {
&self.other
};
message.replace(COUNT_TOKEN, &format_count(count))
}
}
impl From<&str> for CharacterCountTemplate {
fn from(value: &str) -> Self {
Self::new(value)
}
}
impl From<String> for CharacterCountTemplate {
fn from(value: String) -> Self {
Self::new(value)
}
}
fn format_count(count: u64) -> String {
let digits = count.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (index, digit) in digits.chars().enumerate() {
if index > 0 && (digits.len() - index).is_multiple_of(3) {
out.push(',');
}
out.push(digit);
}
out
}
fn resolve_max(max: u32) -> Option<u32> {
(1..=MAX_LIMIT).contains(&max).then_some(max)
}
fn resolve_thresholds(thresholds: Option<&[u32]>) -> Vec<u32> {
let Some(thresholds) = thresholds else {
return DEFAULT_THRESHOLDS.to_vec();
};
let mut kept: Vec<u32> = Vec::new();
for threshold in thresholds {
if *threshold <= MAX_LIMIT && !kept.contains(threshold) {
kept.push(*threshold);
}
if kept.len() >= MAX_THRESHOLDS {
break;
}
}
kept.sort_unstable_by(|first, second| second.cmp(first));
kept
}
#[derive(Clone, Debug, PartialEq)]
struct Config {
max: Option<u32>,
announce_at: Vec<u32>,
remaining_label: CharacterCountTemplate,
over_label: CharacterCountTemplate,
}
impl Config {
fn new(
max: u32,
announce_at: Option<&[u32]>,
remaining_label: Option<&CharacterCountTemplate>,
over_label: Option<&CharacterCountTemplate>,
) -> Self {
Self {
max: resolve_max(max),
announce_at: resolve_thresholds(announce_at),
remaining_label: CharacterCountTemplate::resolve(
remaining_label,
CharacterCountTemplate::default_remaining,
),
over_label: CharacterCountTemplate::resolve(
over_label,
CharacterCountTemplate::default_over,
),
}
}
fn near_threshold(&self) -> Option<u32> {
let max = self.max?;
self.announce_at
.iter()
.copied()
.find(|threshold| *threshold < max)
}
fn snapshot(&self, value: &str) -> CharacterCountSnapshot {
let count = count_graphemes(value);
let Some(max) = self.max else {
return CharacterCountSnapshot {
count,
max: None,
remaining: 0,
state: CharacterCountState::Within,
text: String::new(),
};
};
let count_signed = i64::try_from(count).unwrap_or(i64::MAX);
let remaining = i64::from(max) - count_signed;
if remaining < 0 {
return CharacterCountSnapshot {
count,
max: Some(max),
remaining,
state: CharacterCountState::Over,
text: self.over_label.format(remaining.unsigned_abs()),
};
}
let near = self
.near_threshold()
.is_some_and(|threshold| remaining <= i64::from(threshold));
CharacterCountSnapshot {
count,
max: Some(max),
remaining,
state: if near {
CharacterCountState::Near
} else {
CharacterCountState::Within
},
text: self.remaining_label.format(remaining.unsigned_abs()),
}
}
fn announcement(
&self,
previous: Option<&CharacterCountSnapshot>,
next: &CharacterCountSnapshot,
) -> Option<String> {
let previous = previous?;
let limit = next.max?;
if self.max.is_none() || previous.max != Some(limit) {
return None;
}
let was_over = previous.state == CharacterCountState::Over;
let is_over = next.state == CharacterCountState::Over;
if was_over != is_over {
return Some(next.text.clone());
}
if is_over {
return None;
}
let crossed = self.announce_at.iter().any(|threshold| {
let threshold = i64::from(*threshold);
threshold < i64::from(limit)
&& previous.remaining > threshold
&& next.remaining <= threshold
});
crossed.then(|| next.text.clone())
}
}
fn live_text(current: &str, message: String) -> String {
if current == message {
format!("{message}\u{a0}")
} else {
message
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CharacterCountSnapshot {
pub count: usize,
pub max: Option<u32>,
pub remaining: i64,
pub state: CharacterCountState,
pub text: String,
}
impl CharacterCountSnapshot {
pub fn new(value: &str, max: u32) -> Self {
Config::new(max, None, None, None).snapshot(value)
}
}
#[derive(Props, Clone, PartialEq)]
pub struct CharacterCountProps {
pub max: u32,
#[props(default, into)]
pub value: String,
pub announce_at: Option<Vec<u32>>,
#[props(default = CharacterCountTemplate::default_remaining(), into)]
pub remaining_label: CharacterCountTemplate,
#[props(default = CharacterCountTemplate::default_over(), into)]
pub over_label: CharacterCountTemplate,
#[props(default)]
pub composing: bool,
#[props(into)]
pub value_id: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = p)]
pub attributes: Vec<Attribute>,
}
#[derive(Default)]
struct Announcer {
announced: Option<CharacterCountSnapshot>,
text: String,
}
#[component]
pub fn CharacterCount(props: CharacterCountProps) -> Element {
let generated = use_unique_id();
let value_id = props
.value_id
.clone()
.filter(|id| !id.trim().is_empty())
.unwrap_or_else(|| format!("{generated}-value"));
let announcer = use_hook(|| Rc::new(RefCell::new(Announcer::default())));
let config = Config::new(
props.max,
props.announce_at.as_deref(),
Some(&props.remaining_label),
Some(&props.over_label),
);
let snapshot = config.snapshot(&props.value);
let announcement = {
let mut announcer = announcer.borrow_mut();
if !props.composing {
let message = config.announcement(announcer.announced.as_ref(), &snapshot);
announcer.announced = Some(snapshot.clone());
if let Some(message) = message {
announcer.text = live_text(&announcer.text, message);
}
}
announcer.text.clone()
};
let class = compose([Some("ui-character-count"), props.class.as_deref()]);
rsx! {
p {
class,
"data-slot": "character-count",
"data-state": snapshot.state.as_str(),
"data-ui-character-count": "true",
"data-ui-owner": OWNER,
..props.attributes,
span {
class: "ui-character-count__value",
"data-slot": "character-count-value",
id: value_id,
"{snapshot.text}"
}
span {
aria_atomic: "true",
aria_live: "polite",
class: "ui-sr-only",
"data-slot": "character-count-announcer",
"{announcement}"
}
}
}
}
#[cfg(test)]
mod tests {
use super::{
CharacterCountSnapshot, CharacterCountState, CharacterCountTemplate, Config, format_count,
live_text, resolve_max, resolve_thresholds,
};
fn config(max: u32, announce_at: Option<&[u32]>) -> Config {
Config::new(max, announce_at, None, None)
}
#[test]
fn counts_grapheme_clusters_and_formats_the_remaining_text() {
let snapshot = CharacterCountSnapshot::new("hello", 10);
assert_eq!(snapshot.count, 5);
assert_eq!(snapshot.remaining, 5);
assert_eq!(snapshot.state, CharacterCountState::Within);
assert_eq!(snapshot.text, "5 characters left");
assert_eq!(
CharacterCountSnapshot::new("👍🏽é👨👩👧", 3).text,
"0 characters left"
);
let over = CharacterCountSnapshot::new("👍🏽é👨👩👧!", 3);
assert_eq!(over.state, CharacterCountState::Over);
assert_eq!(over.remaining, -1);
assert_eq!(over.text, "1 character over the limit");
}
#[test]
fn near_starts_at_the_highest_threshold_below_the_limit() {
let near = config(30, None);
assert_eq!(
near.snapshot(&"a".repeat(9)).state,
CharacterCountState::Within
);
assert_eq!(
near.snapshot(&"a".repeat(10)).state,
CharacterCountState::Near
);
let small = config(15, None);
assert_eq!(small.snapshot("abcd").state, CharacterCountState::Within);
assert_eq!(small.snapshot("abcde").state, CharacterCountState::Near);
assert_eq!(small.snapshot("abcdef").text, "9 characters left");
assert_eq!(
config(5, Some(&[])).snapshot("abcde").state,
CharacterCountState::Within
);
}
#[test]
fn invalid_limits_render_no_text() {
assert_eq!(resolve_max(0), None);
assert_eq!(resolve_max(1_000_000_001), None);
assert_eq!(resolve_max(1_000_000_000), Some(1_000_000_000));
let snapshot = CharacterCountSnapshot::new("abc", 0);
assert_eq!(snapshot.max, None);
assert_eq!(snapshot.count, 3);
assert_eq!(snapshot.remaining, 0);
assert_eq!(snapshot.state, CharacterCountState::Within);
assert_eq!(snapshot.text, "");
}
#[test]
fn thresholds_are_deduplicated_capped_and_sorted() {
assert_eq!(resolve_thresholds(None), vec![20, 10, 0]);
assert_eq!(resolve_thresholds(Some(&[0, 10, 10, 50])), vec![50, 10, 0]);
assert_eq!(resolve_thresholds(Some(&[2_000_000_000, 5])), vec![5]);
let many: Vec<u32> = (0..100).collect();
assert_eq!(
resolve_thresholds(Some(&many)),
(0..12).rev().collect::<Vec<u32>>()
);
}
#[test]
fn numbers_use_english_grouping() {
assert_eq!(format_count(0), "0");
assert_eq!(format_count(999), "999");
assert_eq!(format_count(1_999), "1,999");
assert_eq!(format_count(1_000_000_000), "1,000,000,000");
assert_eq!(
CharacterCountSnapshot::new("a", 2000).text,
"1,999 characters left"
);
}
#[test]
fn templates_pick_the_singular_and_fall_back_when_blank() {
let custom = Config::new(
3,
None,
Some(&CharacterCountTemplate::new("Quedan {count}").one("Queda {count}")),
Some(&"{count} de más ({count})".into()),
);
assert_eq!(custom.snapshot("ab").text, "Queda 1");
assert_eq!(custom.snapshot("a").text, "Quedan 2");
assert_eq!(custom.snapshot("abcde").text, "2 de más (2)");
let blank = Config::new(3, None, Some(&" ".into()), None);
assert_eq!(blank.snapshot("a").text, "2 characters left");
}
#[test]
fn announces_only_when_crossing_thresholds_or_the_limit() {
let config = config(12, Some(&[10, 0]));
let step = |previous: &str, next: &str| {
config.announcement(Some(&config.snapshot(previous)), &config.snapshot(next))
};
assert_eq!(config.announcement(None, &config.snapshot("a")), None);
assert_eq!(step("", "a"), None);
assert_eq!(step("a", "ab").as_deref(), Some("10 characters left"));
assert_eq!(step("ab", "abc"), None);
assert_eq!(step("abc", "ab"), None, "deleting stays silent");
assert_eq!(
step("abc", &"a".repeat(13)).as_deref(),
Some("1 character over the limit")
);
assert_eq!(step(&"a".repeat(13), &"a".repeat(14)), None);
assert_eq!(
step(&"a".repeat(13), &"a".repeat(12)).as_deref(),
Some("0 characters left")
);
assert_eq!(
step(&"a".repeat(11), &"a".repeat(12)).as_deref(),
Some("0 characters left")
);
}
#[test]
fn a_new_limit_is_a_new_baseline() {
let before = config(12, None).snapshot("abc");
let after = config(3, None);
assert_eq!(
after.announcement(Some(&before), &after.snapshot("abcd")),
None
);
assert_eq!(
config(0, None).announcement(Some(&before), &config(0, None).snapshot("a")),
None
);
}
#[test]
fn repeated_messages_alternate_a_no_break_space() {
assert_eq!(live_text("", "1 left".to_string()), "1 left");
assert_eq!(live_text("1 left", "1 left".to_string()), "1 left\u{a0}");
assert_eq!(live_text("1 left\u{a0}", "1 left".to_string()), "1 left");
}
}