Skip to main content

lumen_dioxus/inputs/
character_count.rs

1//! `CharacterCount`: the characters left for an input or textarea, with polite announcements.
2
3// cspell:words Queda Quedan
4
5use std::cell::RefCell;
6use std::rc::Rc;
7
8use dioxus::prelude::*;
9
10use super::character_count_graphemes::count_graphemes;
11use crate::class::compose;
12use crate::hooks::use_unique_id;
13
14/// Remaining counts announced while typing when `announce_at` is not set.
15const DEFAULT_THRESHOLDS: [u32; 3] = [20, 10, 0];
16/// The largest limit or threshold lumen-core accepts.
17const MAX_LIMIT: u32 = 1_000_000_000;
18/// At most this many thresholds are kept.
19const MAX_THRESHOLDS: usize = 12;
20const COUNT_TOKEN: &str = "{count}";
21/// Lumen's web runtime skips roots that carry `data-ui-owner`; lumen-react's value keeps the
22/// markup identical.
23const OWNER: &str = "react";
24
25/// Visual state of a [`CharacterCount`], also its `data-state` value.
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum CharacterCountState {
29    /// Within the limit and above the first announcement threshold.
30    #[default]
31    Within,
32    /// At or below the highest announcement threshold that is lower than the limit.
33    Near,
34    /// Over the limit.
35    Over,
36}
37
38impl CharacterCountState {
39    /// The `data-state` value.
40    pub fn as_str(self) -> &'static str {
41        match self {
42            Self::Within => "within",
43            Self::Near => "near",
44            Self::Over => "over",
45        }
46    }
47}
48
49/// A message with a `{count}` placeholder, with an optional singular form.
50///
51/// Build one from a string to use the same text for every count, or with
52/// [`CharacterCountTemplate::new`] and [`CharacterCountTemplate::one`] for English-style plurals:
53///
54/// ```
55/// use lumen_dioxus::CharacterCountTemplate;
56///
57/// let left = CharacterCountTemplate::new("{count} letters left").one("{count} letter left");
58///
59/// assert_eq!(left.other, "{count} letters left");
60/// ```
61#[derive(Clone, Debug, PartialEq, Eq)]
62pub struct CharacterCountTemplate {
63    /// Message for a count of exactly one. Falls back to `other`.
64    pub one: Option<String>,
65    /// Message for every other count.
66    pub other: String,
67}
68
69impl CharacterCountTemplate {
70    /// A template that uses `other` for every count.
71    pub fn new(other: impl Into<String>) -> Self {
72        Self {
73            one: None,
74            other: other.into(),
75        }
76    }
77
78    /// Returns the template with a message for a count of exactly one.
79    #[must_use]
80    pub fn one(mut self, one: impl Into<String>) -> Self {
81        self.one = Some(one.into());
82        self
83    }
84
85    fn default_remaining() -> Self {
86        Self::new("{count} characters left").one("{count} character left")
87    }
88
89    fn default_over() -> Self {
90        Self::new("{count} characters over the limit").one("{count} character over the limit")
91    }
92
93    /// The template, or `fallback` when it is missing or blank, like
94    /// `resolveLumenCharacterCountTemplate`.
95    fn resolve(template: Option<&Self>, fallback: fn() -> Self) -> Self {
96        match template {
97            Some(template) if template.one.is_some() || !template.other.trim().is_empty() => {
98                template.clone()
99            }
100            _ => fallback(),
101        }
102    }
103
104    /// Replaces every `{count}` with the formatted count, picking the English plural form.
105    fn format(&self, count: u64) -> String {
106        let message = if count == 1 {
107            self.one.as_deref().unwrap_or(&self.other)
108        } else {
109            &self.other
110        };
111
112        message.replace(COUNT_TOKEN, &format_count(count))
113    }
114}
115
116impl From<&str> for CharacterCountTemplate {
117    fn from(value: &str) -> Self {
118        Self::new(value)
119    }
120}
121
122impl From<String> for CharacterCountTemplate {
123    fn from(value: String) -> Self {
124        Self::new(value)
125    }
126}
127
128/// Formats a count with English digit grouping (`1,999`), like `Intl.NumberFormat('en')`.
129fn format_count(count: u64) -> String {
130    let digits = count.to_string();
131    let mut out = String::with_capacity(digits.len() + digits.len() / 3);
132
133    for (index, digit) in digits.chars().enumerate() {
134        if index > 0 && (digits.len() - index).is_multiple_of(3) {
135            out.push(',');
136        }
137
138        out.push(digit);
139    }
140
141    out
142}
143
144/// A positive limit of at most one billion, like `resolveLumenCharacterCountMax`.
145fn resolve_max(max: u32) -> Option<u32> {
146    (1..=MAX_LIMIT).contains(&max).then_some(max)
147}
148
149/// Valid, unique thresholds (at most 12, kept in order of appearance) sorted from highest to
150/// lowest, like `resolveLumenCharacterCountThresholds`.
151fn resolve_thresholds(thresholds: Option<&[u32]>) -> Vec<u32> {
152    let Some(thresholds) = thresholds else {
153        return DEFAULT_THRESHOLDS.to_vec();
154    };
155    let mut kept: Vec<u32> = Vec::new();
156
157    for threshold in thresholds {
158        if *threshold <= MAX_LIMIT && !kept.contains(threshold) {
159            kept.push(*threshold);
160        }
161
162        if kept.len() >= MAX_THRESHOLDS {
163            break;
164        }
165    }
166
167    kept.sort_unstable_by(|first, second| second.cmp(first));
168    kept
169}
170
171/// The resolved options of a counter.
172#[derive(Clone, Debug, PartialEq)]
173struct Config {
174    max: Option<u32>,
175    announce_at: Vec<u32>,
176    remaining_label: CharacterCountTemplate,
177    over_label: CharacterCountTemplate,
178}
179
180impl Config {
181    fn new(
182        max: u32,
183        announce_at: Option<&[u32]>,
184        remaining_label: Option<&CharacterCountTemplate>,
185        over_label: Option<&CharacterCountTemplate>,
186    ) -> Self {
187        Self {
188            max: resolve_max(max),
189            announce_at: resolve_thresholds(announce_at),
190            remaining_label: CharacterCountTemplate::resolve(
191                remaining_label,
192                CharacterCountTemplate::default_remaining,
193            ),
194            over_label: CharacterCountTemplate::resolve(
195                over_label,
196                CharacterCountTemplate::default_over,
197            ),
198        }
199    }
200
201    /// The highest threshold below the limit; at or below it the counter is `near`.
202    fn near_threshold(&self) -> Option<u32> {
203        let max = self.max?;
204
205        self.announce_at
206            .iter()
207            .copied()
208            .find(|threshold| *threshold < max)
209    }
210
211    fn snapshot(&self, value: &str) -> CharacterCountSnapshot {
212        let count = count_graphemes(value);
213        let Some(max) = self.max else {
214            return CharacterCountSnapshot {
215                count,
216                max: None,
217                remaining: 0,
218                state: CharacterCountState::Within,
219                text: String::new(),
220            };
221        };
222        let count_signed = i64::try_from(count).unwrap_or(i64::MAX);
223        let remaining = i64::from(max) - count_signed;
224
225        if remaining < 0 {
226            return CharacterCountSnapshot {
227                count,
228                max: Some(max),
229                remaining,
230                state: CharacterCountState::Over,
231                text: self.over_label.format(remaining.unsigned_abs()),
232            };
233        }
234
235        let near = self
236            .near_threshold()
237            .is_some_and(|threshold| remaining <= i64::from(threshold));
238
239        CharacterCountSnapshot {
240            count,
241            max: Some(max),
242            remaining,
243            state: if near {
244                CharacterCountState::Near
245            } else {
246                CharacterCountState::Within
247            },
248            text: self.remaining_label.format(remaining.unsigned_abs()),
249        }
250    }
251
252    /// Text to announce politely, or `None`, like `getLumenCharacterCountAnnouncement`: crossing a
253    /// threshold while typing, going over the limit, or coming back within it announces once.
254    fn announcement(
255        &self,
256        previous: Option<&CharacterCountSnapshot>,
257        next: &CharacterCountSnapshot,
258    ) -> Option<String> {
259        let previous = previous?;
260        let limit = next.max?;
261
262        if self.max.is_none() || previous.max != Some(limit) {
263            return None;
264        }
265
266        let was_over = previous.state == CharacterCountState::Over;
267        let is_over = next.state == CharacterCountState::Over;
268
269        if was_over != is_over {
270            return Some(next.text.clone());
271        }
272
273        if is_over {
274            return None;
275        }
276
277        let crossed = self.announce_at.iter().any(|threshold| {
278            let threshold = i64::from(*threshold);
279
280            threshold < i64::from(limit)
281                && previous.remaining > threshold
282                && next.remaining <= threshold
283        });
284
285        crossed.then(|| next.text.clone())
286    }
287}
288
289/// Live-region text that is announced even when the message repeats: identical text would not
290/// change the DOM, so it alternates a trailing no-break space, like
291/// `getLumenCharacterCountLiveText`.
292fn live_text(current: &str, message: String) -> String {
293    if current == message {
294        format!("{message}\u{a0}")
295    } else {
296        message
297    }
298}
299
300/// The count, the characters left, and the visible text for a value and limit.
301#[derive(Clone, Debug, PartialEq, Eq)]
302pub struct CharacterCountSnapshot {
303    /// User-perceived characters (extended grapheme clusters).
304    pub count: usize,
305    /// The limit, or `None` when it is zero or above one billion.
306    pub max: Option<u32>,
307    /// Characters left; negative when over the limit, zero without a valid limit.
308    pub remaining: i64,
309    /// Within, near, or over the limit, with the default thresholds (20, 10, and 0 left).
310    pub state: CharacterCountState,
311    /// Visible text, such as `5 characters left`. Empty without a valid limit.
312    pub text: String,
313}
314
315impl CharacterCountSnapshot {
316    /// Counts `value` against `max` with the default thresholds and English messages, the same
317    /// way [`CharacterCount`] does. Use it to validate the limit or to mark the control.
318    pub fn new(value: &str, max: u32) -> Self {
319        Config::new(max, None, None, None).snapshot(value)
320    }
321}
322
323/// Props for [`CharacterCount`].
324#[derive(Props, Clone, PartialEq)]
325pub struct CharacterCountProps {
326    /// Maximum user-perceived characters, from 1 to one billion. Other values render no text.
327    /// Input is never truncated; validate the limit in the form.
328    pub max: u32,
329    /// The paired control's current value. The counter cannot read other elements, so pass the
330    /// value the control's `oninput` stores.
331    #[props(default, into)]
332    pub value: String,
333    /// Remaining counts that announce politely while typing. Defaults to 20, 10, and 0.
334    pub announce_at: Option<Vec<u32>>,
335    /// Text while within the limit. Defaults to `{count} characters left` (singular
336    /// `{count} character left`). A blank template falls back to the default.
337    #[props(default = CharacterCountTemplate::default_remaining(), into)]
338    pub remaining_label: CharacterCountTemplate,
339    /// Text while over the limit. Defaults to `{count} characters over the limit` (singular
340    /// `{count} character over the limit`). A blank template falls back to the default.
341    #[props(default = CharacterCountTemplate::default_over(), into)]
342    pub over_label: CharacterCountTemplate,
343    /// Set while the control is composing text with an input method; announcements wait until it
344    /// ends.
345    #[props(default)]
346    pub composing: bool,
347    /// Id of the count text. Defaults to a generated id. Add it to the control's
348    /// `aria-describedby` so assistive technology reads the count.
349    #[props(into)]
350    pub value_id: Option<String>,
351    /// Extra classes appended after the Lumen class.
352    #[props(into)]
353    pub class: Option<String>,
354    /// Any other `<p>` or global attribute.
355    #[props(extends = GlobalAttributes, extends = p)]
356    pub attributes: Vec<Attribute>,
357}
358
359/// What the announcer last compared against and the live text it shows.
360#[derive(Default)]
361struct Announcer {
362    announced: Option<CharacterCountSnapshot>,
363    text: String,
364}
365
366/// Shows the characters left for an input or textarea and announces politely only at thresholds
367/// and when crossing the limit. It never truncates input.
368///
369/// Counts are user-perceived characters (grapheme clusters), so an emoji with modifiers or a
370/// letter with combining marks counts once, like lumen-react.
371#[component]
372pub fn CharacterCount(props: CharacterCountProps) -> Element {
373    let generated = use_unique_id();
374    let value_id = props
375        .value_id
376        .clone()
377        .filter(|id| !id.trim().is_empty())
378        .unwrap_or_else(|| format!("{generated}-value"));
379    let announcer = use_hook(|| Rc::new(RefCell::new(Announcer::default())));
380    let config = Config::new(
381        props.max,
382        props.announce_at.as_deref(),
383        Some(&props.remaining_label),
384        Some(&props.over_label),
385    );
386    let snapshot = config.snapshot(&props.value);
387    let announcement = {
388        let mut announcer = announcer.borrow_mut();
389
390        if !props.composing {
391            let message = config.announcement(announcer.announced.as_ref(), &snapshot);
392
393            announcer.announced = Some(snapshot.clone());
394
395            if let Some(message) = message {
396                announcer.text = live_text(&announcer.text, message);
397            }
398        }
399
400        announcer.text.clone()
401    };
402    let class = compose([Some("ui-character-count"), props.class.as_deref()]);
403
404    rsx! {
405        p {
406            class,
407            "data-slot": "character-count",
408            "data-state": snapshot.state.as_str(),
409            "data-ui-character-count": "true",
410            "data-ui-owner": OWNER,
411            ..props.attributes,
412            span {
413                class: "ui-character-count__value",
414                "data-slot": "character-count-value",
415                id: value_id,
416                "{snapshot.text}"
417            }
418            span {
419                aria_atomic: "true",
420                aria_live: "polite",
421                class: "ui-sr-only",
422                "data-slot": "character-count-announcer",
423                "{announcement}"
424            }
425        }
426    }
427}
428
429#[cfg(test)]
430mod tests {
431    use super::{
432        CharacterCountSnapshot, CharacterCountState, CharacterCountTemplate, Config, format_count,
433        live_text, resolve_max, resolve_thresholds,
434    };
435
436    fn config(max: u32, announce_at: Option<&[u32]>) -> Config {
437        Config::new(max, announce_at, None, None)
438    }
439
440    #[test]
441    fn counts_grapheme_clusters_and_formats_the_remaining_text() {
442        let snapshot = CharacterCountSnapshot::new("hello", 10);
443
444        assert_eq!(snapshot.count, 5);
445        assert_eq!(snapshot.remaining, 5);
446        assert_eq!(snapshot.state, CharacterCountState::Within);
447        assert_eq!(snapshot.text, "5 characters left");
448
449        assert_eq!(
450            CharacterCountSnapshot::new("๐Ÿ‘๐Ÿฝรฉ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง", 3).text,
451            "0 characters left"
452        );
453
454        let over = CharacterCountSnapshot::new("๐Ÿ‘๐Ÿฝรฉ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง!", 3);
455
456        assert_eq!(over.state, CharacterCountState::Over);
457        assert_eq!(over.remaining, -1);
458        assert_eq!(over.text, "1 character over the limit");
459    }
460
461    #[test]
462    fn near_starts_at_the_highest_threshold_below_the_limit() {
463        let near = config(30, None);
464
465        assert_eq!(
466            near.snapshot(&"a".repeat(9)).state,
467            CharacterCountState::Within
468        );
469        assert_eq!(
470            near.snapshot(&"a".repeat(10)).state,
471            CharacterCountState::Near
472        );
473
474        // With a limit of 15, the 20 threshold is skipped and 10 decides.
475        let small = config(15, None);
476
477        assert_eq!(small.snapshot("abcd").state, CharacterCountState::Within);
478        assert_eq!(small.snapshot("abcde").state, CharacterCountState::Near);
479        assert_eq!(small.snapshot("abcdef").text, "9 characters left");
480        assert_eq!(
481            config(5, Some(&[])).snapshot("abcde").state,
482            CharacterCountState::Within
483        );
484    }
485
486    #[test]
487    fn invalid_limits_render_no_text() {
488        assert_eq!(resolve_max(0), None);
489        assert_eq!(resolve_max(1_000_000_001), None);
490        assert_eq!(resolve_max(1_000_000_000), Some(1_000_000_000));
491
492        let snapshot = CharacterCountSnapshot::new("abc", 0);
493
494        assert_eq!(snapshot.max, None);
495        assert_eq!(snapshot.count, 3);
496        assert_eq!(snapshot.remaining, 0);
497        assert_eq!(snapshot.state, CharacterCountState::Within);
498        assert_eq!(snapshot.text, "");
499    }
500
501    #[test]
502    fn thresholds_are_deduplicated_capped_and_sorted() {
503        assert_eq!(resolve_thresholds(None), vec![20, 10, 0]);
504        assert_eq!(resolve_thresholds(Some(&[0, 10, 10, 50])), vec![50, 10, 0]);
505        assert_eq!(resolve_thresholds(Some(&[2_000_000_000, 5])), vec![5]);
506
507        let many: Vec<u32> = (0..100).collect();
508
509        assert_eq!(
510            resolve_thresholds(Some(&many)),
511            (0..12).rev().collect::<Vec<u32>>()
512        );
513    }
514
515    #[test]
516    fn numbers_use_english_grouping() {
517        assert_eq!(format_count(0), "0");
518        assert_eq!(format_count(999), "999");
519        assert_eq!(format_count(1_999), "1,999");
520        assert_eq!(format_count(1_000_000_000), "1,000,000,000");
521        assert_eq!(
522            CharacterCountSnapshot::new("a", 2000).text,
523            "1,999 characters left"
524        );
525    }
526
527    #[test]
528    fn templates_pick_the_singular_and_fall_back_when_blank() {
529        let custom = Config::new(
530            3,
531            None,
532            Some(&CharacterCountTemplate::new("Quedan {count}").one("Queda {count}")),
533            Some(&"{count} de mรกs ({count})".into()),
534        );
535
536        assert_eq!(custom.snapshot("ab").text, "Queda 1");
537        assert_eq!(custom.snapshot("a").text, "Quedan 2");
538        assert_eq!(custom.snapshot("abcde").text, "2 de mรกs (2)");
539
540        let blank = Config::new(3, None, Some(&"  ".into()), None);
541
542        assert_eq!(blank.snapshot("a").text, "2 characters left");
543    }
544
545    #[test]
546    fn announces_only_when_crossing_thresholds_or_the_limit() {
547        let config = config(12, Some(&[10, 0]));
548        let step = |previous: &str, next: &str| {
549            config.announcement(Some(&config.snapshot(previous)), &config.snapshot(next))
550        };
551
552        assert_eq!(config.announcement(None, &config.snapshot("a")), None);
553        assert_eq!(step("", "a"), None);
554        assert_eq!(step("a", "ab").as_deref(), Some("10 characters left"));
555        assert_eq!(step("ab", "abc"), None);
556        assert_eq!(step("abc", "ab"), None, "deleting stays silent");
557        assert_eq!(
558            step("abc", &"a".repeat(13)).as_deref(),
559            Some("1 character over the limit")
560        );
561        assert_eq!(step(&"a".repeat(13), &"a".repeat(14)), None);
562        assert_eq!(
563            step(&"a".repeat(13), &"a".repeat(12)).as_deref(),
564            Some("0 characters left")
565        );
566        assert_eq!(
567            step(&"a".repeat(11), &"a".repeat(12)).as_deref(),
568            Some("0 characters left")
569        );
570    }
571
572    #[test]
573    fn a_new_limit_is_a_new_baseline() {
574        let before = config(12, None).snapshot("abc");
575        let after = config(3, None);
576
577        assert_eq!(
578            after.announcement(Some(&before), &after.snapshot("abcd")),
579            None
580        );
581        assert_eq!(
582            config(0, None).announcement(Some(&before), &config(0, None).snapshot("a")),
583            None
584        );
585    }
586
587    #[test]
588    fn repeated_messages_alternate_a_no_break_space() {
589        assert_eq!(live_text("", "1 left".to_string()), "1 left");
590        assert_eq!(live_text("1 left", "1 left".to_string()), "1 left\u{a0}");
591        assert_eq!(live_text("1 left\u{a0}", "1 left".to_string()), "1 left");
592    }
593}