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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! `CharacterCount`: the characters left for an input or textarea, with polite announcements.

// cspell:words Queda Quedan

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;

/// Remaining counts announced while typing when `announce_at` is not set.
const DEFAULT_THRESHOLDS: [u32; 3] = [20, 10, 0];
/// The largest limit or threshold lumen-core accepts.
const MAX_LIMIT: u32 = 1_000_000_000;
/// At most this many thresholds are kept.
const MAX_THRESHOLDS: usize = 12;
const COUNT_TOKEN: &str = "{count}";
/// Lumen's web runtime skips roots that carry `data-ui-owner`; lumen-react's value keeps the
/// markup identical.
const OWNER: &str = "react";

/// Visual state of a [`CharacterCount`], also its `data-state` value.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum CharacterCountState {
    /// Within the limit and above the first announcement threshold.
    #[default]
    Within,
    /// At or below the highest announcement threshold that is lower than the limit.
    Near,
    /// Over the limit.
    Over,
}

impl CharacterCountState {
    /// The `data-state` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Within => "within",
            Self::Near => "near",
            Self::Over => "over",
        }
    }
}

/// A message with a `{count}` placeholder, with an optional singular form.
///
/// Build one from a string to use the same text for every count, or with
/// [`CharacterCountTemplate::new`] and [`CharacterCountTemplate::one`] for English-style plurals:
///
/// ```
/// use lumen_dioxus::CharacterCountTemplate;
///
/// let left = CharacterCountTemplate::new("{count} letters left").one("{count} letter left");
///
/// assert_eq!(left.other, "{count} letters left");
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CharacterCountTemplate {
    /// Message for a count of exactly one. Falls back to `other`.
    pub one: Option<String>,
    /// Message for every other count.
    pub other: String,
}

impl CharacterCountTemplate {
    /// A template that uses `other` for every count.
    pub fn new(other: impl Into<String>) -> Self {
        Self {
            one: None,
            other: other.into(),
        }
    }

    /// Returns the template with a message for a count of exactly one.
    #[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")
    }

    /// The template, or `fallback` when it is missing or blank, like
    /// `resolveLumenCharacterCountTemplate`.
    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(),
        }
    }

    /// Replaces every `{count}` with the formatted count, picking the English plural form.
    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)
    }
}

/// Formats a count with English digit grouping (`1,999`), like `Intl.NumberFormat('en')`.
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
}

/// A positive limit of at most one billion, like `resolveLumenCharacterCountMax`.
fn resolve_max(max: u32) -> Option<u32> {
    (1..=MAX_LIMIT).contains(&max).then_some(max)
}

/// Valid, unique thresholds (at most 12, kept in order of appearance) sorted from highest to
/// lowest, like `resolveLumenCharacterCountThresholds`.
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
}

/// The resolved options of a counter.
#[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,
            ),
        }
    }

    /// The highest threshold below the limit; at or below it the counter is `near`.
    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()),
        }
    }

    /// Text to announce politely, or `None`, like `getLumenCharacterCountAnnouncement`: crossing a
    /// threshold while typing, going over the limit, or coming back within it announces once.
    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())
    }
}

/// Live-region text that is announced even when the message repeats: identical text would not
/// change the DOM, so it alternates a trailing no-break space, like
/// `getLumenCharacterCountLiveText`.
fn live_text(current: &str, message: String) -> String {
    if current == message {
        format!("{message}\u{a0}")
    } else {
        message
    }
}

/// The count, the characters left, and the visible text for a value and limit.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CharacterCountSnapshot {
    /// User-perceived characters (extended grapheme clusters).
    pub count: usize,
    /// The limit, or `None` when it is zero or above one billion.
    pub max: Option<u32>,
    /// Characters left; negative when over the limit, zero without a valid limit.
    pub remaining: i64,
    /// Within, near, or over the limit, with the default thresholds (20, 10, and 0 left).
    pub state: CharacterCountState,
    /// Visible text, such as `5 characters left`. Empty without a valid limit.
    pub text: String,
}

impl CharacterCountSnapshot {
    /// Counts `value` against `max` with the default thresholds and English messages, the same
    /// way [`CharacterCount`] does. Use it to validate the limit or to mark the control.
    pub fn new(value: &str, max: u32) -> Self {
        Config::new(max, None, None, None).snapshot(value)
    }
}

/// Props for [`CharacterCount`].
#[derive(Props, Clone, PartialEq)]
pub struct CharacterCountProps {
    /// Maximum user-perceived characters, from 1 to one billion. Other values render no text.
    /// Input is never truncated; validate the limit in the form.
    pub max: u32,
    /// The paired control's current value. The counter cannot read other elements, so pass the
    /// value the control's `oninput` stores.
    #[props(default, into)]
    pub value: String,
    /// Remaining counts that announce politely while typing. Defaults to 20, 10, and 0.
    pub announce_at: Option<Vec<u32>>,
    /// Text while within the limit. Defaults to `{count} characters left` (singular
    /// `{count} character left`). A blank template falls back to the default.
    #[props(default = CharacterCountTemplate::default_remaining(), into)]
    pub remaining_label: CharacterCountTemplate,
    /// Text while over the limit. Defaults to `{count} characters over the limit` (singular
    /// `{count} character over the limit`). A blank template falls back to the default.
    #[props(default = CharacterCountTemplate::default_over(), into)]
    pub over_label: CharacterCountTemplate,
    /// Set while the control is composing text with an input method; announcements wait until it
    /// ends.
    #[props(default)]
    pub composing: bool,
    /// Id of the count text. Defaults to a generated id. Add it to the control's
    /// `aria-describedby` so assistive technology reads the count.
    #[props(into)]
    pub value_id: Option<String>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<p>` or global attribute.
    #[props(extends = GlobalAttributes, extends = p)]
    pub attributes: Vec<Attribute>,
}

/// What the announcer last compared against and the live text it shows.
#[derive(Default)]
struct Announcer {
    announced: Option<CharacterCountSnapshot>,
    text: String,
}

/// Shows the characters left for an input or textarea and announces politely only at thresholds
/// and when crossing the limit. It never truncates input.
///
/// Counts are user-perceived characters (grapheme clusters), so an emoji with modifiers or a
/// letter with combining marks counts once, like lumen-react.
#[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
        );

        // With a limit of 15, the 20 threshold is skipped and 10 decides.
        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");
    }
}