1
//! Label widget for displaying static text with platform-specific default styling.
2

            
3
use azul_core::dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec};
4
use azul_css::dynamic_selector::{
5
    CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
6
};
7
#[allow(clippy::wildcard_imports)]
8
// widget/render module pulls in the css property/value types it builds with
9
use azul_css::{
10
    props::{
11
        basic::*,
12
        layout::*,
13
        property::{CssProperty, *},
14
        style::*,
15
    },
16
    *,
17
};
18

            
19
/// A static text label widget with platform-appropriate default styling.
20
#[derive(Debug, Clone)]
21
#[repr(C)]
22
pub struct Label {
23
    pub string: AzString,
24
    /// The label's CSS, or `None` for "no opinion" — in which case the
25
    /// platform default applies.
26
    ///
27
    /// `None` and `Some(empty)` are different answers: the first means the
28
    /// widget picks, the second means the caller asked for no properties at all
29
    /// and gets none.
30
    pub label_style: OptionCssPropertyWithConditionsVec,
31
}
32

            
33
const SANS_SERIF_STR: &str = "system:ui";
34
const SANS_SERIF: AzString = AzString::from_const_str(SANS_SERIF_STR);
35
const SANS_SERIF_FAMILIES: &[StyleFontFamily] = &[StyleFontFamily::System(SANS_SERIF)];
36
const SANS_SERIF_FAMILY: StyleFontFamilyVec =
37
    StyleFontFamilyVec::from_const_slice(SANS_SERIF_FAMILIES);
38

            
39
/// Standard label text color (#4C4C4C), matching platform UI defaults.
40
const COLOR_4C4C4C: ColorU = ColorU {
41
    r: 76,
42
    g: 76,
43
    b: 76,
44
    a: 255,
45
};
46

            
47
static LABEL_STYLE_DEFAULT: &[CssPropertyWithConditions] = &[
48
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
49
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
50
        LayoutFlexDirection::Column,
51
    )),
52
    CssPropertyWithConditions::simple(CssProperty::const_justify_content(
53
        LayoutJustifyContent::Center,
54
    )),
55
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
56
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
57
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
58
        inner: COLOR_4C4C4C,
59
    })),
60
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(13))),
61
    CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Center)),
62
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SANS_SERIF_FAMILY)),
63
];
64

            
65
static LABEL_STYLE_MAC: &[CssPropertyWithConditions] = &[
66
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
67
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
68
        LayoutFlexDirection::Column,
69
    )),
70
    CssPropertyWithConditions::simple(CssProperty::const_justify_content(
71
        LayoutJustifyContent::Center,
72
    )),
73
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
74
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
75
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
76
        inner: COLOR_4C4C4C,
77
    })),
78
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(12))),
79
    CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Center)),
80
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SANS_SERIF_FAMILY)),
81
];
82

            
83
/// No default styling on unsupported platforms (e.g. WASM, FreeBSD);
84
/// callers should provide explicit styles via `label_style`.
85
static LABEL_STYLE_OTHER: &[CssPropertyWithConditions] = &[];
86

            
87
impl Label {
88
    /// Creates a new label with the given text and platform-specific default styling.
89
    #[inline]
90
    #[must_use]
91
1693
    pub const fn create(string: AzString) -> Self {
92
1693
        Self {
93
1693
            string,
94
1693
            label_style: OptionCssPropertyWithConditionsVec::None,
95
1693
        }
96
1693
    }
97

            
98
    /// The label CSS this widget renders with.
99
    ///
100
    /// `None` means no opinion, so the platform default applies — the same
101
    /// answer both themes give, asked in one place so they cannot drift. The
102
    /// `cfg` fan-out that used to sit in the constructor lives here instead,
103
    /// which is why a hand-built `Label` no longer has to know which platform
104
    /// it was compiled for to look right.
105
    #[must_use]
106
2879
    pub fn resolved_label_style(&self) -> CssPropertyWithConditionsVec {
107
2879
        self.label_style.clone().into_option().unwrap_or_else(|| {
108
            #[cfg(any(target_os = "windows", target_os = "linux"))]
109
2875
            let default = LABEL_STYLE_DEFAULT;
110
            #[cfg(target_os = "macos")]
111
            let default = LABEL_STYLE_MAC;
112
            #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
113
            let default = LABEL_STYLE_OTHER;
114
2875
            CssPropertyWithConditionsVec::from_const_slice(default)
115
2875
        })
116
2879
    }
117

            
118
    /// Replaces `self` with an empty default label, returning the original.
119
    #[inline]
120
    #[must_use]
121
205
    pub const fn swap_with_default(&mut self) -> Self {
122
205
        let mut s = Self::create(AzString::from_const_str(""));
123
205
        core::mem::swap(&mut s, self);
124
205
        s
125
205
    }
126

            
127
    /// Converts this label into a `<p>` block carrying the
128
    /// `__azul-native-label` class and wrapping a bare text node.
129
    ///
130
    /// The `<p>` is the styled box: a `NodeType::Text` node is always
131
    /// inline-level and owns no rect, so every box-model property here would
132
    /// be inert on a raw text node.
133
    #[inline]
134
    #[must_use]
135
1457
    pub fn dom(self) -> Dom {
136
        static LABEL_CLASS: &[IdOrClass] =
137
            &[Class(AzString::from_const_str("__azul-native-label"))];
138

            
139
        // Resolved before `self.string` is moved out below.
140
1457
        let label_style = self.resolved_label_style();
141

            
142
1457
        crate::widgets::widget_p_with_text(self.string)
143
1457
            .with_ids_and_classes(IdOrClassVec::from_const_slice(LABEL_CLASS))
144
1457
            .with_css_props(label_style)
145
1457
    }
146
}
147

            
148
impl From<Label> for Dom {
149
3
    fn from(l: Label) -> Self {
150
3
        l.dom()
151
3
    }
152
}
153

            
154
#[cfg(test)]
155
mod autotest_generated {
156
    use std::collections::HashSet;
157

            
158
    use azul_core::dom::NodeType;
159
    use azul_css::props::basic::{length::SizeMetric, pixel::PixelValue};
160

            
161
    use super::*;
162

            
163
    // ------------------------------------------------------------------
164
    // Helpers
165
    // ------------------------------------------------------------------
166

            
167
    /// The number of declarations each *populated* platform table carries.
168
    const DECL_COUNT: usize = 9;
169

            
170
    /// The class `dom()` stamps onto the label `<p>`.
171
    const LABEL_CLASS_NAME: &str = "__azul-native-label";
172

            
173
    /// The style table `Label::create` is expected to pick on *this* target.
174
    ///
175
    /// Uses `cfg!` rather than `#[cfg]` so every branch still type-checks on
176
    /// every platform — a table that stopped compiling on macOS would otherwise
177
    /// only be caught by a macOS CI run.
178
    fn expected_table() -> &'static [CssPropertyWithConditions] {
179
        if cfg!(target_os = "macos") {
180
            LABEL_STYLE_MAC
181
        } else if cfg!(any(target_os = "windows", target_os = "linux")) {
182
            LABEL_STYLE_DEFAULT
183
        } else {
184
            LABEL_STYLE_OTHER
185
        }
186
    }
187

            
188
    /// The font size `Label::create` bakes in on this target — `None` on the
189
    /// platforms that are documented to get no default styling at all.
190
    fn expected_font_size() -> Option<f32> {
191
        if cfg!(target_os = "macos") {
192
            Some(12.0)
193
        } else if cfg!(any(target_os = "windows", target_os = "linux")) {
194
            Some(13.0)
195
        } else {
196
            None
197
        }
198
    }
199

            
200
    /// True when this target is one of the platforms that gets a real table.
201
    fn target_is_styled() -> bool {
202
        !expected_table().is_empty()
203
    }
204

            
205
    /// The declared properties of a style vec, in declaration order.
206
    fn properties(v: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
207
        v.as_ref().iter().map(|p| p.property.clone()).collect()
208
    }
209

            
210
    /// The `f32` of a `PixelValue`, asserting it is an absolute `px` length. A
211
    /// font size declared in `em`/`%` would resolve against the *parent* font
212
    /// and make the "platform default" scale with whatever it is dropped into.
213
    fn px(pv: &PixelValue) -> f32 {
214
        assert_eq!(
215
            pv.metric,
216
            SizeMetric::Px,
217
            "label lengths must be absolute px, got {:?}",
218
            pv.metric
219
        );
220
        pv.number.get()
221
    }
222

            
223
    fn font_size_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
224
        v.as_ref().iter().find_map(|p| match &p.property {
225
            CssProperty::FontSize(f) => f.get_property().map(|f| px(&f.inner)),
226
            _ => None,
227
        })
228
    }
229

            
230
    fn text_color(v: &CssPropertyWithConditionsVec) -> Option<ColorU> {
231
        v.as_ref().iter().find_map(|p| match &p.property {
232
            CssProperty::TextColor(c) => c.get_property().map(|c| c.inner),
233
            _ => None,
234
        })
235
    }
236

            
237
    fn flex_grow(v: &CssPropertyWithConditionsVec) -> Option<f32> {
238
        v.as_ref().iter().find_map(|p| match &p.property {
239
            CssProperty::FlexGrow(f) => f.get_property().map(|f| f.inner.get()),
240
            _ => None,
241
        })
242
    }
243

            
244
    fn font_families(v: &CssPropertyWithConditionsVec) -> Option<Vec<StyleFontFamily>> {
245
        v.as_ref().iter().find_map(|p| match &p.property {
246
            CssProperty::FontFamily(f) => f.get_property().map(|f| f.as_ref().to_vec()),
247
            _ => None,
248
        })
249
    }
250

            
251
    /// True if `node` carries the CSS class `name`.
252
    fn has_class(node: &Dom, name: &str) -> bool {
253
        node.root
254
            .get_ids_and_classes()
255
            .as_ref()
256
            .iter()
257
            .any(|c| matches!(c, Class(s) if s.as_str() == name))
258
    }
259

            
260
    /// The properties of a rendered node's *inline* style, in declaration order.
261
    fn inline_properties(node: &Dom) -> Vec<CssProperty> {
262
        node.root
263
            .style
264
            .iter_inline_properties()
265
            .map(|(p, _)| p.clone())
266
            .collect()
267
    }
268

            
269
    /// The text carried by a text node, looking through the `<p>` block
270
    /// wrapper the label convention mandates (`p > text`).
271
    fn text_of(node: &Dom) -> Option<&str> {
272
        match node.root.get_node_type() {
273
            NodeType::Text(s) => Some(s.as_ref().as_str()),
274
            NodeType::P => match node.children.as_ref() {
275
                [only] => match only.root.get_node_type() {
276
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
277
                    _ => None,
278
                },
279
                _ => None,
280
            },
281
            _ => None,
282
        }
283
    }
284

            
285
    /// `Label` derives neither `PartialEq` nor `Default`, so compare field-wise.
286
    fn assert_same_label(a: &Label, b: &Label, ctx: &str) {
287
        assert_eq!(a.string, b.string, "{ctx}: the string differs");
288
        assert_eq!(
289
            a.resolved_label_style(),
290
            b.resolved_label_style(),
291
            "{ctx}: the style differs"
292
        );
293
    }
294

            
295
    /// Inputs a label must survive verbatim. Empty, whitespace-only, embedded
296
    /// NUL, combining marks, ZWJ sequences, bidi overrides, strings that look
297
    /// like this widget's own sentinels, and one very large allocation.
298
    fn adversarial_strings() -> Vec<String> {
299
        let mut v: Vec<String> = [
300
            "",
301
            "Label",
302
            " ",
303
            "\t\n\r",
304
            "e\u{0301}",                                   // e + combining acute
305
            "\u{212B}",                                    // ANGSTROM SIGN (NFC-folds to U+00C5)
306
            "\u{C5}",                                      // the folded form — must stay distinct
307
            "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}", // ZWJ family emoji
308
            "\u{5E9}\u{5DC}\u{5D5}\u{5DD}",                // RTL Hebrew
309
            "\0",                                          // a single NUL
310
            "a\0b",                                        // embedded NUL
311
            "\u{FFFD}\u{202E}\u{200B}",                    // replacement, RTL override, ZWSP
312
            "system:ui",                                   // the font sentinel this file bakes in
313
            "__azul-native-label",                         // this widget's own class name
314
            "}\n#pwned { color: red; }",                   // CSS-injection shaped
315
            "<div>&amp;</div>",                            // markup shaped
316
            "-9223372036854775808",                        // i64::MIN
317
        ]
318
        .iter()
319
        .map(|s| (*s).to_string())
320
        .collect();
321
        v.push("x".repeat(200_000));
322
        v.push("\0".repeat(1_000));
323
        v
324
    }
325

            
326
    // ------------------------------------------------------------------
327
    // Label::create  (constructor)
328
    // ------------------------------------------------------------------
329

            
330
    #[test]
331
    fn create_stores_every_adversarial_string_verbatim() {
332
        // The string travels through `AzString` (an FFI `U8Vec`), so a
333
        // C-string-style NUL truncation or a lossy UTF-8 round-trip would show
334
        // up as a shortened or mangled label here first.
335
        for s in adversarial_strings() {
336
            let label = Label::create(AzString::from(s.clone()));
337
            assert_eq!(
338
                label.string.as_str(),
339
                s.as_str(),
340
                "the string was rewritten"
341
            );
342
            assert_eq!(
343
                label.string.len(),
344
                s.len(),
345
                "byte length changed (NUL truncation?)"
346
            );
347
            assert_eq!(
348
                label.string.chars().count(),
349
                s.chars().count(),
350
                "char count changed (lossy UTF-8 round-trip?)"
351
            );
352
        }
353
    }
354

            
355
    #[test]
356
    fn create_never_normalises_or_folds_the_string() {
357
        // U+212B and U+00C5 render identically but are different code points;
358
        // a normalisation pass hidden in the string plumbing would silently
359
        // merge them and break byte-exact round-trips through FFI.
360
        let angstrom = Label::create(AzString::from("\u{212B}".to_string()));
361
        let a_ring = Label::create(AzString::from("\u{C5}".to_string()));
362
        assert_ne!(
363
            angstrom.string, a_ring.string,
364
            "the two forms were normalised into one"
365
        );
366
        assert_eq!(
367
            angstrom.string.len(),
368
            3,
369
            "U+212B must stay a 3-byte sequence"
370
        );
371
        assert_eq!(a_ring.string.len(), 2, "U+00C5 must stay a 2-byte sequence");
372
    }
373

            
374
    #[test]
375
    fn create_uses_the_platform_table_for_this_target() {
376
        let label = Label::create(AzString::from_const_str("hello"));
377
        assert_eq!(
378
            properties(&label.resolved_label_style()),
379
            expected_table()
380
                .iter()
381
                .map(|p| p.property.clone())
382
                .collect::<Vec<_>>(),
383
            "the constructor picked the wrong platform style table"
384
        );
385
        assert_eq!(
386
            font_size_px(&label.resolved_label_style()),
387
            expected_font_size()
388
        );
389
    }
390

            
391
    #[test]
392
    fn create_is_deterministic_and_independent_of_the_string() {
393
        // The style must not depend on the text: two labels built from wildly
394
        // different strings must carry byte-identical styling.
395
        let a = Label::create(AzString::from_const_str(""));
396
        let b = Label::create(AzString::from("x".repeat(100_000)));
397
        assert_eq!(
398
            a.resolved_label_style(),
399
            b.resolved_label_style(),
400
            "the style varies with the label text"
401
        );
402
        assert_same_label(
403
            &a,
404
            &Label::create(AzString::from_const_str("")),
405
            "repeat construction",
406
        );
407
    }
408

            
409
    #[test]
410
    fn constructed_style_vec_has_consistent_length_and_capacity() {
411
        let v = Label::create(AzString::from_const_str("hi")).resolved_label_style();
412
        assert_eq!(
413
            v.len(),
414
            v.as_ref().len(),
415
            "len() disagrees with the slice view"
416
        );
417
        assert!(
418
            v.capacity() >= v.len(),
419
            "capacity {} < len {}",
420
            v.capacity(),
421
            v.len()
422
        );
423
        if target_is_styled() {
424
            assert_eq!(v.len(), DECL_COUNT, "unexpected number of declarations");
425
        } else {
426
            assert!(
427
                v.is_empty(),
428
                "unsupported platforms are documented to get no styling"
429
            );
430
        }
431
    }
432

            
433
    #[test]
434
    fn cloning_and_dropping_never_corrupts_the_shared_static_style() {
435
        // `label_style` borrows a `'static` slice (`NoDestructor`) while
436
        // `string` may be heap-owned. A clone that wrongly claims ownership of
437
        // the static, or a `Drop` that frees it, would corrupt every future
438
        // label — so churn hard and re-check both the original and a fresh build.
439
        let base = Label::create(AzString::from("churn \u{1F600}".to_string()));
440
        let expected_props = properties(&base.resolved_label_style());
441
        for round in 0..1000 {
442
            let c = base.clone();
443
            assert_eq!(
444
                c.string.as_str(),
445
                "churn \u{1F600}",
446
                "clone {round}: the string diverged"
447
            );
448
            assert_eq!(
449
                properties(&c.resolved_label_style()),
450
                expected_props,
451
                "clone {round}: the style diverged"
452
            );
453
            drop(c);
454
        }
455
        assert_eq!(
456
            base.string.as_str(),
457
            "churn \u{1F600}",
458
            "the original string was damaged"
459
        );
460
        assert_eq!(
461
            properties(&base.resolved_label_style()),
462
            expected_props,
463
            "the original style was damaged"
464
        );
465
        assert_eq!(
466
            properties(&Label::create(AzString::from_const_str("x")).resolved_label_style()),
467
            expected_props,
468
            "a freshly built label disagrees after 1000 clone/drop cycles"
469
        );
470
    }
471

            
472
    #[test]
473
    fn a_const_str_label_survives_clone_churn_of_its_static_backing() {
474
        // `AzString::from_const_str` is `NoDestructor`-backed; `clone_self`
475
        // copies it. A shallow clone plus a `Drop` that freed the `'static`
476
        // would be a use-after-free the very next read.
477
        let base = Label::create(AzString::from_const_str(LABEL_CLASS_NAME));
478
        for round in 0..1000 {
479
            let c = base.clone();
480
            assert_eq!(
481
                c.string.as_str(),
482
                LABEL_CLASS_NAME,
483
                "clone {round}: static backing corrupted"
484
            );
485
            drop(c);
486
        }
487
        assert_eq!(base.string.as_str(), LABEL_CLASS_NAME);
488
    }
489

            
490
    // ------------------------------------------------------------------
491
    // The platform style tables
492
    // ------------------------------------------------------------------
493

            
494
    #[test]
495
    fn the_two_populated_tables_differ_only_in_font_size() {
496
        // They are hand-duplicated blocks: a fix applied to one and not the
497
        // other is the failure mode this file is most exposed to.
498
        assert_eq!(LABEL_STYLE_DEFAULT.len(), DECL_COUNT);
499
        assert_eq!(
500
            LABEL_STYLE_MAC.len(),
501
            DECL_COUNT,
502
            "the two tables have diverged in length"
503
        );
504
        for (i, (d, m)) in LABEL_STYLE_DEFAULT
505
            .iter()
506
            .zip(LABEL_STYLE_MAC.iter())
507
            .enumerate()
508
        {
509
            assert_eq!(
510
                core::mem::discriminant(&d.property),
511
                core::mem::discriminant(&m.property),
512
                "declaration {i} is a different property on the two platforms"
513
            );
514
            if matches!(d.property, CssProperty::FontSize(_)) {
515
                assert_ne!(
516
                    d.property, m.property,
517
                    "the two tables were expected to differ in font size"
518
                );
519
            } else {
520
                assert_eq!(
521
                    d.property, m.property,
522
                    "declaration {i} drifted between the two tables"
523
                );
524
            }
525
        }
526
    }
527

            
528
    #[test]
529
    fn label_style_other_is_empty_as_documented() {
530
        // The doc comment promises "no default styling on unsupported
531
        // platforms"; a stray declaration here would style WASM/FreeBSD
532
        // differently from everything the other two tables were tuned against.
533
        assert!(
534
            LABEL_STYLE_OTHER.is_empty(),
535
            "the fallback table is no longer empty"
536
        );
537
    }
538

            
539
    #[test]
540
    fn every_declaration_is_unconditional() {
541
        // A label is stateless — a declaration gated on `:hover`/`:active`
542
        // would simply never paint.
543
        for (name, table) in [("default", LABEL_STYLE_DEFAULT), ("mac", LABEL_STYLE_MAC)] {
544
            for p in table {
545
                assert!(
546
                    p.apply_if.as_ref().is_empty(),
547
                    "{name}: {:?} is conditional on a stateless widget",
548
                    p.property
549
                );
550
            }
551
        }
552
    }
553

            
554
    #[test]
555
    fn no_property_is_declared_twice() {
556
        // A duplicated declaration is a last-one-wins ambiguity: two font sizes
557
        // would make one of them silently dead.
558
        for (name, table) in [("default", LABEL_STYLE_DEFAULT), ("mac", LABEL_STYLE_MAC)] {
559
            let mut seen = HashSet::new();
560
            for p in table {
561
                assert!(
562
                    seen.insert(core::mem::discriminant(&p.property)),
563
                    "{name}: duplicate declaration of {:?}",
564
                    p.property
565
                );
566
            }
567
            assert_eq!(seen.len(), table.len());
568
        }
569
    }
570

            
571
    #[test]
572
    fn the_text_colour_is_the_documented_opaque_grey() {
573
        // The doc comment pins it to #4C4C4C; a translucent label would let the
574
        // background bleed through the glyphs.
575
        assert_eq!(
576
            COLOR_4C4C4C,
577
            ColorU {
578
                r: 76,
579
                g: 76,
580
                b: 76,
581
                a: 255
582
            }
583
        );
584
        assert_eq!(
585
            COLOR_4C4C4C.a, 255,
586
            "a translucent label lets the background bleed through"
587
        );
588
        assert_eq!(
589
            COLOR_4C4C4C.r, COLOR_4C4C4C.g,
590
            "the label colour is not neutral grey"
591
        );
592
        assert_eq!(
593
            COLOR_4C4C4C.g, COLOR_4C4C4C.b,
594
            "the label colour is not neutral grey"
595
        );
596

            
597
        for (name, table) in [("default", LABEL_STYLE_DEFAULT), ("mac", LABEL_STYLE_MAC)] {
598
            let v = CssPropertyWithConditionsVec::from_const_slice(table);
599
            assert_eq!(
600
                text_color(&v),
601
                Some(COLOR_4C4C4C),
602
                "{name}: wrong text colour"
603
            );
604
        }
605
    }
606

            
607
    #[test]
608
    fn every_font_size_is_a_finite_positive_absolute_px() {
609
        // Guard the `isize` -> `PixelValue` fixed-point conversion: a NaN, an
610
        // infinity, a zero or a negative size must never reach the shaper.
611
        for (name, table, want) in [
612
            ("default", LABEL_STYLE_DEFAULT, 13.0),
613
            ("mac", LABEL_STYLE_MAC, 12.0),
614
        ] {
615
            let v = CssPropertyWithConditionsVec::from_const_slice(table);
616
            let size = font_size_px(&v).expect("a label must declare a font size");
617
            assert!(size.is_finite(), "{name}: non-finite font size {size}");
618
            assert!(!size.is_nan(), "{name}: NaN font size");
619
            assert!(size > 0.0, "{name}: a {size}px label is invisible");
620
            assert!(
621
                size <= 128.0,
622
                "{name}: {size}px is implausible for a UI label"
623
            );
624
            assert_eq!(size, want, "{name}: unexpected font size");
625
        }
626
    }
627

            
628
    #[test]
629
    fn the_fixed_point_length_encoding_round_trips() {
630
        // encode == decode for every numeric constant this file bakes in.
631
        assert_eq!(PixelValue::const_px(13).number.get(), 13.0);
632
        assert_eq!(PixelValue::const_px(12).number.get(), 12.0);
633
        assert_eq!(StyleFontSize::const_px(13).inner.number.get(), 13.0);
634
        assert_eq!(StyleFontSize::const_px(12).inner.number.get(), 12.0);
635
        assert_eq!(LayoutFlexGrow::const_new(1).inner.get(), 1.0);
636

            
637
        // ...and the values that actually landed in the tables are the ones the
638
        // declarations asked for.
639
        let d: Vec<CssProperty> = LABEL_STYLE_DEFAULT
640
            .iter()
641
            .map(|p| p.property.clone())
642
            .collect();
643
        assert!(d.contains(&CssProperty::const_font_size(StyleFontSize::const_px(13))));
644
        let m: Vec<CssProperty> = LABEL_STYLE_MAC.iter().map(|p| p.property.clone()).collect();
645
        assert!(m.contains(&CssProperty::const_font_size(StyleFontSize::const_px(12))));
646
    }
647

            
648
    #[test]
649
    fn flex_grow_is_exactly_one_and_not_a_rounding_artefact() {
650
        // `FloatValue` stores a fixed-point `isize`; a botched encode/decode
651
        // would show up as 0.999 or -0.0 rather than a clean 1.
652
        for (name, table) in [("default", LABEL_STYLE_DEFAULT), ("mac", LABEL_STYLE_MAC)] {
653
            let v = CssPropertyWithConditionsVec::from_const_slice(table);
654
            let g = flex_grow(&v).expect("flex-grow must be declared");
655
            assert!(g.is_finite(), "{name}: non-finite flex-grow {g}");
656
            assert_eq!(g, 1.0, "{name}: flex-grow is {g}, not 1");
657
            assert!(g.is_sign_positive(), "{name}: flex-grow decoded as -0.0");
658
        }
659
    }
660

            
661
    #[test]
662
    fn the_font_family_is_a_single_system_ui_entry() {
663
        // `SANS_SERIF` / `SANS_SERIF_FAMILY` are `const`, so each mention
664
        // materialises a fresh value — bind them once and read them back.
665
        let sentinel: AzString = SANS_SERIF;
666
        let family_vec: StyleFontFamilyVec = SANS_SERIF_FAMILY;
667

            
668
        assert_eq!(SANS_SERIF_STR, "system:ui");
669
        assert_eq!(
670
            sentinel.as_str(),
671
            SANS_SERIF_STR,
672
            "the const AzString lost its backing str"
673
        );
674
        assert_eq!(sentinel.as_str().len(), SANS_SERIF_STR.len());
675
        assert_eq!(
676
            SANS_SERIF_FAMILIES.len(),
677
            1,
678
            "the fallback chain changed length"
679
        );
680
        assert_eq!(
681
            family_vec.as_ref().len(),
682
            1,
683
            "the const vec disagrees with its slice"
684
        );
685

            
686
        for (name, table) in [("default", LABEL_STYLE_DEFAULT), ("mac", LABEL_STYLE_MAC)] {
687
            let v = CssPropertyWithConditionsVec::from_const_slice(table);
688
            let fams = font_families(&v).expect("a label must declare a font family");
689
            assert_eq!(fams.len(), 1, "{name}: unexpected fallback chain length");
690
            match &fams[0] {
691
                // Pinned as-is: this file spells the UI font as a *named*
692
                // family whose name happens to be the `system:ui` sentinel,
693
                // not as `StyleFontFamily::SystemType(SystemFontType::Ui)`.
694
                StyleFontFamily::System(s) => {
695
                    assert_eq!(s.as_str(), "system:ui", "{name}: wrong family name")
696
                }
697
                other => panic!("{name}: unexpected font family variant {other:?}"),
698
            }
699
        }
700
    }
701

            
702
    #[test]
703
    fn the_centering_declarations_are_mutually_consistent() {
704
        // A label centres its text both ways; each half of that contract lives
705
        // in a different declaration, so assert them together.
706
        for (name, table) in [("default", LABEL_STYLE_DEFAULT), ("mac", LABEL_STYLE_MAC)] {
707
            let props: Vec<CssProperty> = table.iter().map(|p| p.property.clone()).collect();
708
            let has = |p: &CssProperty| props.contains(p);
709
            assert!(
710
                has(&CssProperty::const_display(LayoutDisplay::Flex)),
711
                "{name}: not a flex box"
712
            );
713
            assert!(
714
                has(&CssProperty::const_flex_direction(
715
                    LayoutFlexDirection::Column
716
                )),
717
                "{name}: not a column"
718
            );
719
            assert!(
720
                has(&CssProperty::const_justify_content(
721
                    LayoutJustifyContent::Center
722
                )),
723
                "{name}: not centred on the main axis"
724
            );
725
            assert!(
726
                has(&CssProperty::const_align_items(LayoutAlignItems::Center)),
727
                "{name}: not centred on the cross axis"
728
            );
729
            assert!(
730
                has(&CssProperty::const_text_align(StyleTextAlign::Center)),
731
                "{name}: the text itself is not centred"
732
            );
733
        }
734
    }
735

            
736
    // ------------------------------------------------------------------
737
    // Label::swap_with_default
738
    // ------------------------------------------------------------------
739

            
740
    #[test]
741
    fn swap_with_default_returns_the_original_and_leaves_an_empty_label() {
742
        let mut label = Label::create(AzString::from("original \u{1F600}".to_string()));
743
        let expected_style = label.resolved_label_style();
744
        let taken = label.swap_with_default();
745

            
746
        // The returned value is the *original*, intact.
747
        assert_eq!(
748
            taken.string.as_str(),
749
            "original \u{1F600}",
750
            "the wrong value was returned"
751
        );
752
        assert_eq!(
753
            taken.resolved_label_style(),
754
            expected_style,
755
            "the returned label lost its style"
756
        );
757

            
758
        // What is left behind is a freshly created empty label — not a hollowed
759
        // out husk with a dangling string or an empty style vec.
760
        assert_eq!(
761
            label.string.as_str(),
762
            "",
763
            "what was left behind is not empty"
764
        );
765
        assert!(label.string.is_empty());
766
        assert_same_label(
767
            &label,
768
            &Label::create(AzString::from_const_str("")),
769
            "left-behind label",
770
        );
771
    }
772

            
773
    #[test]
774
    fn swap_with_default_is_idempotent_on_an_already_empty_label() {
775
        let mut label = Label::create(AzString::from_const_str(""));
776
        let first = label.swap_with_default();
777
        let second = label.swap_with_default();
778
        assert_eq!(first.string.as_str(), "");
779
        assert_eq!(second.string.as_str(), "");
780
        assert_same_label(
781
            &label,
782
            &Label::create(AzString::from_const_str("")),
783
            "after two swaps",
784
        );
785
    }
786

            
787
    #[test]
788
    fn repeated_swaps_never_corrupt_the_static_backed_style() {
789
        // `mem::swap` moves a vec that borrows a `'static` slice; 200 rounds of
790
        // swap-and-drop would surface a double free or a dangling `ptr`.
791
        let mut label = Label::create(AzString::from("swap me".to_string()));
792
        for round in 0..200 {
793
            let taken = label.swap_with_default();
794
            if round == 0 {
795
                assert_eq!(
796
                    taken.string.as_str(),
797
                    "swap me",
798
                    "round 0: wrong value returned"
799
                );
800
            } else {
801
                assert_eq!(
802
                    taken.string.as_str(),
803
                    "",
804
                    "round {round}: the emptied slot was not empty"
805
                );
806
            }
807
            assert_eq!(
808
                properties(&taken.resolved_label_style()),
809
                properties(&label.resolved_label_style()),
810
                "round {round}"
811
            );
812
            assert_eq!(
813
                label.string.as_str(),
814
                "",
815
                "round {round}: what was left behind is not empty"
816
            );
817
            drop(taken);
818
        }
819
        assert_same_label(
820
            &label,
821
            &Label::create(AzString::from_const_str("")),
822
            "after 200 swaps",
823
        );
824
    }
825

            
826
    #[test]
827
    fn swap_with_default_returns_a_custom_style_untouched() {
828
        // Both fields are `pub`, so a caller can hand-build a label. The swap
829
        // must hand that style back rather than rewriting it on the way out.
830
        let custom =
831
            CssPropertyWithConditionsVec::from_vec(vec![CssPropertyWithConditions::simple(
832
                CssProperty::const_font_size(StyleFontSize::const_px(42)),
833
            )]);
834
        let mut label = Label {
835
            string: AzString::from_const_str("custom"),
836
            label_style: OptionCssPropertyWithConditionsVec::Some(custom),
837
        };
838
        let taken = label.swap_with_default();
839
        assert_eq!(taken.string.as_str(), "custom");
840
        assert_eq!(
841
            taken.resolved_label_style().len(),
842
            1,
843
            "the custom style was rewritten on the way out"
844
        );
845
        assert_eq!(font_size_px(&taken.resolved_label_style()), Some(42.0));
846
        // ...and the slot is refilled with the platform default, not the custom one.
847
        assert_eq!(
848
            font_size_px(&label.resolved_label_style()),
849
            expected_font_size(),
850
            "the 42px override survived"
851
        );
852
    }
853

            
854
    #[test]
855
    fn swap_with_default_hands_back_a_huge_string_without_truncating_it() {
856
        let huge = "\u{1F600}".repeat(50_000);
857
        let mut label = Label::create(AzString::from(huge.clone()));
858
        let taken = label.swap_with_default();
859
        assert_eq!(
860
            taken.string.len(),
861
            huge.len(),
862
            "the huge string was truncated on the way out"
863
        );
864
        assert_eq!(taken.string.as_str(), huge.as_str());
865
        assert!(label.string.is_empty());
866
    }
867

            
868
    // ------------------------------------------------------------------
869
    // Label::dom  (round-trip: label -> DOM)
870
    // ------------------------------------------------------------------
871

            
872
    #[test]
873
    fn dom_is_a_single_classed_text_node_carrying_the_computed_style() {
874
        let label = Label::create(AzString::from_const_str("Hello"));
875
        let expected = properties(&label.resolved_label_style());
876
        let dom = label.dom();
877

            
878
        assert_eq!(
879
            text_of(&dom),
880
            Some("Hello"),
881
            "the label is not a text node, or was mangled"
882
        );
883
        assert!(
884
            has_class(&dom, LABEL_CLASS_NAME),
885
            "missing the widget class"
886
        );
887
        assert_eq!(
888
            dom.root.get_ids_and_classes().as_ref().len(),
889
            1,
890
            "expected exactly one class and no ids"
891
        );
892
        assert_eq!(
893
            dom.children.as_ref().len(),
894
            1,
895
            "a label is a <p> wrapping exactly one bare text node"
896
        );
897
        assert!(
898
            dom.children.as_ref()[0].children.as_ref().is_empty(),
899
            "the text node itself is a leaf, not a subtree"
900
        );
901
        assert_eq!(
902
            dom.estimated_total_children, 1,
903
            "the <p> owns exactly its text node"
904
        );
905
        // The ONLY sheet a <p> widget carries is the UA-margin reset
906
        // (`widgets::widget_p_margin_reset`), scoped to the node itself.
907
        assert_eq!(
908
            dom.css.as_ref().len(),
909
            1,
910
            "a label attaches exactly the <p> margin reset, nothing else"
911
        );
912
        assert!(
913
            dom.root.callbacks.as_ref().is_empty(),
914
            "a static widget must not bind callbacks"
915
        );
916
        assert_eq!(
917
            inline_properties(&dom),
918
            expected,
919
            "the label lost its computed style"
920
        );
921
    }
922

            
923
    #[test]
924
    fn dom_preserves_adversarial_labels_verbatim() {
925
        for s in adversarial_strings() {
926
            let dom = Label::create(AzString::from(s.clone())).dom();
927
            let t = text_of(&dom).expect("expected a text node");
928
            assert_eq!(t, s.as_str(), "the label changed on its way into the DOM");
929
            assert_eq!(t.len(), s.len(), "byte length changed (NUL truncation?)");
930
            assert!(
931
                has_class(&dom, LABEL_CLASS_NAME),
932
                "the class was lost for {s:?}"
933
            );
934
            // The text must never leak into the style, and the style must never
935
            // vary with the text.
936
            assert_eq!(
937
                inline_properties(&dom).len(),
938
                expected_table().len(),
939
                "style varies with the text"
940
            );
941
        }
942
    }
943

            
944
    #[test]
945
    fn dom_of_an_empty_label_is_still_a_classed_text_node() {
946
        // The empty label is what `swap_with_default` leaves behind, so it is
947
        // the one input guaranteed to be rendered somewhere.
948
        let dom = Label::create(AzString::from_const_str("")).dom();
949
        assert_eq!(
950
            text_of(&dom),
951
            Some(""),
952
            "the empty label is not a text node"
953
        );
954
        assert!(has_class(&dom, LABEL_CLASS_NAME));
955
        assert_eq!(inline_properties(&dom).len(), expected_table().len());
956
    }
957

            
958
    #[test]
959
    fn dom_renders_the_style_field_verbatim_even_when_hand_built() {
960
        // `dom()` consumes `label_style` as-is. A hand-built label must be
961
        // rendered with exactly the style it was given — no re-derivation.
962
        let custom = CssPropertyWithConditionsVec::from_vec(vec![
963
            CssPropertyWithConditions::simple(CssProperty::const_font_size(
964
                StyleFontSize::const_px(99),
965
            )),
966
            CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Left)),
967
        ]);
968
        let dom = Label {
969
            string: AzString::from_const_str("hand built"),
970
            label_style: OptionCssPropertyWithConditionsVec::Some(custom.clone()),
971
        }
972
        .dom();
973
        assert_eq!(
974
            inline_properties(&dom),
975
            properties(&custom),
976
            "the custom style was rewritten"
977
        );
978
        assert!(
979
            has_class(&dom, LABEL_CLASS_NAME),
980
            "a hand-built label lost the widget class"
981
        );
982
        assert_eq!(text_of(&dom), Some("hand built"));
983
    }
984

            
985
    #[test]
986
    fn dom_of_a_style_less_label_carries_no_inline_declarations() {
987
        // The `LABEL_STYLE_OTHER` shape: an empty style vec must produce an
988
        // empty inline style, not a phantom rule block.
989
        let dom = Label {
990
            string: AzString::from_const_str("bare"),
991
            label_style: OptionCssPropertyWithConditionsVec::Some(
992
                CssPropertyWithConditionsVec::from_const_slice(LABEL_STYLE_OTHER),
993
            ),
994
        }
995
        .dom();
996
        assert!(
997
            inline_properties(&dom).is_empty(),
998
            "an empty style vec produced declarations"
999
        );
        assert!(has_class(&dom, LABEL_CLASS_NAME));
        assert_eq!(text_of(&dom), Some("bare"));
    }
    #[test]
    fn the_widget_class_is_a_namespaced_ascii_css_identifier() {
        let dom = Label::create(AzString::from_const_str("x")).dom();
        let classes = dom.root.get_ids_and_classes();
        let name = classes
            .as_ref()
            .iter()
            .find_map(|c| match c {
                Class(s) => Some(s.as_str().to_string()),
                IdOrClass::Id(_) => None,
            })
            .expect("the label must carry a class");
        assert_eq!(name, LABEL_CLASS_NAME);
        assert!(!name.is_empty(), "empty class name");
        assert!(name.is_ascii(), "non-ASCII class name {name:?}");
        assert!(
            name.starts_with("__azul-native-"),
            "unnamespaced class {name:?}"
        );
        // A space, a dot or a `#` would silently split/re-target the selector.
        assert!(
            name.chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'),
            "class name {name:?} contains a CSS-significant character"
        );
    }
    #[test]
    fn a_label_whose_text_is_the_class_name_does_not_gain_a_second_class() {
        // `dom()` sets ids-and-classes *after* the text node is built; a
        // confusion between the two would show up as an extra attribute here.
        let dom = Label::create(AzString::from_const_str(LABEL_CLASS_NAME)).dom();
        assert_eq!(
            dom.root.get_ids_and_classes().as_ref().len(),
            1,
            "the text leaked into the class list"
        );
        assert_eq!(text_of(&dom), Some(LABEL_CLASS_NAME));
    }
    #[test]
    fn from_label_for_dom_is_exactly_dom() {
        for s in ["", "ok", "\u{1F600}\0"] {
            let label = Label::create(AzString::from(s.to_string()));
            let via_into: Dom = label.clone().into();
            let via_dom = label.dom();
            assert_eq!(via_into, via_dom, "{s:?}: `From` diverges from `dom()`");
        }
    }
    #[test]
    fn building_many_doms_never_corrupts_the_shared_static_class_list() {
        // `dom()` hands a `'static`-backed `IdOrClassVec` to each node it
        // builds; 1000 build-and-drop rounds would surface a double free.
        for round in 0..1000 {
            let dom = Label::create(AzString::from_const_str("churn")).dom();
            assert!(
                has_class(&dom, LABEL_CLASS_NAME),
                "round {round}: the static class list was corrupted"
            );
            drop(dom);
        }
        let dom = Label::create(AzString::from_const_str("churn")).dom();
        assert!(
            has_class(&dom, LABEL_CLASS_NAME),
            "the static class list did not survive the churn"
        );
        assert_eq!(inline_properties(&dom).len(), expected_table().len());
    }
}