1
//! Badge widget — a small rounded "pill" showing a short count or status string
2
//! (e.g. a notification count or a status label). A stateless, single styled
3
//! text node with no callback — a near-clone of [`crate::widgets::label::Label`]
4
//! restyled as a coloured pill, with an optional [`BadgeKind`] colour variant
5
//! (mirroring `button::ButtonType`).
6
//!
7
//! Key types: [`Badge`], [`BadgeKind`].
8

            
9
use azul_core::dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec};
10
use azul_css::{
11
    dynamic_selector::{
12
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
13
    },
14
    props::{
15
        basic::{color::ColorU, StyleFontSize},
16
        layout::{
17
            LayoutAlignItems, LayoutAlignSelf, LayoutDisplay, LayoutFlexDirection, LayoutFlexGrow,
18
            LayoutJustifyContent, LayoutPaddingBottom, LayoutPaddingLeft, LayoutPaddingRight,
19
            LayoutPaddingTop,
20
        },
21
        property::{CssProperty, *},
22
        style::{
23
            StyleBackgroundContent, StyleBackgroundContentVec, StyleBorderBottomLeftRadius,
24
            StyleBorderBottomRightRadius, StyleBorderTopLeftRadius, StyleBorderTopRightRadius,
25
            StyleTextAlign, StyleTextColor,
26
        },
27
    },
28
    AzString,
29
};
30

            
31
/// The semantic colour variant of a [`Badge`] (mirrors `button::ButtonType`).
32
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
33
#[repr(C)]
34
pub enum BadgeKind {
35
    /// Neutral grey badge — the default.
36
    #[default]
37
    Default,
38
    /// Blue "primary" badge.
39
    Primary,
40
    /// Green "success" badge.
41
    Success,
42
    /// Red "danger" badge.
43
    Danger,
44
    /// Yellow "warning" badge (uses dark text).
45
    Warning,
46
    /// Cyan "info" badge (uses dark text).
47
    Info,
48
}
49

            
50
impl BadgeKind {
51
    /// Returns the `(background, text)` colours for this badge kind.
52
    #[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
53
                                                 // pixel/coord path or to avoid churning call sites
54
                                                 // for a perf-neutral change)
55
777
    const fn colors(&self) -> (ColorU, ColorU) {
56
        const WHITE: ColorU = ColorU {
57
            r: 255,
58
            g: 255,
59
            b: 255,
60
            a: 255,
61
        };
62
        const DARK: ColorU = ColorU {
63
            r: 33,
64
            g: 37,
65
            b: 41,
66
            a: 255,
67
        };
68
777
        match self {
69
171
            Self::Default => (
70
171
                ColorU {
71
171
                    r: 108,
72
171
                    g: 117,
73
171
                    b: 125,
74
171
                    a: 255,
75
171
                },
76
171
                WHITE,
77
171
            ),
78
124
            Self::Primary => (
79
124
                ColorU {
80
124
                    r: 13,
81
124
                    g: 110,
82
124
                    b: 253,
83
124
                    a: 255,
84
124
                },
85
124
                WHITE,
86
124
            ),
87
119
            Self::Success => (
88
119
                ColorU {
89
119
                    r: 25,
90
119
                    g: 135,
91
119
                    b: 84,
92
119
                    a: 255,
93
119
                },
94
119
                WHITE,
95
119
            ),
96
121
            Self::Danger => (
97
121
                ColorU {
98
121
                    r: 220,
99
121
                    g: 53,
100
121
                    b: 69,
101
121
                    a: 255,
102
121
                },
103
121
                WHITE,
104
121
            ),
105
119
            Self::Warning => (
106
119
                ColorU {
107
119
                    r: 255,
108
119
                    g: 193,
109
119
                    b: 7,
110
119
                    a: 255,
111
119
                },
112
119
                DARK,
113
119
            ),
114
123
            Self::Info => (
115
123
                ColorU {
116
123
                    r: 13,
117
123
                    g: 202,
118
123
                    b: 240,
119
123
                    a: 255,
120
123
                },
121
123
                DARK,
122
123
            ),
123
        }
124
777
    }
125

            
126
    /// CSS class name for this badge kind (mirrors `ButtonType::class_name`).
127
    #[must_use]
128
19
    pub const fn class_name(&self) -> &'static str {
129
19
        match self {
130
4
            Self::Default => "__azul-badge-default",
131
3
            Self::Primary => "__azul-badge-primary",
132
3
            Self::Success => "__azul-badge-success",
133
3
            Self::Danger => "__azul-badge-danger",
134
3
            Self::Warning => "__azul-badge-warning",
135
3
            Self::Info => "__azul-badge-info",
136
        }
137
19
    }
138
}
139

            
140
/// A small rounded pill showing a short status/count string. Stateless;
141
/// renders a single styled text node.
142
#[derive(Debug, Clone, PartialEq, Eq)]
143
#[repr(C)]
144
pub struct Badge {
145
    /// The text shown inside the pill.
146
    pub string: AzString,
147
    /// The colour variant.
148
    pub kind: BadgeKind,
149
    /// The pill's CSS, or `None` for "no opinion" — in which case the style is
150
    /// derived from `kind` at render time.
151
    ///
152
    /// `None` and `Some(empty)` are different answers: the first means the
153
    /// widget picks, the second means the caller asked for no properties at all
154
    /// and gets none.
155
    pub badge_style: OptionCssPropertyWithConditionsVec,
156
}
157

            
158
/// Builds the pill style for a given [`BadgeKind`]. The colours are the only
159
/// kind-dependent properties, so the style is built at runtime per the recipe's
160
/// "runtime vec when param-dependent" path (see `switch::build_track_style`).
161
591
fn build_badge_style(kind: BadgeKind) -> CssPropertyWithConditionsVec {
162
591
    let (bg, text) = kind.colors();
163
591
    let bg_vec =
164
591
        StyleBackgroundContentVec::from_vec(alloc::vec![StyleBackgroundContent::Color(bg)]);
165
591
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
166
591
        CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
167
591
        CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
168
591
            LayoutFlexDirection::Row,
169
        )),
170
591
        CssPropertyWithConditions::simple(CssProperty::const_justify_content(
171
591
            LayoutJustifyContent::Center,
172
        )),
173
591
        CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
174
        // Hug the content rather than stretch across a flex parent's cross axis.
175
591
        CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Start)),
176
591
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
177
            0,
178
        ))),
179
        // padding: 2px 8px
180
591
        CssPropertyWithConditions::simple(CssProperty::const_padding_top(
181
591
            LayoutPaddingTop::const_px(2,)
182
        )),
183
591
        CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
184
591
            LayoutPaddingBottom::const_px(2),
185
        )),
186
591
        CssPropertyWithConditions::simple(CssProperty::const_padding_left(
187
591
            LayoutPaddingLeft::const_px(8),
188
        )),
189
591
        CssPropertyWithConditions::simple(CssProperty::const_padding_right(
190
591
            LayoutPaddingRight::const_px(8),
191
        )),
192
        // border-radius: 10px (pill)
193
591
        CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
194
591
            StyleBorderTopLeftRadius::const_px(10),
195
        )),
196
591
        CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
197
591
            StyleBorderTopRightRadius::const_px(10),
198
        )),
199
591
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
200
591
            StyleBorderBottomLeftRadius::const_px(10),
201
        )),
202
591
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
203
591
            StyleBorderBottomRightRadius::const_px(10),
204
        )),
205
591
        CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(
206
            12
207
        ))),
208
591
        CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Center)),
209
591
        CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
210
591
            inner: text,
211
591
        })),
212
591
        CssPropertyWithConditions::simple(CssProperty::const_background_content(bg_vec)),
213
    ])
214
591
}
215

            
216
impl Badge {
217
    /// Creates a new badge with the given text and the default (grey) kind.
218
    #[inline]
219
    #[must_use]
220
81
    pub const fn create(string: AzString) -> Self {
221
81
        Self::with_kind(string, BadgeKind::Default)
222
81
    }
223

            
224
    /// Creates a new badge with the given text and colour variant.
225
    #[inline]
226
    #[must_use]
227
178
    pub const fn with_kind(string: AzString, kind: BadgeKind) -> Self {
228
178
        Self {
229
178
            string,
230
178
            kind,
231
178
            badge_style: OptionCssPropertyWithConditionsVec::None,
232
178
        }
233
178
    }
234

            
235
    /// The pill CSS this badge renders with.
236
    ///
237
    /// `None` means no opinion, so the kind's default applies — the same answer
238
    /// both themes give, asked in one place so they cannot drift.
239
    #[must_use]
240
357
    pub fn resolved_badge_style(&self) -> CssPropertyWithConditionsVec {
241
357
        self.badge_style
242
357
            .clone()
243
357
            .into_option()
244
357
            .unwrap_or_else(|| build_badge_style(self.kind))
245
357
    }
246

            
247
    /// Sets the colour variant.
248
    ///
249
    /// Does not touch `badge_style`: the style is resolved from `kind` when the
250
    /// DOM is built, so changing the kind is enough. Writing it here would also
251
    /// overwrite a caller's explicit style.
252
    #[inline]
253
74
    pub const fn set_kind(&mut self, kind: BadgeKind) {
254
74
        self.kind = kind;
255
74
    }
256

            
257
    /// Builder-style setter for the colour variant.
258
    #[inline]
259
    #[must_use]
260
9
    pub const fn with_badge_kind(mut self, kind: BadgeKind) -> Self {
261
9
        self.set_kind(kind);
262
9
        self
263
9
    }
264

            
265
    /// Replaces `self` with an empty default badge and returns the original.
266
    #[inline]
267
    #[must_use]
268
13
    pub const fn swap_with_default(&mut self) -> Self {
269
13
        let mut s = Self::create(AzString::from_const_str(""));
270
13
        core::mem::swap(&mut s, self);
271
13
        s
272
13
    }
273

            
274
    /// Converts this badge into a `<p>` pill carrying the
275
    /// `__azul-native-badge` class and wrapping a bare text node.
276
    ///
277
    /// The pill's background, padding and border-radius live on the `<p>`: a
278
    /// `NodeType::Text` node is always inline-level and owns no rect, so those
279
    /// properties would never paint on a raw text node.
280
    #[inline]
281
    #[must_use]
282
41
    pub fn dom(self) -> Dom {
283
        static BADGE_CLASS: &[IdOrClass] =
284
            &[Class(AzString::from_const_str("__azul-native-badge"))];
285

            
286
        // Resolved before `self.string` is moved out below.
287
41
        let badge_style = self.resolved_badge_style();
288

            
289
41
        crate::widgets::widget_p_with_text(self.string)
290
41
            .with_ids_and_classes(IdOrClassVec::from_const_slice(BADGE_CLASS))
291
41
            .with_css_props(badge_style)
292
41
    }
293
}
294

            
295
impl Default for Badge {
296
25
    fn default() -> Self {
297
25
        Self::create(AzString::from_const_str(""))
298
25
    }
299
}
300

            
301
impl From<Badge> for Dom {
302
6
    fn from(b: Badge) -> Self {
303
6
        b.dom()
304
6
    }
305
}
306

            
307
#[cfg(test)]
308
mod autotest_generated {
309
    use std::collections::HashSet;
310

            
311
    use azul_core::dom::NodeType;
312
    use azul_css::props::basic::{length::SizeMetric, pixel::PixelValue};
313

            
314
    use super::*;
315

            
316
    // ------------------------------------------------------------------
317
    // Helpers
318
    // ------------------------------------------------------------------
319

            
320
    /// Every variant of `BadgeKind` — the complete input domain of `colors`,
321
    /// `class_name` and `build_badge_style`.
322
    const ALL_KINDS: [BadgeKind; 6] = [
323
        BadgeKind::Default,
324
        BadgeKind::Primary,
325
        BadgeKind::Success,
326
        BadgeKind::Danger,
327
        BadgeKind::Warning,
328
        BadgeKind::Info,
329
    ];
330

            
331
    const WHITE: ColorU = ColorU {
332
        r: 255,
333
        g: 255,
334
        b: 255,
335
        a: 255,
336
    };
337
    const DARK: ColorU = ColorU {
338
        r: 33,
339
        g: 37,
340
        b: 41,
341
        a: 255,
342
    };
343

            
344
    /// The declared properties of a style vec, in declaration order.
345
    fn properties(v: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
346
        v.as_ref().iter().map(|p| p.property.clone()).collect()
347
    }
348

            
349
    /// The `f32` of a `PixelValue`, asserting it is an absolute `px` length — an
350
    /// `em`/`%` slipping into the pill geometry would resolve against the parent
351
    /// font/box instead of the intended fixed padding or radius.
352
    fn px(pv: &PixelValue) -> f32 {
353
        assert_eq!(
354
            pv.metric,
355
            SizeMetric::Px,
356
            "badge geometry must be absolute px, got {:?}",
357
            pv.metric
358
        );
359
        pv.number.get()
360
    }
361

            
362
    /// The four paddings in `(top, bottom, left, right)` order.
363
    fn padding_px(
364
        v: &CssPropertyWithConditionsVec,
365
    ) -> (Option<f32>, Option<f32>, Option<f32>, Option<f32>) {
366
        let find = |f: &dyn Fn(&CssProperty) -> Option<f32>| {
367
            v.as_ref().iter().find_map(|p| f(&p.property))
368
        };
369
        (
370
            find(&|p| match p {
371
                CssProperty::PaddingTop(x) => x.get_property().map(|x| px(&x.inner)),
372
                _ => None,
373
            }),
374
            find(&|p| match p {
375
                CssProperty::PaddingBottom(x) => x.get_property().map(|x| px(&x.inner)),
376
                _ => None,
377
            }),
378
            find(&|p| match p {
379
                CssProperty::PaddingLeft(x) => x.get_property().map(|x| px(&x.inner)),
380
                _ => None,
381
            }),
382
            find(&|p| match p {
383
                CssProperty::PaddingRight(x) => x.get_property().map(|x| px(&x.inner)),
384
                _ => None,
385
            }),
386
        )
387
    }
388

            
389
    /// The four corner radii, in declaration order.
390
    fn radii_px(v: &CssPropertyWithConditionsVec) -> Vec<f32> {
391
        v.as_ref()
392
            .iter()
393
            .filter_map(|p| match &p.property {
394
                CssProperty::BorderTopLeftRadius(r) => r.get_property().map(|r| px(&r.inner)),
395
                CssProperty::BorderTopRightRadius(r) => r.get_property().map(|r| px(&r.inner)),
396
                CssProperty::BorderBottomLeftRadius(r) => r.get_property().map(|r| px(&r.inner)),
397
                CssProperty::BorderBottomRightRadius(r) => r.get_property().map(|r| px(&r.inner)),
398
                _ => None,
399
            })
400
            .collect()
401
    }
402

            
403
    fn font_size_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
404
        v.as_ref().iter().find_map(|p| match &p.property {
405
            CssProperty::FontSize(f) => f.get_property().map(|f| px(&f.inner)),
406
            _ => None,
407
        })
408
    }
409

            
410
    fn text_color(v: &CssPropertyWithConditionsVec) -> Option<ColorU> {
411
        v.as_ref().iter().find_map(|p| match &p.property {
412
            CssProperty::TextColor(c) => c.get_property().map(|c| c.inner),
413
            _ => None,
414
        })
415
    }
416

            
417
    /// The single background layer of a style vec, asserting there is exactly one
418
    /// and that it is a flat colour (a gradient would not be a `Color`).
419
    fn background_color(v: &CssPropertyWithConditionsVec) -> Option<ColorU> {
420
        let bg = v.as_ref().iter().find_map(|p| match &p.property {
421
            CssProperty::BackgroundContent(b) => b.get_property(),
422
            _ => None,
423
        })?;
424
        assert_eq!(
425
            bg.as_ref().len(),
426
            1,
427
            "a badge must declare exactly one background layer"
428
        );
429
        match &bg.as_ref()[0] {
430
            StyleBackgroundContent::Color(c) => Some(*c),
431
            other => panic!("badge background is not a flat colour: {other:?}"),
432
        }
433
    }
434

            
435
    /// Every `PixelValue` a style vec mentions (paddings, radii, font size).
436
    fn all_pixel_values(v: &CssPropertyWithConditionsVec) -> Vec<PixelValue> {
437
        v.as_ref()
438
            .iter()
439
            .filter_map(|p| match &p.property {
440
                CssProperty::PaddingTop(x) => x.get_property().map(|x| x.inner),
441
                CssProperty::PaddingBottom(x) => x.get_property().map(|x| x.inner),
442
                CssProperty::PaddingLeft(x) => x.get_property().map(|x| x.inner),
443
                CssProperty::PaddingRight(x) => x.get_property().map(|x| x.inner),
444
                CssProperty::BorderTopLeftRadius(r) => r.get_property().map(|r| r.inner),
445
                CssProperty::BorderTopRightRadius(r) => r.get_property().map(|r| r.inner),
446
                CssProperty::BorderBottomLeftRadius(r) => r.get_property().map(|r| r.inner),
447
                CssProperty::BorderBottomRightRadius(r) => r.get_property().map(|r| r.inner),
448
                CssProperty::FontSize(f) => f.get_property().map(|f| f.inner),
449
                _ => None,
450
            })
451
            .collect()
452
    }
453

            
454
    /// Perceived brightness (0..=255) of an sRGB colour, Rec.709 weights. Kept to
455
    /// plain `+`/`*` (no gamma expansion) so the readability assertions below stay
456
    /// exact and toolchain-independent.
457
    fn luma(c: ColorU) -> f32 {
458
        0.2126 * f32::from(c.r) + 0.7152 * f32::from(c.g) + 0.0722 * f32::from(c.b)
459
    }
460

            
461
    /// True if `node` carries the CSS class `name`.
462
    fn has_class(node: &Dom, name: &str) -> bool {
463
        node.root
464
            .get_ids_and_classes()
465
            .as_ref()
466
            .iter()
467
            .any(|c| matches!(c, Class(s) if s.as_str() == name))
468
    }
469

            
470
    /// The properties of a rendered node's *inline* style, in declaration order.
471
    fn inline_properties(node: &Dom) -> Vec<CssProperty> {
472
        node.root
473
            .style
474
            .iter_inline_properties()
475
            .map(|(p, _)| p.clone())
476
            .collect()
477
    }
478

            
479
    /// The text carried by a text node, looking through the `<p>` block
480
    /// wrapper the label convention mandates (`p > text`).
481
    fn text_of(node: &Dom) -> Option<&str> {
482
        match node.root.get_node_type() {
483
            NodeType::Text(s) => Some(s.as_ref().as_str()),
484
            NodeType::P => match node.children.as_ref() {
485
                [only] => match only.root.get_node_type() {
486
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
487
                    _ => None,
488
                },
489
                _ => None,
490
            },
491
            _ => None,
492
        }
493
    }
494

            
495
    /// Adversarial badge texts: empty, whitespace, combining marks, ZWJ emoji,
496
    /// RTL, embedded NULs (`AzString` is length-based, so a NUL must not
497
    /// truncate) and a string far longer than any plausible badge label.
498
    fn adversarial_strings() -> Vec<String> {
499
        let mut v: Vec<String> = [
500
            "",
501
            "9",
502
            "99+",
503
            " ",
504
            "e\u{0301}",                                   // e + combining acute
505
            "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}", // ZWJ family emoji
506
            "\u{5E9}\u{5DC}\u{5D5}\u{5DD}",                // RTL Hebrew
507
            "\0",                                          // a single NUL
508
            "a\0b",                                        // embedded NUL
509
            "\u{FFFD}\u{202E}\u{200B}",                    // replacement char, RTL override, ZWSP
510
            "-9223372036854775808",                        // i64::MIN as a "count"
511
        ]
512
        .iter()
513
        .map(|s| (*s).to_string())
514
        .collect();
515
        v.push("x".repeat(100_000));
516
        v
517
    }
518

            
519
    // ------------------------------------------------------------------
520
    // BadgeKind::colors  (getter)
521
    // ------------------------------------------------------------------
522

            
523
    #[test]
524
    fn colors_returns_the_documented_constants_for_every_kind() {
525
        let expected = [
526
            (
527
                BadgeKind::Default,
528
                ColorU {
529
                    r: 108,
530
                    g: 117,
531
                    b: 125,
532
                    a: 255,
533
                },
534
                WHITE,
535
            ),
536
            (
537
                BadgeKind::Primary,
538
                ColorU {
539
                    r: 13,
540
                    g: 110,
541
                    b: 253,
542
                    a: 255,
543
                },
544
                WHITE,
545
            ),
546
            (
547
                BadgeKind::Success,
548
                ColorU {
549
                    r: 25,
550
                    g: 135,
551
                    b: 84,
552
                    a: 255,
553
                },
554
                WHITE,
555
            ),
556
            (
557
                BadgeKind::Danger,
558
                ColorU {
559
                    r: 220,
560
                    g: 53,
561
                    b: 69,
562
                    a: 255,
563
                },
564
                WHITE,
565
            ),
566
            (
567
                BadgeKind::Warning,
568
                ColorU {
569
                    r: 255,
570
                    g: 193,
571
                    b: 7,
572
                    a: 255,
573
                },
574
                DARK,
575
            ),
576
            (
577
                BadgeKind::Info,
578
                ColorU {
579
                    r: 13,
580
                    g: 202,
581
                    b: 240,
582
                    a: 255,
583
                },
584
                DARK,
585
            ),
586
        ];
587
        for (kind, bg, text) in expected {
588
            assert_eq!(
589
                kind.colors(),
590
                (bg, text),
591
                "{kind:?}: wrong (background, text) pair"
592
            );
593
        }
594
        // The doc comments promise Warning/Info are the dark-text kinds and no
595
        // others: a fifth white-text kind sneaking in here is a regression.
596
        for kind in ALL_KINDS {
597
            let (_, text) = kind.colors();
598
            let dark_text = matches!(kind, BadgeKind::Warning | BadgeKind::Info);
599
            assert_eq!(
600
                text == DARK,
601
                dark_text,
602
                "{kind:?}: text colour contradicts the documented variant"
603
            );
604
        }
605
    }
606

            
607
    #[test]
608
    fn colors_are_fully_opaque_on_every_kind() {
609
        // A non-opaque pill would let the page background bleed through and
610
        // silently destroy the contrast the kind was chosen for.
611
        for kind in ALL_KINDS {
612
            let (bg, text) = kind.colors();
613
            assert_eq!(bg.a, 255, "{kind:?}: translucent background {bg:?}");
614
            assert_eq!(text.a, 255, "{kind:?}: translucent text colour {text:?}");
615
        }
616
    }
617

            
618
    #[test]
619
    fn colors_give_every_kind_a_distinguishable_background() {
620
        // Two kinds that render identically make the semantic variant useless.
621
        let mut seen = HashSet::new();
622
        for kind in ALL_KINDS {
623
            let (bg, _) = kind.colors();
624
            assert!(
625
                seen.insert((bg.r, bg.g, bg.b, bg.a)),
626
                "{kind:?}: duplicate background colour {bg:?}"
627
            );
628
        }
629
        assert_eq!(seen.len(), ALL_KINDS.len());
630
    }
631

            
632
    #[test]
633
    fn colors_pick_the_more_readable_of_the_two_text_colours() {
634
        // The only real invariant of `colors()`: the text must be legible on the
635
        // pill. For each kind the chosen text colour must be further from the
636
        // background (in perceived brightness) than the rejected alternative,
637
        // and light backgrounds must take the dark text.
638
        for kind in ALL_KINDS {
639
            let (bg, text) = kind.colors();
640
            let other = if text == WHITE { DARK } else { WHITE };
641

            
642
            let chosen = (luma(bg) - luma(text)).abs();
643
            let rejected = (luma(bg) - luma(other)).abs();
644
            assert!(
645
                chosen > rejected,
646
                "{kind:?}: text {text:?} (Δluma {chosen:.1}) is less readable on {bg:?} than \
647
                 {other:?} (Δluma {rejected:.1})"
648
            );
649
            assert!(
650
                chosen >= 60.0,
651
                "{kind:?}: text/background brightness gap {chosen:.1} is too low to read"
652
            );
653

            
654
            // Mid-grey split: a light pill must not carry white text.
655
            let light_bg = luma(bg) >= 128.0;
656
            assert_eq!(
657
                text == DARK,
658
                light_bg,
659
                "{kind:?}: bg luma {:.1} but text is {text:?}",
660
                luma(bg)
661
            );
662
        }
663
    }
664

            
665
    #[test]
666
    fn colors_is_pure_and_the_default_kind_is_grey() {
667
        assert_eq!(BadgeKind::default(), BadgeKind::Default);
668
        assert_eq!(BadgeKind::default().colors(), BadgeKind::Default.colors());
669
        // `colors()` takes `&self` on a `Copy` enum: repeated calls, and calls
670
        // through a copy, must be side-effect free and identical.
671
        for kind in ALL_KINDS {
672
            let copy = kind;
673
            assert_eq!(
674
                kind.colors(),
675
                kind.colors(),
676
                "{kind:?}: colors() is not pure"
677
            );
678
            assert_eq!(
679
                kind.colors(),
680
                copy.colors(),
681
                "{kind:?}: a copy disagrees with the original"
682
            );
683
        }
684
    }
685

            
686
    // ------------------------------------------------------------------
687
    // BadgeKind::class_name  (getter)
688
    // ------------------------------------------------------------------
689

            
690
    #[test]
691
    fn class_name_returns_the_documented_string_for_every_kind() {
692
        assert_eq!(BadgeKind::Default.class_name(), "__azul-badge-default");
693
        assert_eq!(BadgeKind::Primary.class_name(), "__azul-badge-primary");
694
        assert_eq!(BadgeKind::Success.class_name(), "__azul-badge-success");
695
        assert_eq!(BadgeKind::Danger.class_name(), "__azul-badge-danger");
696
        assert_eq!(BadgeKind::Warning.class_name(), "__azul-badge-warning");
697
        assert_eq!(BadgeKind::Info.class_name(), "__azul-badge-info");
698
        assert_eq!(BadgeKind::default().class_name(), "__azul-badge-default");
699
    }
700

            
701
    #[test]
702
    fn class_name_is_unique_per_kind_and_a_usable_css_identifier() {
703
        let mut seen = HashSet::new();
704
        for kind in ALL_KINDS {
705
            let name = kind.class_name();
706
            assert!(
707
                seen.insert(name),
708
                "{kind:?}: class name {name:?} collides with another kind"
709
            );
710
            assert!(!name.is_empty(), "{kind:?}: empty class name");
711
            assert!(
712
                name.starts_with("__azul-badge-"),
713
                "{kind:?}: unnamespaced class {name:?}"
714
            );
715
            assert!(name.is_ascii(), "{kind:?}: non-ASCII class name {name:?}");
716
            // A space, a dot or a `#` would silently split/re-target the selector.
717
            assert!(
718
                name.chars()
719
                    .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'),
720
                "{kind:?}: class name {name:?} contains a CSS-significant character"
721
            );
722
            // The returned `&'static str` must be stable across calls.
723
            assert_eq!(
724
                name.as_ptr(),
725
                kind.class_name().as_ptr(),
726
                "{kind:?}: class_name() is not a stable constant"
727
            );
728
        }
729
        assert_eq!(seen.len(), ALL_KINDS.len());
730
    }
731

            
732
    // ------------------------------------------------------------------
733
    // build_badge_style
734
    // ------------------------------------------------------------------
735

            
736
    #[test]
737
    fn build_badge_style_emits_the_documented_pill_geometry() {
738
        for kind in ALL_KINDS {
739
            let style = build_badge_style(kind);
740
            assert_eq!(
741
                padding_px(&style),
742
                (Some(2.0), Some(2.0), Some(8.0), Some(8.0)),
743
                "{kind:?}: padding is not 2px 8px"
744
            );
745
            assert_eq!(
746
                radii_px(&style),
747
                vec![10.0, 10.0, 10.0, 10.0],
748
                "{kind:?}: all four corners must carry a 10px radius"
749
            );
750
            assert_eq!(
751
                font_size_px(&style),
752
                Some(12.0),
753
                "{kind:?}: wrong font size"
754
            );
755
        }
756
    }
757

            
758
    #[test]
759
    fn build_badge_style_radius_actually_rounds_the_pill_to_a_semicircle() {
760
        // The widget's premise: the corner radius must reach at least half the
761
        // content height (font + vertical padding), otherwise it renders as a
762
        // rounded rectangle rather than a pill.
763
        for kind in ALL_KINDS {
764
            let style = build_badge_style(kind);
765
            let (top, bottom, ..) = padding_px(&style);
766
            let height = font_size_px(&style).expect("a font size must be declared")
767
                + top.expect("padding-top")
768
                + bottom.expect("padding-bottom");
769
            for r in radii_px(&style) {
770
                assert!(
771
                    r * 2.0 >= height,
772
                    "{kind:?}: radius {r} does not reach half of the {height}px pill height"
773
                );
774
            }
775
        }
776
    }
777

            
778
    #[test]
779
    fn build_badge_style_hugs_its_content_and_centres_the_text() {
780
        for kind in ALL_KINDS {
781
            let props = properties(&build_badge_style(kind));
782
            let has = |p: &CssProperty| props.contains(p);
783

            
784
            assert!(
785
                has(&CssProperty::const_display(LayoutDisplay::Flex)),
786
                "{kind:?}: not a flex box"
787
            );
788
            assert!(
789
                has(&CssProperty::const_flex_direction(LayoutFlexDirection::Row)),
790
                "{kind:?}: wrong flex direction"
791
            );
792
            assert!(
793
                has(&CssProperty::const_justify_content(
794
                    LayoutJustifyContent::Center
795
                )),
796
                "{kind:?}: text not centred"
797
            );
798
            assert!(
799
                has(&CssProperty::const_align_items(LayoutAlignItems::Center)),
800
                "{kind:?}: text not centred"
801
            );
802
            assert!(
803
                has(&CssProperty::const_text_align(StyleTextAlign::Center)),
804
                "{kind:?}: text not centred"
805
            );
806
            // align-self: start + flex-grow: 0 — without both, the pill stretches
807
            // across a flex parent instead of hugging its label.
808
            assert!(
809
                has(&CssProperty::align_self(LayoutAlignSelf::Start)),
810
                "{kind:?}: badge stretches on the cross axis"
811
            );
812
            assert!(
813
                has(&CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
814
                "{kind:?}: badge grows on the main axis"
815
            );
816
        }
817
    }
818

            
819
    #[test]
820
    fn build_badge_style_colours_track_the_kind() {
821
        for kind in ALL_KINDS {
822
            let style = build_badge_style(kind);
823
            let (bg, text) = kind.colors();
824
            assert_eq!(
825
                background_color(&style),
826
                Some(bg),
827
                "{kind:?}: emitted background != colors().0"
828
            );
829
            assert_eq!(
830
                text_color(&style),
831
                Some(text),
832
                "{kind:?}: emitted text colour != colors().1"
833
            );
834
        }
835
    }
836

            
837
    #[test]
838
    fn build_badge_style_declares_every_property_at_most_once() {
839
        // A duplicated declaration is a last-one-wins ambiguity: two backgrounds
840
        // would make one of them silently dead.
841
        for kind in ALL_KINDS {
842
            let props = properties(&build_badge_style(kind));
843
            let mut seen = HashSet::new();
844
            for p in &props {
845
                assert!(
846
                    seen.insert(core::mem::discriminant(p)),
847
                    "{kind:?}: duplicate declaration of {p:?}"
848
                );
849
            }
850
            assert_eq!(seen.len(), props.len());
851
        }
852
    }
853

            
854
    #[test]
855
    fn build_badge_style_properties_are_all_unconditional() {
856
        // A badge is stateless — a declaration gated on `:hover`/`:active` would
857
        // simply never paint.
858
        for kind in ALL_KINDS {
859
            for p in build_badge_style(kind).as_ref() {
860
                assert!(
861
                    p.apply_if.as_ref().is_empty(),
862
                    "{kind:?}: {:?} is conditional on a stateless widget",
863
                    p.property
864
                );
865
            }
866
        }
867
    }
868

            
869
    #[test]
870
    fn build_badge_style_is_deterministic_and_kind_dependent() {
871
        let len = build_badge_style(BadgeKind::Default).as_ref().len();
872
        for kind in ALL_KINDS {
873
            assert_eq!(
874
                properties(&build_badge_style(kind)),
875
                properties(&build_badge_style(kind)),
876
                "{kind:?}: two builds of the same kind disagree"
877
            );
878
            assert_eq!(
879
                build_badge_style(kind).as_ref().len(),
880
                len,
881
                "{kind:?}: emits a different number of declarations than Default"
882
            );
883
        }
884
        // No two kinds may collapse onto the same style, or the variant is a no-op.
885
        for (i, a) in ALL_KINDS.iter().enumerate() {
886
            for b in &ALL_KINDS[i + 1..] {
887
                assert_ne!(
888
                    properties(&build_badge_style(*a)),
889
                    properties(&build_badge_style(*b)),
890
                    "{a:?} and {b:?} produce an identical style"
891
                );
892
            }
893
        }
894
    }
895

            
896
    #[test]
897
    fn build_badge_style_emits_only_finite_non_negative_px_lengths() {
898
        // Guard the one numeric conversion in this file (`isize` -> `PixelValue`):
899
        // a NaN/inf/negative length must never reach the layout solver.
900
        for kind in ALL_KINDS {
901
            let values = all_pixel_values(&build_badge_style(kind));
902
            assert_eq!(
903
                values.len(),
904
                9,
905
                "{kind:?}: expected 4 paddings + 4 radii + 1 font size"
906
            );
907
            for pv in values {
908
                let n = px(&pv); // also asserts SizeMetric::Px
909
                assert!(n.is_finite(), "{kind:?}: non-finite length {n}");
910
                assert!(n >= 0.0, "{kind:?}: negative length {n}");
911
                assert!(
912
                    n <= 128.0,
913
                    "{kind:?}: implausibly large length {n} for a badge"
914
                );
915
            }
916
        }
917
    }
918

            
919
    // ------------------------------------------------------------------
920
    // Badge::create / Badge::with_kind  (constructors)
921
    // ------------------------------------------------------------------
922

            
923
    #[test]
924
    fn create_defaults_to_grey_and_keeps_the_text_verbatim() {
925
        for s in adversarial_strings() {
926
            let b = Badge::create(AzString::from(s.clone()));
927
            assert_eq!(
928
                b.string.as_str(),
929
                s.as_str(),
930
                "the label was not preserved verbatim"
931
            );
932
            assert_eq!(
933
                b.string.len(),
934
                s.len(),
935
                "byte length changed (NUL truncation?)"
936
            );
937
            assert_eq!(
938
                b.kind,
939
                BadgeKind::Default,
940
                "create() must use the grey default kind"
941
            );
942
            assert_eq!(
943
                properties(&b.resolved_badge_style()),
944
                properties(&build_badge_style(BadgeKind::Default))
945
            );
946
        }
947
    }
948

            
949
    #[test]
950
    fn with_kind_stores_both_arguments_and_the_matching_style() {
951
        for kind in ALL_KINDS {
952
            for s in adversarial_strings() {
953
                let b = Badge::with_kind(AzString::from(s.clone()), kind);
954
                assert_eq!(
955
                    b.string.as_str(),
956
                    s.as_str(),
957
                    "{kind:?}: label not preserved"
958
                );
959
                assert_eq!(b.string.len(), s.len(), "{kind:?}: byte length changed");
960
                assert_eq!(
961
                    b.kind, kind,
962
                    "{kind:?}: kind field does not match the argument"
963
                );
964
                // The resolver has to answer from `kind`, not from a stored vec.
965
                assert_eq!(
966
                    properties(&b.resolved_badge_style()),
967
                    properties(&build_badge_style(kind))
968
                );
969
                assert_eq!(
970
                    background_color(&b.resolved_badge_style()),
971
                    Some(kind.colors().0)
972
                );
973
            }
974
        }
975
    }
976

            
977
    #[test]
978
    fn create_is_with_kind_default() {
979
        for s in ["", "99+", "\u{1F600}"] {
980
            assert_eq!(
981
                Badge::create(AzString::from_const_str(s)),
982
                Badge::with_kind(AzString::from_const_str(s), BadgeKind::Default)
983
            );
984
        }
985
    }
986

            
987
    #[test]
988
    fn default_badge_is_an_empty_grey_badge_and_equality_sees_every_field() {
989
        let d = Badge::default();
990
        assert_eq!(d, Badge::create(AzString::from_const_str("")));
991
        assert_eq!(d.string.as_str(), "");
992
        assert_eq!(d.kind, BadgeKind::Default);
993
        assert_eq!(d.clone(), d, "Clone must preserve equality");
994

            
995
        assert_ne!(
996
            d,
997
            Badge::create(AzString::from_const_str("9")),
998
            "the label must affect equality"
999
        );
        assert_ne!(
            Badge::with_kind(AzString::from_const_str("9"), BadgeKind::Danger),
            Badge::with_kind(AzString::from_const_str("9"), BadgeKind::Success),
            "badges of different kinds must not compare equal"
        );
    }
    // ------------------------------------------------------------------
    // Badge::set_kind / with_badge_kind  (setters)
    // ------------------------------------------------------------------
    #[test]
    fn set_kind_recomputes_the_style_without_growing_it() {
        // A push-instead-of-replace bug would grow the style vec on every call and
        // leave stale (earlier-kind) colour declarations behind, which then win or
        // lose the cascade by accident.
        let mut b = Badge::create(AzString::from_const_str("99+"));
        let expected_len = build_badge_style(BadgeKind::Default).as_ref().len();
        for round in 0..50 {
            let kind = ALL_KINDS[round % ALL_KINDS.len()];
            b.set_kind(kind);
            assert_eq!(b.kind, kind, "round {round}: kind field not updated");
            assert_eq!(
                b.resolved_badge_style().as_slice().len(),
                expected_len,
                "round {round}: style vec changed length — stale declarations?"
            );
            assert_eq!(
                properties(&b.resolved_badge_style()),
                properties(&build_badge_style(kind)),
                "round {round}: style does not match a freshly built one"
            );
            assert_eq!(
                background_color(&b.resolved_badge_style()),
                Some(kind.colors().0),
                "round {round}: stale background"
            );
            assert_eq!(
                b.string.as_str(),
                "99+",
                "round {round}: set_kind ate the label"
            );
        }
    }
    #[test]
    fn with_badge_kind_agrees_with_set_kind_and_is_last_call_wins() {
        let chained = Badge::create(AzString::from_const_str("9"))
            .with_badge_kind(BadgeKind::Danger)
            .with_badge_kind(BadgeKind::Warning)
            .with_badge_kind(BadgeKind::Info);
        let mut mutated = Badge::create(AzString::from_const_str("9"));
        mutated.set_kind(BadgeKind::Danger);
        mutated.set_kind(BadgeKind::Warning);
        mutated.set_kind(BadgeKind::Info);
        assert_eq!(chained, mutated, "the builder and the mutator must agree");
        assert_eq!(chained.kind, BadgeKind::Info);
        assert_eq!(chained.string.as_str(), "9");
        assert_eq!(
            properties(&chained.resolved_badge_style()),
            properties(&build_badge_style(BadgeKind::Info))
        );
        // In particular the Danger red must be completely gone.
        assert_eq!(
            background_color(&chained.resolved_badge_style()),
            Some(BadgeKind::Info.colors().0)
        );
    }
    #[test]
    fn setting_the_same_kind_twice_is_idempotent() {
        for kind in ALL_KINDS {
            let once = Badge::with_kind(AzString::from_const_str("x"), kind);
            let twice = once.clone().with_badge_kind(kind);
            assert_eq!(
                once, twice,
                "{kind:?}: re-setting the same kind changed the badge"
            );
        }
    }
    // ------------------------------------------------------------------
    // Badge::swap_with_default
    // ------------------------------------------------------------------
    #[test]
    fn swap_with_default_returns_the_original_and_leaves_a_default_behind() {
        let mut b = Badge::with_kind(AzString::from_const_str("99+"), BadgeKind::Danger);
        let taken = b.swap_with_default();
        // The returned value is the *original*, intact.
        assert_eq!(taken.string.as_str(), "99+");
        assert_eq!(taken.kind, BadgeKind::Danger);
        assert_eq!(
            properties(&taken.resolved_badge_style()),
            properties(&build_badge_style(BadgeKind::Danger))
        );
        // What is left behind is a *default* badge — in particular its style must
        // be the grey one and not a stale Danger red.
        assert_eq!(b, Badge::default());
        assert_eq!(b.string.as_str(), "");
        assert_eq!(b.kind, BadgeKind::Default);
        assert_eq!(
            background_color(&b.resolved_badge_style()),
            Some(BadgeKind::Default.colors().0),
            "the red survived the swap"
        );
    }
    #[test]
    fn swap_with_default_is_idempotent_on_an_already_default_badge() {
        let mut b = Badge::default();
        let first = b.swap_with_default();
        let second = b.swap_with_default();
        assert_eq!(first, Badge::default());
        assert_eq!(second, Badge::default());
        assert_eq!(b, Badge::default());
    }
    #[test]
    fn swap_with_default_survives_a_huge_label_and_repeated_swaps() {
        let long = "x".repeat(100_000);
        let mut b = Badge::with_kind(AzString::from(long.clone()), BadgeKind::Success);
        for round in 0..10 {
            let taken = b.swap_with_default();
            if round == 0 {
                assert_eq!(
                    taken.string.len(),
                    long.len(),
                    "the long label was truncated"
                );
                assert_eq!(taken.kind, BadgeKind::Success);
            } else {
                assert_eq!(
                    taken,
                    Badge::default(),
                    "round {round}: the emptied badge is not a default"
                );
            }
            assert_eq!(
                b,
                Badge::default(),
                "round {round}: what was left behind is not a default"
            );
        }
    }
    // ------------------------------------------------------------------
    // Badge::dom  (round-trip: badge -> DOM)
    // ------------------------------------------------------------------
    #[test]
    fn dom_is_a_single_classed_pill_carrying_the_computed_style() {
        for kind in ALL_KINDS {
            let badge = Badge::with_kind(AzString::from_const_str("99+"), kind);
            let expected = properties(&badge.resolved_badge_style());
            let dom = badge.dom();
            assert!(
                has_class(&dom, "__azul-native-badge"),
                "{kind:?}: missing the widget class"
            );
            assert!(
                matches!(dom.root.get_node_type(), NodeType::P),
                "{kind:?}: the pill box must be the <p>, not a rect-less text node"
            );
            assert_eq!(
                dom.children.as_ref().len(),
                1,
                "{kind:?}: a badge is one <p> wrapping one text node"
            );
            assert_eq!(
                inline_properties(&dom),
                expected,
                "{kind:?}: the pill lost its computed style"
            );
            assert!(
                inline_properties(&dom.children.as_ref()[0]).is_empty(),
                "{kind:?}: styling belongs on the <p>, not on the text node"
            );
            assert_eq!(
                text_of(&dom),
                Some("99+"),
                "{kind:?}: the label was mangled"
            );
        }
    }
    #[test]
    fn dom_renders_the_kind_the_badge_was_last_set_to() {
        // `dom()` consumes the *cached* style, so a `set_kind` that forgot to
        // recompute would paint the previous colour here and nowhere else.
        for kind in ALL_KINDS {
            let mut badge = Badge::create(AzString::from_const_str("9"));
            badge.set_kind(BadgeKind::Danger);
            badge.set_kind(kind);
            let expected = properties(&build_badge_style(kind));
            assert_eq!(
                inline_properties(&badge.dom()),
                expected,
                "{kind:?}: the DOM does not show the current kind"
            );
        }
    }
    #[test]
    fn dom_preserves_adversarial_labels_verbatim() {
        for s in adversarial_strings() {
            let dom = Badge::create(AzString::from(s.clone())).dom();
            match dom.children.as_ref() {
                [only] => match only.root.get_node_type() {
                    NodeType::Text(t) => {
                        assert_eq!(
                            t.as_ref().as_str(),
                            s.as_str(),
                            "the label changed on its way into the DOM"
                        );
                        assert_eq!(
                            t.as_ref().len(),
                            s.len(),
                            "byte length changed (NUL truncation?)"
                        );
                    }
                    other => panic!("expected a text node, got {other:?}"),
                },
                other => panic!(
                    "expected exactly one text child, got {} children",
                    other.len()
                ),
            }
            assert!(has_class(&dom, "__azul-native-badge"));
        }
    }
    #[test]
    fn from_badge_for_dom_is_exactly_dom() {
        for kind in ALL_KINDS {
            let badge = Badge::with_kind(AzString::from_const_str("ok"), kind);
            let via_into: Dom = badge.clone().into();
            let via_dom = badge.dom();
            assert_eq!(
                inline_properties(&via_into),
                inline_properties(&via_dom),
                "{kind:?}: `From` diverges from `dom()`"
            );
            assert_eq!(
                via_into.root.get_node_type(),
                via_dom.root.get_node_type(),
                "{kind:?}: `From` built a different node"
            );
        }
    }
}