1
//! Avatar widget — a circular container showing either an image or short
2
//! initials text, in one of three size variants. A stateless widget (no
3
//! callbacks), a styled near-clone of [`crate::widgets::label::Label`] /
4
//! [`crate::widgets::button::Button`] (image-or-text content) rendered as a
5
//! `border-radius: 50%` circle.
6
//!
7
//! If an [`ImageRef`] is set it is rendered (clipped to the circle); otherwise
8
//! the `initials` string is shown centred on a neutral background.
9
//!
10
//! TODO2: the circular image relies on `overflow: hidden` + `border-radius` on
11
//! the container clipping the child image; whether the renderer clips a child
12
//! image to the parent's rounded corners is not GUI-verified here, so the image
13
//! is *also* given its own matching `border-radius` as a fallback.
14
//!
15
//! Key types: [`Avatar`], [`AvatarSize`].
16

            
17
use azul_core::{
18
    dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec},
19
    resources::{ImageRef, OptionImageRef},
20
};
21
use azul_css::{
22
    dynamic_selector::{
23
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
24
    },
25
    props::{
26
        basic::{color::ColorU, StyleFontSize},
27
        layout::{
28
            LayoutAlignItems, LayoutAlignSelf, LayoutDisplay, LayoutFlexDirection, LayoutFlexGrow,
29
            LayoutHeight, LayoutJustifyContent, LayoutOverflow, LayoutWidth,
30
        },
31
        property::{CssProperty, *},
32
        style::{
33
            StyleBackgroundContent, StyleBackgroundContentVec, StyleBorderBottomLeftRadius,
34
            StyleBorderBottomRightRadius, StyleBorderTopLeftRadius, StyleBorderTopRightRadius,
35
            StyleTextAlign, StyleTextColor,
36
        },
37
    },
38
    AzString,
39
};
40

            
41
use crate::widgets::themes::{OptionUiTheme, UiTheme};
42

            
43
pub static AVATAR_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str("__azul-native-avatar"))];
44
pub static AVATAR_IMAGE_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
45
    "__azul-native-avatar-image",
46
))];
47
pub static AVATAR_INITIALS_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
48
    "__azul-native-avatar-initials",
49
))];
50

            
51
/// Neutral background (#6c757d, grey) shown behind the initials.
52
const AVATAR_BG_COLOR: ColorU = ColorU {
53
    r: 108,
54
    g: 117,
55
    b: 125,
56
    a: 255,
57
};
58
/// Initials text colour (white).
59
const AVATAR_TEXT_COLOR: ColorU = ColorU {
60
    r: 255,
61
    g: 255,
62
    b: 255,
63
    a: 255,
64
};
65

            
66
const AVATAR_BG_ITEMS: &[StyleBackgroundContent] =
67
    &[StyleBackgroundContent::Color(AVATAR_BG_COLOR)];
68
const AVATAR_BG: StyleBackgroundContentVec =
69
    StyleBackgroundContentVec::from_const_slice(AVATAR_BG_ITEMS);
70

            
71
/// Diameter (and font) size variant of an [`Avatar`].
72
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
73
#[repr(C)]
74
pub enum AvatarSize {
75
    /// 24px diameter.
76
    Small,
77
    /// 40px diameter — the default.
78
    #[default]
79
    Medium,
80
    /// 64px diameter.
81
    Large,
82
}
83

            
84
impl AvatarSize {
85
    /// Diameter of the circle in logical pixels.
86
    #[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
87
                                                 // pixel/coord path or to avoid churning call sites
88
                                                 // for a perf-neutral change)
89
584
    const fn diameter(&self) -> isize {
90
584
        match self {
91
171
            Self::Small => 24,
92
230
            Self::Medium => 40,
93
183
            Self::Large => 64,
94
        }
95
584
    }
96

            
97
    /// Corner radius for a full circle = diameter / 2.
98
    #[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
99
                                                 // pixel/coord path or to avoid churning call sites
100
                                                 // for a perf-neutral change)
101
284
    const fn radius(&self) -> isize {
102
284
        self.diameter() / 2
103
284
    }
104

            
105
    /// Initials font size in logical pixels.
106
    #[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
107
                                                 // pixel/coord path or to avoid churning call sites
108
                                                 // for a perf-neutral change)
109
260
    const fn font_size(&self) -> isize {
110
260
        match self {
111
76
            Self::Small => 11,
112
105
            Self::Medium => 16,
113
79
            Self::Large => 24,
114
        }
115
260
    }
116
}
117

            
118
/// A circular avatar showing an image or initials. Stateless.
119
#[derive(Debug, Clone, PartialEq, Eq)]
120
#[repr(C)]
121
pub struct Avatar {
122
    /// Optional image; when present it is shown instead of the initials.
123
    pub image: OptionImageRef,
124
    /// Fallback initials shown when no image is set.
125
    pub initials: AzString,
126
    /// The size variant.
127
    pub size: AvatarSize,
128
    /// The computed inline style for the circular container.
129
    pub theme: OptionUiTheme,
130
    pub avatar_style: OptionCssPropertyWithConditionsVec,
131
}
132

            
133
/// Builds the circular container style for a given size. Diameter, corner radius
134
/// and font size are size-dependent, so the style is built at runtime per the
135
/// recipe's "runtime vec when param-dependent" path (see `badge::build_badge_style`).
136
#[must_use]
137
239
pub fn build_avatar_style(size: AvatarSize) -> CssPropertyWithConditionsVec {
138
239
    let d = size.diameter();
139
239
    let r = size.radius();
140
239
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
141
239
        CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
142
239
        CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
143
239
            LayoutFlexDirection::Row,
144
        )),
145
239
        CssPropertyWithConditions::simple(CssProperty::const_justify_content(
146
239
            LayoutJustifyContent::Center,
147
        )),
148
239
        CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
149
        // Hug content rather than stretch across a flex parent's cross axis.
150
239
        CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Start)),
151
239
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
152
            0,
153
        ))),
154
239
        CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(d))),
155
239
        CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(d))),
156
        // circle
157
239
        CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
158
239
            StyleBorderTopLeftRadius::const_px(r),
159
        )),
160
239
        CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
161
239
            StyleBorderTopRightRadius::const_px(r),
162
        )),
163
239
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
164
239
            StyleBorderBottomLeftRadius::const_px(r),
165
        )),
166
239
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
167
239
            StyleBorderBottomRightRadius::const_px(r),
168
        )),
169
        // clip the image (or overflowing initials) to the circle
170
239
        CssPropertyWithConditions::simple(CssProperty::const_overflow_x(LayoutOverflow::Hidden)),
171
239
        CssPropertyWithConditions::simple(CssProperty::const_overflow_y(LayoutOverflow::Hidden)),
172
239
        CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(
173
239
            size.font_size(),
174
        ))),
175
239
        CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Center)),
176
239
        CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
177
239
            inner: AVATAR_TEXT_COLOR,
178
239
        })),
179
239
        CssPropertyWithConditions::simple(CssProperty::const_background_content(AVATAR_BG)),
180
    ])
181
239
}
182

            
183
/// Builds the inner image style: fills the circle and is itself rounded so the
184
/// image reads as a circle even if `overflow: hidden` clipping is unavailable.
185
#[must_use]
186
27
pub fn build_image_style(size: AvatarSize) -> CssPropertyWithConditionsVec {
187
27
    let d = size.diameter();
188
27
    let r = size.radius();
189
27
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
190
27
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
191
            0,
192
        ))),
193
27
        CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(d))),
194
27
        CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(d))),
195
27
        CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
196
27
            StyleBorderTopLeftRadius::const_px(r),
197
        )),
198
27
        CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
199
27
            StyleBorderTopRightRadius::const_px(r),
200
        )),
201
27
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
202
27
            StyleBorderBottomLeftRadius::const_px(r),
203
        )),
204
27
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
205
27
            StyleBorderBottomRightRadius::const_px(r),
206
        )),
207
    ])
208
27
}
209

            
210
impl Avatar {
211
    /// The avatar CSS this widget renders with.
212
    ///
213
    /// `None` means no opinion, so the size's default applies — the same
214
    /// answer both themes give, asked in one place so they cannot drift.
215
    #[must_use]
216
119
    pub fn resolved_avatar_style(&self) -> CssPropertyWithConditionsVec {
217
119
        self.avatar_style
218
119
            .clone()
219
119
            .into_option()
220
119
            .unwrap_or_else(|| build_avatar_style(self.size))
221
119
    }
222

            
223
    /// Creates a medium initials avatar with the given text.
224
    #[inline]
225
    #[must_use]
226
43
    pub fn create(initials: AzString) -> Self {
227
43
        Self {
228
43
            image: None.into(),
229
43
            initials,
230
43
            size: AvatarSize::Medium,
231
43
            theme: OptionUiTheme::None,
232
43
            avatar_style: OptionCssPropertyWithConditionsVec::None,
233
43
        }
234
43
    }
235

            
236
    /// Creates a medium image avatar (with empty fallback initials).
237
    #[inline]
238
    #[must_use]
239
8
    pub fn create_with_image(image: ImageRef) -> Self {
240
8
        Self {
241
8
            image: Some(image).into(),
242
8
            initials: AzString::from_const_str(""),
243
8
            size: AvatarSize::Medium,
244
8
            theme: OptionUiTheme::None,
245
8
            avatar_style: OptionCssPropertyWithConditionsVec::None,
246
8
        }
247
8
    }
248

            
249
    /// Sets the avatar image (shown instead of the initials).
250
    #[inline]
251
7
    pub fn set_image(&mut self, image: ImageRef) {
252
7
        self.image = Some(image).into();
253
7
    }
254

            
255
    /// Builder-style setter for the avatar image.
256
    #[inline]
257
    #[must_use]
258
5
    pub fn with_image(mut self, image: ImageRef) -> Self {
259
5
        self.set_image(image);
260
5
        self
261
5
    }
262

            
263
    /// Sets the theme this avatar renders with.
264
    #[inline]
265
    pub const fn set_theme(&mut self, theme: UiTheme) {
266
        self.theme = OptionUiTheme::Some(theme);
267
    }
268

            
269
    #[must_use]
270
    pub const fn with_theme(mut self, theme: UiTheme) -> Self {
271
        self.set_theme(theme);
272
        self
273
    }
274

            
275
    #[inline]
276
71
    pub const fn set_size(&mut self, size: AvatarSize) {
277
71
        self.size = size;
278
71
    }
279

            
280
    /// Builder-style setter for the size variant.
281
    #[inline]
282
    #[must_use]
283
16
    pub const fn with_size(mut self, size: AvatarSize) -> Self {
284
16
        self.set_size(size);
285
16
        self
286
16
    }
287

            
288
    /// Replaces `self` with a default (empty medium) avatar and returns the original.
289
    #[inline]
290
    #[must_use]
291
3
    pub fn swap_with_default(&mut self) -> Self {
292
3
        let mut s = Self::create(AzString::from_const_str(""));
293
3
        core::mem::swap(&mut s, self);
294
3
        s
295
3
    }
296

            
297
    /// Converts this avatar into a DOM subtree with the `__azul-native-avatar` class.
298
    #[inline]
299
    #[must_use]
300
23
    pub fn dom(self) -> Dom {
301
23
        let theme = match self.theme {
302
            OptionUiTheme::Some(theme) => theme,
303
23
            OptionUiTheme::None => UiTheme::Flat,
304
        };
305
23
        match theme {
306
23
            UiTheme::Flat => crate::widgets::themes::flat::avatar(self),
307
            UiTheme::Flora => crate::widgets::themes::flora::avatar(self),
308
        }
309
23
    }
310
}
311

            
312
impl Default for Avatar {
313
6
    fn default() -> Self {
314
6
        Self::create(AzString::from_const_str(""))
315
6
    }
316
}
317

            
318
impl From<Avatar> for Dom {
319
1
    fn from(a: Avatar) -> Self {
320
1
        a.dom()
321
1
    }
322
}
323

            
324
#[cfg(test)]
325
mod autotest_generated {
326
    use std::collections::HashSet;
327

            
328
    use azul_core::{dom::NodeType, resources::RawImageFormat};
329
    use azul_css::props::basic::{length::SizeMetric, pixel::PixelValue};
330

            
331
    use super::*;
332
    use crate::widgets::themes::{OptionUiTheme, UiTheme};
333

            
334
    // ------------------------------------------------------------------
335
    // Helpers
336
    // ------------------------------------------------------------------
337

            
338
    /// Every variant of `AvatarSize` — the full input domain of the getters and
339
    /// of `build_avatar_style` / `build_image_style`.
340
    const ALL_SIZES: [AvatarSize; 3] = [AvatarSize::Small, AvatarSize::Medium, AvatarSize::Large];
341

            
342
    /// A 2x2 placeholder image: `null_image` needs neither a decoder nor a GPU.
343
    fn test_image() -> ImageRef {
344
        ImageRef::null_image(2, 2, RawImageFormat::RGBA8, Vec::new())
345
    }
346

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

            
352
    /// The `f32` of a `PixelValue`, asserting it is an absolute `px` length —
353
    /// an `em`/`%` slipping in here would make the "circle" resolve against the
354
    /// parent instead of the intended diameter.
355
    fn px(pv: &PixelValue) -> f32 {
356
        assert_eq!(
357
            pv.metric,
358
            SizeMetric::Px,
359
            "avatar geometry must be absolute px, got {:?}",
360
            pv.metric
361
        );
362
        pv.number.get()
363
    }
364

            
365
    fn width_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
366
        v.as_ref().iter().find_map(|p| match &p.property {
367
            CssProperty::Width(w) => match w.get_property()? {
368
                LayoutWidth::Px(pv) => Some(px(pv)),
369
                _ => None,
370
            },
371
            _ => None,
372
        })
373
    }
374

            
375
    fn height_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
376
        v.as_ref().iter().find_map(|p| match &p.property {
377
            CssProperty::Height(h) => match h.get_property()? {
378
                LayoutHeight::Px(pv) => Some(px(pv)),
379
                _ => None,
380
            },
381
            _ => None,
382
        })
383
    }
384

            
385
    fn font_size_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
386
        v.as_ref().iter().find_map(|p| match &p.property {
387
            CssProperty::FontSize(f) => f.get_property().map(|f| px(&f.inner)),
388
            _ => None,
389
        })
390
    }
391

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

            
407
    /// Every `PixelValue` a style vec mentions (sizes, radii, font size).
408
    fn all_pixel_values(v: &CssPropertyWithConditionsVec) -> Vec<PixelValue> {
409
        v.as_ref()
410
            .iter()
411
            .filter_map(|p| match &p.property {
412
                CssProperty::Width(w) => match w.get_property()? {
413
                    LayoutWidth::Px(pv) => Some(*pv),
414
                    _ => None,
415
                },
416
                CssProperty::Height(h) => match h.get_property()? {
417
                    LayoutHeight::Px(pv) => Some(*pv),
418
                    _ => None,
419
                },
420
                CssProperty::BorderTopLeftRadius(r) => r.get_property().map(|r| r.inner),
421
                CssProperty::BorderTopRightRadius(r) => r.get_property().map(|r| r.inner),
422
                CssProperty::BorderBottomLeftRadius(r) => r.get_property().map(|r| r.inner),
423
                CssProperty::BorderBottomRightRadius(r) => r.get_property().map(|r| r.inner),
424
                CssProperty::FontSize(f) => f.get_property().map(|f| f.inner),
425
                _ => None,
426
            })
427
            .collect()
428
    }
429

            
430
    /// True if `node` carries the CSS class `name`.
431
    fn has_class(node: &Dom, name: &str) -> bool {
432
        node.root
433
            .get_ids_and_classes()
434
            .as_ref()
435
            .iter()
436
            .any(|c| matches!(c, Class(s) if s.as_str() == name))
437
    }
438

            
439
    /// The properties of a rendered node's *inline* style, in declaration order.
440
    fn inline_properties(node: &Dom) -> Vec<CssProperty> {
441
        node.root
442
            .style
443
            .iter_inline_properties()
444
            .map(|(p, _)| p.clone())
445
            .collect()
446
    }
447

            
448
    /// The single child of a rendered avatar DOM (the widget is always
449
    /// `container -> [image | p > text]`).
450
    fn only_child(dom: &Dom) -> &Dom {
451
        let children = dom.children.as_ref();
452
        assert_eq!(children.len(), 1, "an avatar renders exactly one child");
453
        &children[0]
454
    }
455

            
456
    /// The text carried by a text node, looking through the `<p>` block
457
    /// wrapper the label convention mandates (`p > text`).
458
    fn text_of(node: &Dom) -> Option<&str> {
459
        match node.root.get_node_type() {
460
            NodeType::Text(s) => Some(s.as_ref().as_str()),
461
            NodeType::P => match node.children.as_ref() {
462
                [only] => match only.root.get_node_type() {
463
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
464
                    _ => None,
465
                },
466
                _ => None,
467
            },
468
            _ => None,
469
        }
470
    }
471

            
472
    // ------------------------------------------------------------------
473
    // AvatarSize::diameter / radius / font_size  (getters)
474
    // ------------------------------------------------------------------
475

            
476
    #[test]
477
    fn avatar_size_getters_return_documented_values() {
478
        assert_eq!(AvatarSize::Small.diameter(), 24);
479
        assert_eq!(AvatarSize::Medium.diameter(), 40);
480
        assert_eq!(AvatarSize::Large.diameter(), 64);
481

            
482
        assert_eq!(AvatarSize::Small.radius(), 12);
483
        assert_eq!(AvatarSize::Medium.radius(), 20);
484
        assert_eq!(AvatarSize::Large.radius(), 32);
485

            
486
        assert_eq!(AvatarSize::Small.font_size(), 11);
487
        assert_eq!(AvatarSize::Medium.font_size(), 16);
488
        assert_eq!(AvatarSize::Large.font_size(), 24);
489
    }
490

            
491
    #[test]
492
    fn avatar_size_radius_is_exactly_half_the_diameter() {
493
        // `radius()` is an integer division: an odd diameter would truncate and
494
        // the "circle" would render as a rounded square. Every variant must be even.
495
        for size in ALL_SIZES {
496
            let d = size.diameter();
497
            assert_eq!(
498
                d % 2,
499
                0,
500
                "{size:?}: diameter {d} is odd, so radius() truncates and the avatar is not a \
501
                 circle"
502
            );
503
            assert_eq!(size.radius() * 2, d, "{size:?}: radius must be exactly d/2");
504
        }
505
    }
506

            
507
    #[test]
508
    fn avatar_size_getters_are_positive_and_font_fits_the_circle() {
509
        for size in ALL_SIZES {
510
            assert!(size.diameter() > 0, "{size:?}: non-positive diameter");
511
            assert!(size.radius() > 0, "{size:?}: non-positive radius");
512
            assert!(size.font_size() > 0, "{size:?}: non-positive font size");
513
            assert!(
514
                size.font_size() < size.diameter(),
515
                "{size:?}: font size {} does not fit in a {}px circle",
516
                size.font_size(),
517
                size.diameter()
518
            );
519
        }
520
    }
521

            
522
    #[test]
523
    fn avatar_size_getters_are_monotonic_in_the_size_variant() {
524
        // Small < Medium < Large must hold for both the box and the text, or a
525
        // "larger" avatar could render smaller than a "smaller" one.
526
        let d: Vec<isize> = ALL_SIZES.iter().map(AvatarSize::diameter).collect();
527
        let f: Vec<isize> = ALL_SIZES.iter().map(AvatarSize::font_size).collect();
528
        assert!(
529
            d[0] < d[1] && d[1] < d[2],
530
            "diameters not increasing: {d:?}"
531
        );
532
        assert!(
533
            f[0] < f[1] && f[1] < f[2],
534
            "font sizes not increasing: {f:?}"
535
        );
536
    }
537

            
538
    #[test]
539
    fn avatar_size_getters_are_pure_and_default_is_medium() {
540
        assert_eq!(AvatarSize::default(), AvatarSize::Medium);
541
        assert_eq!(AvatarSize::default().diameter(), 40);
542

            
543
        // The getters take `&self` on a `Copy` enum: repeated calls (and calls
544
        // through a copy) must be side-effect free and identical.
545
        for size in ALL_SIZES {
546
            let copy = size;
547
            assert_eq!(size.diameter(), copy.diameter());
548
            assert_eq!(size.diameter(), size.diameter());
549
            assert_eq!(size.radius(), size.radius());
550
            assert_eq!(size.font_size(), size.font_size());
551
        }
552
    }
553

            
554
    // ------------------------------------------------------------------
555
    // build_avatar_style / build_image_style  (numeric)
556
    // ------------------------------------------------------------------
557

            
558
    #[test]
559
    fn build_avatar_style_box_matches_the_size_variant() {
560
        for size in ALL_SIZES {
561
            let style = build_avatar_style(size);
562
            #[allow(clippy::cast_precision_loss)]
563
            let d = size.diameter() as f32;
564
            #[allow(clippy::cast_precision_loss)]
565
            let r = size.radius() as f32;
566
            #[allow(clippy::cast_precision_loss)]
567
            let f = size.font_size() as f32;
568

            
569
            assert_eq!(width_px(&style), Some(d), "{size:?}: width != diameter");
570
            assert_eq!(height_px(&style), Some(d), "{size:?}: height != diameter");
571
            assert_eq!(font_size_px(&style), Some(f), "{size:?}: wrong font size");
572
            assert_eq!(
573
                radii_px(&style),
574
                vec![r, r, r, r],
575
                "{size:?}: all four corners must carry the same radius"
576
            );
577
        }
578
    }
579

            
580
    #[test]
581
    fn build_avatar_style_radius_is_half_the_box_so_it_renders_as_a_circle() {
582
        // The widget's whole premise: r == d/2 in the *emitted* style, not just
583
        // in the getters.
584
        for size in ALL_SIZES {
585
            let style = build_avatar_style(size);
586
            let d = width_px(&style).expect("width must be declared");
587
            for r in radii_px(&style) {
588
                assert!(
589
                    (r * 2.0 - d).abs() < f32::EPSILON,
590
                    "{size:?}: radius {r} is not half of the {d}px box"
591
                );
592
            }
593
        }
594
    }
595

            
596
    #[test]
597
    fn build_avatar_style_clips_and_centres_its_content() {
598
        for size in ALL_SIZES {
599
            let props = properties(&build_avatar_style(size));
600
            let has = |p: &CssProperty| props.contains(p);
601

            
602
            assert!(has(&CssProperty::const_display(LayoutDisplay::Flex)));
603
            assert!(has(&CssProperty::const_flex_direction(
604
                LayoutFlexDirection::Row
605
            )));
606
            assert!(has(&CssProperty::const_justify_content(
607
                LayoutJustifyContent::Center
608
            )));
609
            assert!(has(&CssProperty::const_align_items(
610
                LayoutAlignItems::Center
611
            )));
612
            assert!(has(&CssProperty::align_self(LayoutAlignSelf::Start)));
613
            assert!(has(&CssProperty::const_text_align(StyleTextAlign::Center)));
614
            // Both axes must clip, or an image/long initials escape the circle.
615
            assert!(has(&CssProperty::const_overflow_x(LayoutOverflow::Hidden)));
616
            assert!(has(&CssProperty::const_overflow_y(LayoutOverflow::Hidden)));
617
            // flex-grow: 0 — the avatar hugs its fixed diameter in a flex parent.
618
            assert!(has(&CssProperty::const_flex_grow(
619
                LayoutFlexGrow::const_new(0)
620
            )));
621
        }
622
    }
623

            
624
    #[test]
625
    fn build_avatar_style_colors_are_the_documented_constants() {
626
        let props = properties(&build_avatar_style(AvatarSize::Medium));
627

            
628
        let text = props.iter().find_map(|p| match p {
629
            CssProperty::TextColor(c) => c.get_property().map(|c| c.inner),
630
            _ => None,
631
        });
632
        assert_eq!(
633
            text,
634
            Some(ColorU {
635
                r: 255,
636
                g: 255,
637
                b: 255,
638
                a: 255
639
            })
640
        );
641

            
642
        let bg = props.iter().find_map(|p| match p {
643
            CssProperty::BackgroundContent(b) => b.get_property(),
644
            _ => None,
645
        });
646
        let bg = bg.expect("a background must be declared behind the initials");
647
        assert_eq!(bg.as_ref().len(), 1, "exactly one background layer");
648
        assert_eq!(
649
            bg.as_ref()[0],
650
            StyleBackgroundContent::Color(ColorU {
651
                r: 108,
652
                g: 117,
653
                b: 125,
654
                a: 255
655
            })
656
        );
657
        // Both colours must be fully opaque, or the initials wash out.
658
        assert_eq!(text.expect("text colour").a, 255);
659
    }
660

            
661
    #[test]
662
    fn build_avatar_style_declares_every_property_at_most_once() {
663
        // A duplicated declaration is a last-one-wins ambiguity: two `width`s
664
        // would silently make one of them dead.
665
        for size in ALL_SIZES {
666
            let props = properties(&build_avatar_style(size));
667
            let mut seen = HashSet::new();
668
            for p in &props {
669
                assert!(
670
                    seen.insert(core::mem::discriminant(p)),
671
                    "{size:?}: duplicate declaration of {p:?}"
672
                );
673
            }
674
            assert_eq!(seen.len(), props.len());
675
        }
676
    }
677

            
678
    #[test]
679
    fn build_avatar_style_properties_are_all_unconditional() {
680
        // Every declaration must apply with no `:hover`/state condition — a
681
        // conditional one would simply never paint on a stateless widget.
682
        for size in ALL_SIZES {
683
            for p in build_avatar_style(size).as_ref() {
684
                assert!(
685
                    p.apply_if.as_ref().is_empty(),
686
                    "{size:?}: {:?} is conditional on a stateless widget",
687
                    p.property
688
                );
689
            }
690
        }
691
    }
692

            
693
    #[test]
694
    fn build_avatar_style_is_deterministic_and_size_dependent() {
695
        for size in ALL_SIZES {
696
            assert_eq!(
697
                properties(&build_avatar_style(size)),
698
                properties(&build_avatar_style(size)),
699
                "{size:?}: two builds of the same size disagree"
700
            );
701
        }
702
        // Different variants must not collapse onto the same style.
703
        assert_ne!(
704
            properties(&build_avatar_style(AvatarSize::Small)),
705
            properties(&build_avatar_style(AvatarSize::Large))
706
        );
707
        assert_ne!(
708
            properties(&build_avatar_style(AvatarSize::Small)),
709
            properties(&build_avatar_style(AvatarSize::Medium))
710
        );
711
    }
712

            
713
    #[test]
714
    fn build_image_style_fills_the_circle_exactly() {
715
        for size in ALL_SIZES {
716
            let container = build_avatar_style(size);
717
            let image = build_image_style(size);
718

            
719
            // The image must be exactly as big and as round as its container,
720
            // otherwise it either leaves a gap or is clipped square at a corner.
721
            assert_eq!(
722
                width_px(&image),
723
                width_px(&container),
724
                "{size:?}: image width"
725
            );
726
            assert_eq!(
727
                height_px(&image),
728
                height_px(&container),
729
                "{size:?}: image height"
730
            );
731
            assert_eq!(
732
                radii_px(&image),
733
                radii_px(&container),
734
                "{size:?}: image radii"
735
            );
736
            assert_eq!(
737
                radii_px(&image).len(),
738
                4,
739
                "{size:?}: all four corners rounded"
740
            );
741
            // The image must not grow past the circle in a flex row.
742
            assert!(properties(&image)
743
                .contains(&CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))));
744
        }
745
    }
746

            
747
    #[test]
748
    fn build_image_style_declares_every_property_once_and_unconditionally() {
749
        for size in ALL_SIZES {
750
            let style = build_image_style(size);
751
            let mut seen = HashSet::new();
752
            for p in style.as_ref() {
753
                assert!(
754
                    seen.insert(core::mem::discriminant(&p.property)),
755
                    "{size:?}: duplicate declaration of {:?}",
756
                    p.property
757
                );
758
                assert!(
759
                    p.apply_if.as_ref().is_empty(),
760
                    "{size:?}: conditional image property"
761
                );
762
            }
763
            assert_eq!(
764
                properties(&build_image_style(size)),
765
                properties(&build_image_style(size)),
766
                "{size:?}: build_image_style is not deterministic"
767
            );
768
        }
769
    }
770

            
771
    #[test]
772
    fn every_emitted_length_is_a_finite_non_negative_px_value() {
773
        // `isize` -> `PixelValue` is the only numeric conversion in this file:
774
        // guard against a NaN/inf/negative length ever reaching the solver.
775
        for size in ALL_SIZES {
776
            for style in [build_avatar_style(size), build_image_style(size)] {
777
                let values = all_pixel_values(&style);
778
                assert!(!values.is_empty(), "{size:?}: no lengths emitted at all");
779
                for pv in values {
780
                    let n = px(&pv); // also asserts SizeMetric::Px
781
                    assert!(n.is_finite(), "{size:?}: non-finite length {n}");
782
                    assert!(n >= 0.0, "{size:?}: negative length {n}");
783
                    assert!(n <= 4096.0, "{size:?}: implausibly large length {n}");
784
                }
785
            }
786
        }
787
    }
788

            
789
    // ------------------------------------------------------------------
790
    // Avatar::create / create_with_image  (constructors)
791
    // ------------------------------------------------------------------
792

            
793
    #[test]
794
    fn create_round_trips_initials_verbatim() {
795
        // Adversarial strings: empty, combining marks, ZWJ emoji, RTL, embedded
796
        // NULs (AzString is length-based, so a NUL must NOT truncate), and a
797
        // string far longer than any real set of initials.
798
        let long = "x".repeat(100_000);
799
        let cases = [
800
            "",
801
            "AB",
802
            "e\u{0301}",                                   // e + combining acute
803
            "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}", // ZWJ family
804
            "\u{5E9}\u{5DC}",                              // RTL Hebrew
805
            "\0\0",                                        // embedded NULs
806
            "  ",                                          // whitespace only
807
            long.as_str(),
808
        ];
809

            
810
        for s in cases {
811
            let a = Avatar::create(AzString::from(s.to_string()));
812
            assert_eq!(
813
                a.initials.as_str(),
814
                s,
815
                "initials were not preserved verbatim"
816
            );
817
            assert_eq!(
818
                a.initials.len(),
819
                s.len(),
820
                "byte length changed (NUL truncation?)"
821
            );
822
            assert!(a.image.is_none(), "create() must not set an image");
823
            assert_eq!(a.size, AvatarSize::Medium);
824
            assert_eq!(
825
                properties(&a.resolved_avatar_style()),
826
                properties(&build_avatar_style(AvatarSize::Medium))
827
            );
828
        }
829
    }
830

            
831
    #[test]
832
    fn create_with_image_keeps_the_image_and_empty_initials() {
833
        let img = test_image();
834
        let hash = img.get_hash();
835
        let a = Avatar::create_with_image(img);
836

            
837
        assert!(a.image.is_some());
838
        match &a.image {
839
            OptionImageRef::Some(i) => {
840
                assert_eq!(i.get_hash(), hash, "a different image came back")
841
            }
842
            OptionImageRef::None => panic!("image was dropped by create_with_image"),
843
        }
844
        assert_eq!(
845
            a.initials.as_str(),
846
            "",
847
            "image avatars have empty fallback initials"
848
        );
849
        assert_eq!(a.size, AvatarSize::Medium);
850
    }
851

            
852
    #[test]
853
    fn default_avatar_equals_an_empty_medium_avatar() {
854
        let d = Avatar::default();
855
        assert_eq!(d, Avatar::create(AzString::from_const_str("")));
856
        assert_eq!(d.clone(), d, "Clone must preserve equality");
857
        assert_ne!(d, Avatar::create(AzString::from_const_str("AB")));
858
        assert_ne!(
859
            Avatar::create(AzString::from_const_str("AB")),
860
            Avatar::create(AzString::from_const_str("AB")).with_size(AvatarSize::Large),
861
            "avatars of different sizes must not compare equal"
862
        );
863
    }
864

            
865
    // ------------------------------------------------------------------
866
    // set_image / with_image / set_size / with_size  (setters)
867
    // ------------------------------------------------------------------
868

            
869
    #[test]
870
    fn with_image_and_set_image_agree_and_keep_the_other_fields() {
871
        let base = Avatar::create(AzString::from_const_str("AB")).with_size(AvatarSize::Large);
872

            
873
        let mut mutated = base.clone();
874
        mutated.set_image(test_image());
875
        let built = base.clone().with_image(test_image());
876

            
877
        assert!(mutated.image.is_some() && built.image.is_some());
878
        // Setting an image must not disturb the size, the style, or the fallback text.
879
        for a in [&mutated, &built] {
880
            assert_eq!(a.size, AvatarSize::Large);
881
            assert_eq!(
882
                a.initials.as_str(),
883
                "AB",
884
                "set_image must keep the fallback initials"
885
            );
886
            assert_eq!(
887
                properties(&a.resolved_avatar_style()),
888
                properties(&base.resolved_avatar_style())
889
            );
890
        }
891
    }
892

            
893
    #[test]
894
    fn set_image_replaces_a_previous_image_rather_than_stacking() {
895
        let first = test_image();
896
        let second = test_image();
897
        let (h1, h2) = (first.get_hash(), second.get_hash());
898
        assert_ne!(
899
            h1, h2,
900
            "fixture bug: the two images must be distinguishable"
901
        );
902

            
903
        let mut a = Avatar::create_with_image(first);
904
        a.set_image(second);
905
        match &a.image {
906
            OptionImageRef::Some(i) => assert_eq!(i.get_hash(), h2, "the second image must win"),
907
            OptionImageRef::None => panic!("image lost"),
908
        }
909
    }
910

            
911
    #[test]
912
    fn set_size_recomputes_the_style_without_growing_it() {
913
        // A `push`-instead-of-replace bug would make the style vec grow on every
914
        // call and leave stale (earlier-size) declarations behind.
915
        let mut a = Avatar::create(AzString::from_const_str("AB"));
916
        let expected_len = build_avatar_style(AvatarSize::Medium).as_ref().len();
917

            
918
        for round in 0..50 {
919
            let size = ALL_SIZES[round % ALL_SIZES.len()];
920
            a.set_size(size);
921

            
922
            assert_eq!(a.size, size, "round {round}: size field not updated");
923
            assert_eq!(
924
                a.resolved_avatar_style().as_slice().len(),
925
                expected_len,
926
                "round {round}: style vec changed length — stale declarations?"
927
            );
928
            assert_eq!(
929
                properties(&a.resolved_avatar_style()),
930
                properties(&build_avatar_style(size)),
931
                "round {round}: style does not match the freshly built one"
932
            );
933
            assert_eq!(
934
                a.initials.as_str(),
935
                "AB",
936
                "round {round}: set_size ate the initials"
937
            );
938
        }
939
    }
940

            
941
    #[test]
942
    fn set_size_keeps_the_image() {
943
        let mut a = Avatar::create_with_image(test_image());
944
        a.set_size(AvatarSize::Small);
945
        assert!(a.image.is_some(), "set_size must not drop the image");
946
        assert_eq!(width_px(&a.resolved_avatar_style()), Some(24.0));
947
    }
948

            
949
    #[test]
950
    fn with_size_is_last_call_wins_and_matches_set_size() {
951
        let chained = Avatar::create(AzString::from_const_str("AB"))
952
            .with_size(AvatarSize::Large)
953
            .with_size(AvatarSize::Small)
954
            .with_size(AvatarSize::Medium);
955

            
956
        let mut mutated = Avatar::create(AzString::from_const_str("AB"));
957
        mutated.set_size(AvatarSize::Large);
958
        mutated.set_size(AvatarSize::Small);
959
        mutated.set_size(AvatarSize::Medium);
960

            
961
        assert_eq!(chained, mutated, "builder and mutator must agree");
962
        assert_eq!(chained.size, AvatarSize::Medium);
963
        assert_eq!(
964
            properties(&chained.resolved_avatar_style()),
965
            properties(&build_avatar_style(AvatarSize::Medium))
966
        );
967
    }
968

            
969
    // ------------------------------------------------------------------
970
    // swap_with_default
971
    // ------------------------------------------------------------------
972

            
973
    #[test]
974
    fn swap_with_default_returns_the_original_and_leaves_a_default_behind() {
975
        let mut a = Avatar::create(AzString::from_const_str("AB"))
976
            .with_size(AvatarSize::Large)
977
            .with_image(test_image());
978

            
979
        let taken = a.swap_with_default();
980

            
981
        // The returned value is the *original*, intact.
982
        assert_eq!(taken.initials.as_str(), "AB");
983
        assert_eq!(taken.size, AvatarSize::Large);
984
        assert!(taken.image.is_some());
985
        assert_eq!(
986
            properties(&taken.resolved_avatar_style()),
987
            properties(&build_avatar_style(AvatarSize::Large))
988
        );
989

            
990
        // What is left behind is a *default* avatar — in particular its style
991
        // must be Medium's, not a stale Large one.
992
        assert_eq!(a, Avatar::default());
993
        assert!(
994
            a.image.is_none(),
995
            "the image must not survive in the emptied avatar"
996
        );
997
        assert_eq!(a.initials.as_str(), "");
998
        assert_eq!(a.size, AvatarSize::Medium);
999
        assert_eq!(
            properties(&a.resolved_avatar_style()),
            properties(&build_avatar_style(AvatarSize::Medium))
        );
    }
    #[test]
    fn swap_with_default_is_idempotent_on_an_already_default_avatar() {
        let mut a = Avatar::default();
        let first = a.swap_with_default();
        let second = a.swap_with_default();
        assert_eq!(first, Avatar::default());
        assert_eq!(second, Avatar::default());
        assert_eq!(a, Avatar::default());
    }
    // ------------------------------------------------------------------
    // Avatar::dom
    // ------------------------------------------------------------------
    #[test]
    fn dom_of_an_initials_avatar_is_a_circle_wrapping_the_text() {
        for size in ALL_SIZES {
            let avatar = Avatar::create(AzString::from_const_str("AB")).with_size(size);
            let expected = properties(&avatar.resolved_avatar_style());
            let dom = avatar.dom();
            assert!(
                has_class(&dom, "__azul-native-avatar"),
                "{size:?}: missing root class"
            );
            assert_eq!(
                inline_properties(&dom),
                expected,
                "{size:?}: the container lost its computed style"
            );
            let child = only_child(&dom);
            assert!(has_class(child, "__azul-native-avatar-initials"));
            assert_eq!(text_of(child), Some("AB"), "{size:?}: expected `p > text`");
        }
    }
    #[test]
    fn dom_of_an_image_avatar_renders_the_image_and_drops_the_initials() {
        for size in ALL_SIZES {
            let img = test_image();
            let hash = img.get_hash();
            // The initials are only a *fallback*: with an image set they must not
            // be rendered as a second child on top of the image.
            let avatar = Avatar::create(AzString::from_const_str("AB"))
                .with_size(size)
                .with_image(img);
            let dom = avatar.dom();
            let child = only_child(&dom);
            assert!(
                has_class(child, "__azul-native-avatar-image"),
                "{size:?}: missing image class"
            );
            assert!(
                !has_class(child, "__azul-native-avatar-initials"),
                "{size:?}: initials rendered on top of the image"
            );
            match child.root.get_node_type() {
                NodeType::Image(i) => {
                    assert_eq!(i.as_ref().get_hash(), hash, "{size:?}: wrong image")
                }
                other => panic!("{size:?}: expected an image child, got {other:?}"),
            }
            assert_eq!(
                inline_properties(child),
                properties(&build_image_style(size)),
                "{size:?}: the image child does not carry the matching circular style"
            );
        }
    }
    #[test]
    fn dom_preserves_adversarial_initials_verbatim() {
        let long = "\u{1F600}".repeat(10_000); // 40 000 bytes of emoji
        for s in ["", "\0", "e\u{0301}", "\u{5E9}\u{5DC}", long.as_str()] {
            let dom = Avatar::create(AzString::from(s.to_string())).dom();
            let child = only_child(&dom);
            match child.children.as_ref() {
                [only] => match only.root.get_node_type() {
                    NodeType::Text(t) => {
                        assert_eq!(t.as_ref().as_str(), s, "text node mangled the initials");
                        assert_eq!(
                            t.as_ref().len(),
                            s.len(),
                            "text node changed the byte length"
                        );
                    }
                    other => panic!("expected a text child, got {other:?}"),
                },
                other => panic!("expected `p > text`, got {} grandchildren", other.len()),
            }
        }
    }
    #[test]
    fn dom_and_the_from_impl_agree() {
        let avatar = Avatar::create(AzString::from_const_str("AB")).with_size(AvatarSize::Small);
        assert_eq!(Dom::from(avatar.clone()), avatar.dom());
    }
    #[test]
    fn dom_geometry_is_consistent_between_container_and_image_after_set_size() {
        // Through the supported API (`set_size` / `with_size`) the container and
        // the image must always resolve to the same diameter.
        for size in ALL_SIZES {
            let dom = Avatar::create_with_image(test_image())
                .with_size(size)
                .dom();
            #[allow(clippy::cast_precision_loss)]
            let d = size.diameter() as f32;
            let container: Vec<CssProperty> = inline_properties(&dom);
            let child: Vec<CssProperty> = inline_properties(only_child(&dom));
            let width_of = |props: &[CssProperty]| {
                props.iter().find_map(|p| match p {
                    CssProperty::Width(w) => match w.get_property()? {
                        LayoutWidth::Px(pv) => Some(px(pv)),
                        _ => None,
                    },
                    _ => None,
                })
            };
            assert_eq!(width_of(&container), Some(d), "{size:?}: container width");
            assert_eq!(width_of(&child), Some(d), "{size:?}: image width");
        }
    }
    #[test]
    fn assigning_the_size_field_directly_keeps_the_container_and_the_image_in_step() {
        // `size` and `avatar_style` are both public, and a direct field write
        // used to desync them: `dom()` read the image geometry from `size`
        // while the container kept whatever style the constructor had stored,
        // so bypassing `set_size` rendered a Large image inside a Medium
        // circle. There is no stored style left to go stale —
        // `resolved_avatar_style` derives it from `size` — so the bypass and
        // `set_size` now reach the same DOM.
        let mut assigned = Avatar::create_with_image(test_image());
        assigned.size = AvatarSize::Large; // the bypass the old desync needed
        let mut via_setter = Avatar::create_with_image(test_image());
        via_setter.set_size(AvatarSize::Large);
        let dom = assigned.dom();
        assert_eq!(
            inline_properties(&dom),
            inline_properties(&via_setter.dom()),
            "a direct `size` write must render like `set_size`"
        );
        let container_width = inline_properties(&dom).iter().find_map(|p| match p {
            CssProperty::Width(w) => match w.get_property()? {
                LayoutWidth::Px(pv) => Some(px(pv)),
                _ => None,
            },
            _ => None,
        });
        assert_eq!(
            container_width,
            width_px(&build_avatar_style(AvatarSize::Large)),
            "the circle follows the freshly assigned `size` field"
        );
        assert_ne!(
            width_px(&build_avatar_style(AvatarSize::Large)),
            width_px(&build_avatar_style(AvatarSize::Medium)),
            "fixture: the two sizes have to differ for this to prove anything"
        );
        assert_eq!(
            inline_properties(only_child(&dom)),
            properties(&build_image_style(AvatarSize::Large)),
            "and so does the image inside it"
        );
    }
}