1
//! Spinner / activity-indicator widget — a small indeterminate "busy" ring. A
2
//! stateless single styled node (a near-clone of the leaf-node construction of
3
//! [`crate::widgets::badge::Badge`] / [`crate::widgets::progressbar::ProgressBar`]),
4
//! drawn as a circular ring whose three sides use a faint "track" colour and
5
//! whose top side uses a solid accent colour — the classic spinner look frozen
6
//! mid-rotation.
7
//!
8
//! ## PARTIAL — STATIC ONLY (no spin animation). See `TODO2` below.
9
//!
10
//! TODO2: this spinner is **static** — it shows the indeterminate ring shape but
11
//! does NOT rotate. Azul has no declarative CSS animation: there is no
12
//! `@keyframes` / `animation` / `transition` CSS property (`css/src/props` only
13
//! exposes one-shot `Transform`/`TransformOrigin` GPU props and the system-level
14
//! `AnimationMetrics` toggle; `props/basic/animation.rs` is SVG-curve
15
//! interpolation maths, not a style-driven keyframe engine). Producing real
16
//! motion would require a timer-driven `Update` loop that re-issues a rotating
17
//! `CssProperty::Transform` each tick (the same mechanism scroll-smoothing uses),
18
//! driven from the host app — there is no widget-local way to start such a timer
19
//! at DOM-build time. Rather than fake motion that cannot be produced, the ring
20
//! is rendered statically; a future revision can add the timer-driven rotation
21
//! once a widget-owned animation hook exists. (Compile-verified; not GUI-verified.)
22
//!
23
//! Key types: [`Spinner`].
24

            
25
use azul_core::dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec};
26
use azul_css::{
27
    dynamic_selector::{
28
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
29
    },
30
    props::{
31
        basic::{color::ColorU, *},
32
        layout::{LayoutAlignSelf, LayoutFlexGrow, LayoutHeight, LayoutWidth},
33
        property::{CssProperty, *},
34
        style::{
35
            BorderStyle, LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
36
            LayoutBorderTopWidth, StyleBorderBottomColor, StyleBorderBottomLeftRadius,
37
            StyleBorderBottomRightRadius, StyleBorderBottomStyle, StyleBorderLeftColor,
38
            StyleBorderLeftStyle, StyleBorderRightColor, StyleBorderRightStyle,
39
            StyleBorderTopColor, StyleBorderTopLeftRadius, StyleBorderTopRightRadius,
40
            StyleBorderTopStyle,
41
        },
42
    },
43
    AzString,
44
};
45

            
46
static SPINNER_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str("__azul-native-spinner"))];
47

            
48
/// Default ring diameter, in logical px.
49
const DEFAULT_SIZE: isize = 24;
50
/// Faint "track" colour for the three inactive sides (#d0d4d9).
51
const DEFAULT_TRACK_COLOR: ColorU = ColorU {
52
    r: 208,
53
    g: 212,
54
    b: 217,
55
    a: 255,
56
};
57
/// Solid accent colour for the active (top) arc (#0d6efd, accent blue).
58
const DEFAULT_ACCENT_COLOR: ColorU = ColorU {
59
    r: 13,
60
    g: 110,
61
    b: 253,
62
    a: 255,
63
};
64

            
65
/// An indeterminate busy-indicator ring. Stateless; renders a single styled
66
/// node. **Static** — the ring shows the spinner shape but does not rotate
67
/// (see the module-level `TODO2`).
68
#[derive(Debug, Clone, PartialEq, Eq)]
69
#[repr(C)]
70
pub struct Spinner {
71
    /// The ring diameter, in logical px.
72
    pub size: isize,
73
    /// Colour of the active (top) arc.
74
    pub color: ColorU,
75
    /// Colour of the three inactive ("track") sides.
76
    pub track_color: ColorU,
77
    /// The ring's CSS, or `None` for "no opinion" — in which case the style is
78
    /// derived from `size`, `color` and `track_color` at render time.
79
    ///
80
    /// `None` and `Some(empty)` are different answers: the first means the
81
    /// widget picks, the second means the caller asked for no properties at all
82
    /// and gets none.
83
    pub spinner_style: OptionCssPropertyWithConditionsVec,
84
}
85

            
86
/// Builds the ring style for the given diameter and colours. All three are
87
/// instance-dependent, so the style is built at runtime per the recipe's
88
/// "runtime vec when param-dependent" path (see `badge::build_badge_style`).
89
1407
fn build_spinner_style(
90
1407
    size: isize,
91
1407
    color: ColorU,
92
1407
    track_color: ColorU,
93
1407
) -> CssPropertyWithConditionsVec {
94
    // Ring thickness scales with the diameter (min 2px); radius = size/2 → circle.
95
1407
    let border_width = (size / 8).max(2);
96
1407
    let radius = size / 2;
97
1407
    CssPropertyWithConditionsVec::from_vec(alloc::vec![
98
        // Hug its own size inside a flex parent rather than stretch/grow.
99
1407
        CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Start)),
100
1407
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
101
            0,
102
        ))),
103
1407
        CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(size))),
104
1407
        CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(size))),
105
        // border: <border_width>px solid — three sides track, top accent.
106
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
107
1407
            LayoutBorderTopWidth::const_px(border_width),
108
        )),
109
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
110
1407
            LayoutBorderBottomWidth::const_px(border_width),
111
        )),
112
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
113
1407
            LayoutBorderLeftWidth::const_px(border_width),
114
        )),
115
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
116
1407
            LayoutBorderRightWidth::const_px(border_width),
117
        )),
118
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_top_style(
119
1407
            StyleBorderTopStyle {
120
1407
                inner: BorderStyle::Solid,
121
1407
            }
122
        )),
123
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
124
1407
            StyleBorderBottomStyle {
125
1407
                inner: BorderStyle::Solid,
126
1407
            },
127
        )),
128
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_left_style(
129
1407
            StyleBorderLeftStyle {
130
1407
                inner: BorderStyle::Solid,
131
1407
            }
132
        )),
133
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
134
1407
            StyleBorderRightStyle {
135
1407
                inner: BorderStyle::Solid,
136
1407
            },
137
        )),
138
        // top = accent (the visible "arc"); other three = faint track.
139
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_top_color(
140
1407
            StyleBorderTopColor { inner: color }
141
        )),
142
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
143
1407
            StyleBorderBottomColor { inner: track_color },
144
        )),
145
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_left_color(
146
1407
            StyleBorderLeftColor { inner: track_color }
147
        )),
148
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
149
1407
            StyleBorderRightColor { inner: track_color },
150
        )),
151
        // border-radius: size/2 → a circle.
152
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
153
1407
            StyleBorderTopLeftRadius::const_px(radius),
154
        )),
155
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
156
1407
            StyleBorderTopRightRadius::const_px(radius),
157
        )),
158
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
159
1407
            StyleBorderBottomLeftRadius::const_px(radius),
160
        )),
161
1407
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
162
1407
            StyleBorderBottomRightRadius::const_px(radius),
163
        )),
164
    ])
165
1407
}
166

            
167
impl Spinner {
168
    /// Creates a new spinner with the default size (24px) and accent colour.
169
    #[inline]
170
    #[must_use]
171
66
    pub const fn create() -> Self {
172
66
        Self::with_size(DEFAULT_SIZE)
173
66
    }
174

            
175
    /// Creates a new spinner with the given diameter (logical px) and the
176
    /// default colours.
177
    #[inline]
178
    #[must_use]
179
156
    pub const fn with_size(size: isize) -> Self {
180
156
        Self {
181
156
            size,
182
156
            color: DEFAULT_ACCENT_COLOR,
183
156
            track_color: DEFAULT_TRACK_COLOR,
184
156
            spinner_style: OptionCssPropertyWithConditionsVec::None,
185
156
        }
186
156
    }
187

            
188
    /// The ring CSS this spinner renders with.
189
    ///
190
    /// `None` means no opinion, so the geometry and colours decide — the same
191
    /// answer both themes give, asked in one place so they cannot drift. It is
192
    /// also what makes the three setters below plain field writes: there is no
193
    /// cached vec left for them to keep in step.
194
    #[must_use]
195
151
    pub fn resolved_spinner_style(&self) -> CssPropertyWithConditionsVec {
196
151
        self.spinner_style
197
151
            .clone()
198
151
            .into_option()
199
151
            .unwrap_or_else(|| build_spinner_style(self.size, self.color, self.track_color))
200
151
    }
201

            
202
    /// Sets the ring diameter (logical px).
203
    #[inline]
204
155
    pub const fn set_size(&mut self, size: isize) {
205
155
        self.size = size;
206
155
    }
207

            
208
    /// Builder-style setter for the ring diameter.
209
    #[inline]
210
    #[must_use]
211
21
    pub const fn with_spinner_size(mut self, size: isize) -> Self {
212
21
        self.set_size(size);
213
21
        self
214
21
    }
215

            
216
    /// Sets the active-arc colour.
217
    #[inline]
218
181
    pub const fn set_color(&mut self, color: ColorU) {
219
181
        self.color = color;
220
181
    }
221

            
222
    /// Builder-style setter for the active-arc colour.
223
    #[inline]
224
    #[must_use]
225
79
    pub const fn with_color(mut self, color: ColorU) -> Self {
226
79
        self.set_color(color);
227
79
        self
228
79
    }
229

            
230
    /// Sets the inactive "track" colour.
231
    #[inline]
232
179
    pub const fn set_track_color(&mut self, track_color: ColorU) {
233
179
        self.track_color = track_color;
234
179
    }
235

            
236
    /// Builder-style setter for the inactive "track" colour.
237
    #[inline]
238
    #[must_use]
239
76
    pub const fn with_track_color(mut self, track_color: ColorU) -> Self {
240
76
        self.set_track_color(track_color);
241
76
        self
242
76
    }
243

            
244
    /// Replaces `self` with a default spinner and returns the original.
245
    #[inline]
246
    #[must_use]
247
4
    pub const fn swap_with_default(&mut self) -> Self {
248
4
        let mut s = Self::create();
249
4
        core::mem::swap(&mut s, self);
250
4
        s
251
4
    }
252

            
253
    /// Converts this spinner into a single DOM node with the
254
    /// `__azul-native-spinner` class.
255
    #[inline]
256
    #[must_use]
257
58
    pub fn dom(self) -> Dom {
258
58
        Dom::create_div()
259
58
            .with_ids_and_classes(IdOrClassVec::from_const_slice(SPINNER_CLASS))
260
58
            .with_css_props(self.resolved_spinner_style())
261
58
    }
262
}
263

            
264
impl Default for Spinner {
265
1
    fn default() -> Self {
266
1
        Self::create()
267
1
    }
268
}
269

            
270
impl From<Spinner> for Dom {
271
1
    fn from(s: Spinner) -> Self {
272
1
        s.dom()
273
1
    }
274
}
275

            
276
#[cfg(test)]
277
#[allow(
278
    clippy::too_many_lines,
279
    clippy::unreadable_literal,
280
    clippy::cast_possible_truncation,
281
    clippy::cast_precision_loss,
282
    clippy::float_cmp
283
)]
284
mod autotest_generated {
285
    use azul_core::dom::NodeType;
286

            
287
    use super::*;
288

            
289
    // ------------------------------------------------------------------
290
    // Helpers
291
    // ------------------------------------------------------------------
292

            
293
    /// The number of declarations `build_spinner_style` is supposed to emit.
294
    const DECLARATIONS: usize = 20;
295

            
296
    /// Every property the ring declares, in source order. A missing side (or a
297
    /// side declared twice) is the difference between a ring and a solid box.
298
    const EXPECTED_ORDER: [CssPropertyType; DECLARATIONS] = [
299
        CssPropertyType::AlignSelf,
300
        CssPropertyType::FlexGrow,
301
        CssPropertyType::Width,
302
        CssPropertyType::Height,
303
        CssPropertyType::BorderTopWidth,
304
        CssPropertyType::BorderBottomWidth,
305
        CssPropertyType::BorderLeftWidth,
306
        CssPropertyType::BorderRightWidth,
307
        CssPropertyType::BorderTopStyle,
308
        CssPropertyType::BorderBottomStyle,
309
        CssPropertyType::BorderLeftStyle,
310
        CssPropertyType::BorderRightStyle,
311
        CssPropertyType::BorderTopColor,
312
        CssPropertyType::BorderBottomColor,
313
        CssPropertyType::BorderLeftColor,
314
        CssPropertyType::BorderRightColor,
315
        CssPropertyType::BorderTopLeftRadius,
316
        CssPropertyType::BorderTopRightRadius,
317
        CssPropertyType::BorderBottomLeftRadius,
318
        CssPropertyType::BorderBottomRightRadius,
319
    ];
320

            
321
    /// `FloatValue` stores `value * FP_PRECISION_MULTIPLIER` as an `isize`, so a
322
    /// whole-pixel size only survives while `|size| <= isize::MAX / 1000`.
323
    const FP_SCALE: isize = 1000;
324

            
325
    /// The largest / smallest diameters that still fit the fixed-point encoding.
326
    /// `isize::MIN / 1000` truncates toward zero, so it scales back to
327
    /// `-9223372036854775000`, one step inside `isize::MIN`.
328
    const MAX_ENCODABLE_SIZE: isize = isize::MAX / FP_SCALE;
329
    const MIN_ENCODABLE_SIZE: isize = isize::MIN / FP_SCALE;
330

            
331
    /// Diameters that must all build a style without panicking: the degenerate
332
    /// small ones (where the 2px floor is thicker than the box), the ordinary
333
    /// ones, negatives (nothing in the widget rejects them), and both ends of
334
    /// the encodable range.
335
    const SAFE_SIZES: [isize; 16] = [
336
        0,
337
        1,
338
        2,
339
        3,
340
        4,
341
        7,
342
        8,
343
        15,
344
        16,
345
        24,
346
        1_000,
347
        -1,
348
        -3,
349
        -24,
350
        MAX_ENCODABLE_SIZE,
351
        MIN_ENCODABLE_SIZE,
352
    ];
353

            
354
    /// Colours that are trivially distinguishable in a failure message, plus the
355
    /// fully transparent one (alpha is carried untouched, so it must survive).
356
    const RED: ColorU = ColorU {
357
        r: 255,
358
        g: 0,
359
        b: 0,
360
        a: 255,
361
    };
362
    const GREEN: ColorU = ColorU {
363
        r: 0,
364
        g: 255,
365
        b: 0,
366
        a: 255,
367
    };
368
    const GHOST: ColorU = ColorU {
369
        r: 0,
370
        g: 0,
371
        b: 0,
372
        a: 0,
373
    };
374

            
375
    /// The declared properties of a style vec, in declaration order.
376
    fn props(v: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
377
        v.as_slice().iter().map(|p| p.property.clone()).collect()
378
    }
379

            
380
    /// The first property matching `f`, or `None` if the style never declares it.
381
    fn find<T>(
382
        v: &CssPropertyWithConditionsVec,
383
        f: impl Fn(&CssProperty) -> Option<T>,
384
    ) -> Option<T> {
385
        v.as_slice().iter().find_map(|p| f(&p.property))
386
    }
387

            
388
    /// The raw fixed-point encoding of a length — the value that actually
389
    /// survives, without a second lossy round trip through `get()`.
390
    fn raw(pv: PixelValue) -> isize {
391
        pv.number.number()
392
    }
393

            
394
    fn width(v: &CssPropertyWithConditionsVec) -> PixelValue {
395
        find(v, |p| match p {
396
            CssProperty::Width(x) => match x.get_property() {
397
                Some(LayoutWidth::Px(pv)) => Some(*pv),
398
                other => panic!("the ring must size in absolute lengths, got {other:?}"),
399
            },
400
            _ => None,
401
        })
402
        .expect("the ring must declare a width")
403
    }
404

            
405
    fn height(v: &CssPropertyWithConditionsVec) -> PixelValue {
406
        find(v, |p| match p {
407
            CssProperty::Height(x) => match x.get_property() {
408
                Some(LayoutHeight::Px(pv)) => Some(*pv),
409
                other => panic!("the ring must size in absolute lengths, got {other:?}"),
410
            },
411
            _ => None,
412
        })
413
        .expect("the ring must declare a height")
414
    }
415

            
416
    /// Border widths in `[top, right, bottom, left]` order.
417
    fn border_widths(v: &CssPropertyWithConditionsVec) -> [PixelValue; 4] {
418
        [
419
            find(v, |p| match p {
420
                CssProperty::BorderTopWidth(x) => x.get_property().map(|x| x.inner),
421
                _ => None,
422
            }),
423
            find(v, |p| match p {
424
                CssProperty::BorderRightWidth(x) => x.get_property().map(|x| x.inner),
425
                _ => None,
426
            }),
427
            find(v, |p| match p {
428
                CssProperty::BorderBottomWidth(x) => x.get_property().map(|x| x.inner),
429
                _ => None,
430
            }),
431
            find(v, |p| match p {
432
                CssProperty::BorderLeftWidth(x) => x.get_property().map(|x| x.inner),
433
                _ => None,
434
            }),
435
        ]
436
        .map(|o| o.expect("the ring must declare all four border widths"))
437
    }
438

            
439
    /// Border colours in `[top, right, bottom, left]` order.
440
    fn border_colors(v: &CssPropertyWithConditionsVec) -> [ColorU; 4] {
441
        [
442
            find(v, |p| match p {
443
                CssProperty::BorderTopColor(x) => x.get_property().map(|x| x.inner),
444
                _ => None,
445
            }),
446
            find(v, |p| match p {
447
                CssProperty::BorderRightColor(x) => x.get_property().map(|x| x.inner),
448
                _ => None,
449
            }),
450
            find(v, |p| match p {
451
                CssProperty::BorderBottomColor(x) => x.get_property().map(|x| x.inner),
452
                _ => None,
453
            }),
454
            find(v, |p| match p {
455
                CssProperty::BorderLeftColor(x) => x.get_property().map(|x| x.inner),
456
                _ => None,
457
            }),
458
        ]
459
        .map(|o| o.expect("the ring must declare all four border colours"))
460
    }
461

            
462
    /// Border styles in `[top, right, bottom, left]` order.
463
    fn border_styles(v: &CssPropertyWithConditionsVec) -> [BorderStyle; 4] {
464
        [
465
            find(v, |p| match p {
466
                CssProperty::BorderTopStyle(x) => x.get_property().map(|x| x.inner),
467
                _ => None,
468
            }),
469
            find(v, |p| match p {
470
                CssProperty::BorderRightStyle(x) => x.get_property().map(|x| x.inner),
471
                _ => None,
472
            }),
473
            find(v, |p| match p {
474
                CssProperty::BorderBottomStyle(x) => x.get_property().map(|x| x.inner),
475
                _ => None,
476
            }),
477
            find(v, |p| match p {
478
                CssProperty::BorderLeftStyle(x) => x.get_property().map(|x| x.inner),
479
                _ => None,
480
            }),
481
        ]
482
        .map(|o| o.expect("the ring must declare all four border styles"))
483
    }
484

            
485
    /// Corner radii in `[top-left, top-right, bottom-left, bottom-right]` order.
486
    fn radii(v: &CssPropertyWithConditionsVec) -> [PixelValue; 4] {
487
        [
488
            find(v, |p| match p {
489
                CssProperty::BorderTopLeftRadius(x) => x.get_property().map(|x| x.inner),
490
                _ => None,
491
            }),
492
            find(v, |p| match p {
493
                CssProperty::BorderTopRightRadius(x) => x.get_property().map(|x| x.inner),
494
                _ => None,
495
            }),
496
            find(v, |p| match p {
497
                CssProperty::BorderBottomLeftRadius(x) => x.get_property().map(|x| x.inner),
498
                _ => None,
499
            }),
500
            find(v, |p| match p {
501
                CssProperty::BorderBottomRightRadius(x) => x.get_property().map(|x| x.inner),
502
                _ => None,
503
            }),
504
        ]
505
        .map(|o| o.expect("the ring must declare all four corner radii"))
506
    }
507

            
508
    /// Every absolute length the style declares — width, height, the four border
509
    /// widths and the four radii.
510
    fn lengths(v: &CssPropertyWithConditionsVec) -> Vec<PixelValue> {
511
        let mut out = vec![width(v), height(v)];
512
        out.extend(border_widths(v));
513
        out.extend(radii(v));
514
        out
515
    }
516

            
517
    /// The properties a built DOM node carries inline, in declaration order.
518
    fn dom_props(dom: &Dom) -> Vec<CssProperty> {
519
        dom.root
520
            .style
521
            .iter_inline_properties()
522
            .map(|(p, _)| p.clone())
523
            .collect()
524
    }
525

            
526
    fn dom_classes(dom: &Dom) -> Vec<String> {
527
        dom.root
528
            .get_ids_and_classes()
529
            .as_ref()
530
            .iter()
531
            .filter_map(|c| match c {
532
                Class(s) => Some(s.as_str().to_string()),
533
                IdOrClass::Id(_) => None,
534
            })
535
            .collect()
536
    }
537

            
538
    // ==================================================================
539
    // build_spinner_style — shape of the emitted style
540
    // ==================================================================
541

            
542
    #[test]
543
    fn build_spinner_style_declares_every_side_exactly_once() {
544
        // A ring is four independently-declared sides. A dropped or duplicated
545
        // declaration silently turns the spinner into a box (or a solid disc).
546
        for size in SAFE_SIZES {
547
            let style = build_spinner_style(size, RED, GREEN);
548
            let types: Vec<CssPropertyType> =
549
                props(&style).iter().map(CssProperty::get_type).collect();
550

            
551
            assert_eq!(
552
                style.len(),
553
                DECLARATIONS,
554
                "declaration count changed for {size}"
555
            );
556
            assert_eq!(
557
                types,
558
                EXPECTED_ORDER.to_vec(),
559
                "declaration order changed for {size}"
560
            );
561

            
562
            let mut sorted = types.clone();
563
            sorted.sort_unstable();
564
            sorted.dedup();
565
            assert_eq!(
566
                sorted.len(),
567
                DECLARATIONS,
568
                "a property is declared twice for {size}"
569
            );
570
        }
571
    }
572

            
573
    #[test]
574
    fn build_spinner_style_declarations_are_all_unconditional() {
575
        // `simple()` means "no @media/@os/:hover guard". A condition sneaking in
576
        // would make the ring vanish on some platforms only.
577
        let style = build_spinner_style(24, RED, GREEN);
578
        for p in style.as_slice() {
579
            assert!(
580
                p.apply_if.is_empty(),
581
                "{:?} became conditional: {:?}",
582
                p.property.get_type(),
583
                p.apply_if,
584
            );
585
        }
586
    }
587

            
588
    #[test]
589
    fn build_spinner_style_is_deterministic() {
590
        for size in SAFE_SIZES {
591
            assert_eq!(
592
                build_spinner_style(size, RED, GREEN),
593
                build_spinner_style(size, RED, GREEN),
594
                "two identical calls produced different styles for {size}",
595
            );
596
        }
597
    }
598

            
599
    // ==================================================================
600
    // build_spinner_style — numeric edges
601
    // ==================================================================
602

            
603
    #[test]
604
    fn build_spinner_style_at_zero_size() {
605
        // 0 / 8 = 0, so the `.max(2)` floor is what keeps the border declarable;
606
        // the radius collapses to 0 and the box to 0x0.
607
        let style = build_spinner_style(0, RED, GREEN);
608

            
609
        assert_eq!(raw(width(&style)), 0);
610
        assert_eq!(raw(height(&style)), 0);
611
        for bw in border_widths(&style) {
612
            assert_eq!(
613
                raw(bw),
614
                2 * FP_SCALE,
615
                "the 2px border floor stopped applying at size 0"
616
            );
617
        }
618
        for r in radii(&style) {
619
            assert_eq!(raw(r), 0, "a zero-diameter ring must have a zero radius");
620
        }
621
    }
622

            
623
    #[test]
624
    fn border_width_is_an_eighth_of_the_size_with_a_two_px_floor() {
625
        // `(size / 8).max(2)`: integer division truncates toward zero, and every
626
        // negative eighth is swallowed by the floor.
627
        for size in (-256_isize..=256).chain(SAFE_SIZES) {
628
            let style = build_spinner_style(size, RED, GREEN);
629
            let expected = (size / 8).max(2);
630

            
631
            for bw in border_widths(&style) {
632
                assert_eq!(
633
                    raw(bw),
634
                    expected * FP_SCALE,
635
                    "border width wrong for size {size}",
636
                );
637
                assert!(
638
                    raw(bw) >= 2 * FP_SCALE,
639
                    "border width dropped below 2px for {size}"
640
                );
641
            }
642
        }
643
    }
644

            
645
    #[test]
646
    fn radius_is_half_the_size_truncated_toward_zero() {
647
        // `size / 2` truncates, so odd diameters get a radius half a pixel short
648
        // of a perfect circle — deterministic, and identical on all four corners.
649
        for size in (-256_isize..=256).chain(SAFE_SIZES) {
650
            let style = build_spinner_style(size, RED, GREEN);
651
            let corners = radii(&style);
652

            
653
            for r in corners {
654
                assert_eq!(
655
                    raw(r),
656
                    (size / 2) * FP_SCALE,
657
                    "radius wrong for size {size}"
658
                );
659
            }
660
            assert!(
661
                corners.iter().all(|r| *r == corners[0]),
662
                "the four corners disagree for size {size}: {corners:?}",
663
            );
664
        }
665
    }
666

            
667
    #[test]
668
    fn negative_sizes_pass_straight_through_unclamped() {
669
        // Nothing rejects or clamps a negative diameter: the box and the radius
670
        // both go negative while the border keeps its 2px floor. Pinned because
671
        // it is the *only* documented behaviour — if the widget ever starts
672
        // clamping to 0, this flips loudly rather than silently changing layout.
673
        let style = build_spinner_style(-24, RED, GREEN);
674

            
675
        assert_eq!(raw(width(&style)), -24 * FP_SCALE);
676
        assert_eq!(raw(height(&style)), -24 * FP_SCALE);
677
        assert_eq!(raw(border_widths(&style)[0]), 2 * FP_SCALE);
678
        assert_eq!(raw(radii(&style)[0]), -12 * FP_SCALE);
679
    }
680

            
681
    #[test]
682
    fn the_ring_is_thicker_than_its_box_only_below_four_px() {
683
        // Below 4px the 2px-per-side floor eats more than the whole diameter, so
684
        // the "ring" degenerates into a filled blob. Above it, `size / 8` keeps
685
        // the two borders at a quarter of the box at most.
686
        for size in 0_isize..=64 {
687
            let style = build_spinner_style(size, RED, GREEN);
688
            let total = 2 * (raw(border_widths(&style)[0]) / FP_SCALE);
689

            
690
            if size >= 4 {
691
                assert!(
692
                    total <= size,
693
                    "size {size}: borders ({total}px) overflow the box"
694
                );
695
            } else {
696
                assert!(
697
                    total > size,
698
                    "size {size}: expected the degenerate 2px-floor ring"
699
                );
700
            }
701
        }
702
    }
703

            
704
    #[test]
705
    fn every_length_is_an_absolute_pixel() {
706
        // A relative unit here would resolve against the parent font or box and
707
        // either vanish or blow up — the ring must be self-contained.
708
        for size in SAFE_SIZES {
709
            let style = build_spinner_style(size, RED, GREEN);
710
            for length in lengths(&style) {
711
                assert_eq!(
712
                    length.metric,
713
                    SizeMetric::Px,
714
                    "size {size} produced a relative length: {length:?}",
715
                );
716
            }
717
        }
718
    }
719

            
720
    #[test]
721
    fn size_round_trips_through_the_fixed_point_encoding() {
722
        // encode == decode: the diameter goes in as an `isize` and must come back
723
        // out of the style unchanged, including at both ends of the range.
724
        for size in SAFE_SIZES {
725
            let style = build_spinner_style(size, RED, GREEN);
726

            
727
            assert_eq!(
728
                raw(width(&style)),
729
                size * FP_SCALE,
730
                "width encoding lost {size}"
731
            );
732
            assert_eq!(
733
                raw(width(&style)) / FP_SCALE,
734
                size,
735
                "width did not round-trip for {size}"
736
            );
737
            assert_eq!(
738
                raw(height(&style)) / FP_SCALE,
739
                size,
740
                "height did not round-trip for {size}"
741
            );
742

            
743
            // The `f32` view is only exact for values a float can hold.
744
            if size.abs() <= 1_000 {
745
                assert_eq!(
746
                    width(&style).number.get(),
747
                    size as f32,
748
                    "float view wrong for {size}",
749
                );
750
            }
751
        }
752
    }
753

            
754
    #[test]
755
    fn the_edges_of_the_encodable_range_do_not_overflow() {
756
        // `isize::MAX / 1000` is the largest whole-pixel diameter `const_px` can
757
        // scale without wrapping; one more is the overflow pinned below.
758
        for size in [MAX_ENCODABLE_SIZE, MIN_ENCODABLE_SIZE] {
759
            let style = build_spinner_style(size, RED, GREEN);
760

            
761
            assert_eq!(style.len(), DECLARATIONS);
762
            assert_eq!(raw(width(&style)), size * FP_SCALE);
763
            assert_eq!(raw(radii(&style)[0]), (size / 2) * FP_SCALE);
764
            assert_eq!(raw(border_widths(&style)[0]), (size / 8).max(2) * FP_SCALE);
765
        }
766
    }
767

            
768
    #[cfg(panic = "unwind")]
769
    #[test]
770
    fn sizes_beyond_the_encodable_range_are_not_saturated() {
771
        use std::{
772
            hint::black_box,
773
            panic::{catch_unwind, AssertUnwindSafe},
774
        };
775

            
776
        // LATENT BUG, pinned: `PixelValue::const_px` multiplies by 1000 with a
777
        // plain `*`, so any diameter above `isize::MAX / 1000` (~9.2e15) either
778
        // panics (overflow checks on: `Spinner::with_size(isize::MAX)` kills a
779
        // debug build) or wraps to a garbage length (checks off) — it never
780
        // saturates. Asserted against a probe of the *current* profile so the
781
        // test is profile-independent; adding saturation flips it loudly.
782
        let profile_traps_overflow = catch_unwind(AssertUnwindSafe(|| {
783
            let big = black_box(isize::MAX);
784
            let _ = black_box(big * FP_SCALE);
785
        }))
786
        .is_err();
787

            
788
        for size in [
789
            isize::MAX,
790
            isize::MIN,
791
            MAX_ENCODABLE_SIZE + 1,
792
            MIN_ENCODABLE_SIZE - 1,
793
        ] {
794
            let widget_panicked = catch_unwind(AssertUnwindSafe(|| {
795
                drop(build_spinner_style(size, RED, GREEN))
796
            }))
797
            .is_err();
798

            
799
            assert_eq!(
800
                widget_panicked, profile_traps_overflow,
801
                "size {size}: the fixed-point encoding no longer behaves like a raw multiply \
802
                 (expected panic == {profile_traps_overflow})",
803
            );
804
        }
805
    }
806

            
807
    // ==================================================================
808
    // build_spinner_style — colour placement
809
    // ==================================================================
810

            
811
    #[test]
812
    fn only_the_top_side_gets_the_accent_colour() {
813
        // The whole spinner illusion is "one lit side, three faint ones". Swapping
814
        // a side would render a static ring with no visible arc.
815
        for (color, track) in [
816
            (RED, GREEN),
817
            (GHOST, RED),
818
            (RED, GHOST),
819
            (RED, RED),
820
            (
821
                ColorU {
822
                    r: 0,
823
                    g: 0,
824
                    b: 0,
825
                    a: 0,
826
                },
827
                ColorU {
828
                    r: 255,
829
                    g: 255,
830
                    b: 255,
831
                    a: 255,
832
                },
833
            ),
834
        ] {
835
            let style = build_spinner_style(24, color, track);
836
            let [top, right, bottom, left] = border_colors(&style);
837

            
838
            assert_eq!(top, color, "the top side lost the accent colour");
839
            assert_eq!(
840
                [right, bottom, left],
841
                [track; 3],
842
                "a track side lost its colour"
843
            );
844
        }
845
    }
846

            
847
    #[test]
848
    fn colour_channels_survive_untouched() {
849
        // Alpha in particular: a fully transparent accent must stay transparent
850
        // rather than being normalised to opaque somewhere in the pipeline.
851
        for a in [0_u8, 1, 127, 255] {
852
            let color = ColorU {
853
                r: 1,
854
                g: 2,
855
                b: 3,
856
                a,
857
            };
858
            let track = ColorU {
859
                r: 253,
860
                g: 254,
861
                b: 255,
862
                a: 255 - a,
863
            };
864
            let style = build_spinner_style(24, color, track);
865
            let [top, right, bottom, left] = border_colors(&style);
866

            
867
            assert_eq!((top.r, top.g, top.b, top.a), (1, 2, 3, a));
868
            for side in [right, bottom, left] {
869
                assert_eq!((side.r, side.g, side.b, side.a), (253, 254, 255, 255 - a));
870
            }
871
        }
872
    }
873

            
874
    #[test]
875
    fn all_four_sides_are_solid() {
876
        // `BorderStyle::None` on any side would delete that quarter of the ring.
877
        for size in SAFE_SIZES {
878
            assert_eq!(
879
                border_styles(&build_spinner_style(size, RED, GREEN)),
880
                [BorderStyle::Solid; 4],
881
                "a side stopped being solid at size {size}",
882
            );
883
        }
884
    }
885

            
886
    #[test]
887
    fn the_ring_neither_grows_nor_stretches() {
888
        // `align-self: start` + `flex-grow: 0` are what stop a flex parent from
889
        // stretching the ring into an ellipse.
890
        let style = build_spinner_style(24, RED, GREEN);
891

            
892
        let align = find(&style, |p| match p {
893
            CssProperty::AlignSelf(x) => x.get_property().copied(),
894
            _ => None,
895
        });
896
        let grow = find(&style, |p| match p {
897
            CssProperty::FlexGrow(x) => x.get_property().map(|x| x.inner),
898
            _ => None,
899
        });
900

            
901
        assert_eq!(align, Some(LayoutAlignSelf::Start));
902
        assert_eq!(grow.map(|g| g.number()), Some(0));
903
    }
904

            
905
    // ==================================================================
906
    // create / with_size / Default — construction invariants
907
    // ==================================================================
908

            
909
    #[test]
910
    fn create_matches_the_documented_defaults() {
911
        let s = Spinner::create();
912

            
913
        assert_eq!(s.size, DEFAULT_SIZE);
914
        assert_eq!(s.size, 24, "the documented default diameter changed");
915
        assert_eq!(
916
            s.color,
917
            ColorU {
918
                r: 13,
919
                g: 110,
920
                b: 253,
921
                a: 255
922
            }
923
        );
924
        assert_eq!(
925
            s.track_color,
926
            ColorU {
927
                r: 208,
928
                g: 212,
929
                b: 217,
930
                a: 255
931
            }
932
        );
933
        assert_eq!(
934
            s.resolved_spinner_style(),
935
            build_spinner_style(DEFAULT_SIZE, DEFAULT_ACCENT_COLOR, DEFAULT_TRACK_COLOR),
936
        );
937
        // 24px → 3px border, 12px radius.
938
        assert_eq!(
939
            raw(border_widths(&s.resolved_spinner_style())[0]),
940
            3 * FP_SCALE
941
        );
942
        assert_eq!(raw(radii(&s.resolved_spinner_style())[0]), 12 * FP_SCALE);
943
    }
944

            
945
    #[test]
946
    fn default_is_create() {
947
        assert_eq!(Spinner::default(), Spinner::create());
948
    }
949

            
950
    #[test]
951
    fn with_size_records_the_size_and_rebuilds_the_style() {
952
        for size in SAFE_SIZES {
953
            let s = Spinner::with_size(size);
954

            
955
            assert_eq!(s.size, size, "the size field does not match the argument");
956
            assert_eq!(s.color, DEFAULT_ACCENT_COLOR);
957
            assert_eq!(s.track_color, DEFAULT_TRACK_COLOR);
958
            assert_eq!(s.resolved_spinner_style().len(), DECLARATIONS);
959
            assert_eq!(
960
                s.resolved_spinner_style(),
961
                build_spinner_style(size, DEFAULT_ACCENT_COLOR, DEFAULT_TRACK_COLOR),
962
            );
963
            assert_eq!(raw(width(&s.resolved_spinner_style())) / FP_SCALE, size);
964
        }
965
    }
966

            
967
    // ==================================================================
968
    // set_size / set_color / set_track_color — no cross-clobbering
969
    // ==================================================================
970

            
971
    #[test]
972
    fn set_size_keeps_the_custom_colours() {
973
        // `set_size` rebuilds the whole style, so it has to feed the *current*
974
        // colours back in — a regression here silently resets the palette.
975
        let mut s = Spinner::create().with_color(RED).with_track_color(GREEN);
976
        s.set_size(64);
977

            
978
        assert_eq!(s.size, 64);
979
        assert_eq!(s.color, RED);
980
        assert_eq!(s.track_color, GREEN);
981
        assert_eq!(
982
            border_colors(&s.resolved_spinner_style()),
983
            [RED, GREEN, GREEN, GREEN]
984
        );
985
        assert_eq!(raw(width(&s.resolved_spinner_style())), 64 * FP_SCALE);
986
    }
987

            
988
    #[test]
989
    fn set_color_touches_only_the_accent() {
990
        let mut s = Spinner::with_size(48).with_track_color(GREEN);
991
        s.set_color(RED);
992

            
993
        assert_eq!(s.size, 48, "set_color moved the diameter");
994
        assert_eq!(s.track_color, GREEN, "set_color clobbered the track colour");
995
        assert_eq!(
996
            border_colors(&s.resolved_spinner_style()),
997
            [RED, GREEN, GREEN, GREEN]
998
        );
999
        assert_eq!(raw(width(&s.resolved_spinner_style())), 48 * FP_SCALE);
    }
    #[test]
    fn set_track_color_touches_only_the_track() {
        let mut s = Spinner::with_size(48).with_color(RED);
        s.set_track_color(GREEN);
        assert_eq!(s.size, 48, "set_track_color moved the diameter");
        assert_eq!(s.color, RED, "set_track_color clobbered the accent colour");
        assert_eq!(
            border_colors(&s.resolved_spinner_style()),
            [RED, GREEN, GREEN, GREEN]
        );
    }
    #[test]
    fn setters_are_idempotent_and_never_grow_the_style() {
        // The style is *replaced*, not appended to: a hundred rounds of setters
        // must leave exactly the same 20 declarations as one round.
        let mut s = Spinner::create();
        for _ in 0..100 {
            s.set_size(24);
            s.set_color(RED);
            s.set_track_color(GREEN);
        }
        let once = Spinner::with_size(24)
            .with_color(RED)
            .with_track_color(GREEN);
        assert_eq!(
            s.resolved_spinner_style().len(),
            DECLARATIONS,
            "the style vec grew"
        );
        assert_eq!(
            s, once,
            "repeated setters diverged from a single application"
        );
    }
    #[test]
    fn set_size_survives_every_encodable_diameter() {
        // The same spinner walked across the whole safe range: each step must
        // leave a fully-formed style, with no state left over from the previous.
        let mut s = Spinner::create().with_color(RED).with_track_color(GREEN);
        for size in SAFE_SIZES {
            s.set_size(size);
            assert_eq!(s.size, size);
            assert_eq!(s.resolved_spinner_style().len(), DECLARATIONS);
            assert_eq!(
                s,
                Spinner::with_size(size)
                    .with_color(RED)
                    .with_track_color(GREEN)
            );
        }
    }
    // ==================================================================
    // Builder setters mirror the mutating ones
    // ==================================================================
    #[test]
    fn builder_setters_match_the_mutating_setters() {
        for size in SAFE_SIZES {
            let mut mutated = Spinner::create();
            mutated.set_size(size);
            assert_eq!(
                Spinner::create().with_spinner_size(size),
                mutated,
                "size {size}"
            );
        }
        let mut mutated = Spinner::create();
        mutated.set_color(RED);
        assert_eq!(Spinner::create().with_color(RED), mutated);
        let mut mutated = Spinner::create();
        mutated.set_track_color(GHOST);
        assert_eq!(Spinner::create().with_track_color(GHOST), mutated);
    }
    #[test]
    fn the_builder_chain_is_order_independent() {
        // Each setter rebuilds from all three fields, so the final spinner must
        // not depend on the order the fields were set in.
        let a = Spinner::create()
            .with_spinner_size(40)
            .with_color(RED)
            .with_track_color(GREEN);
        let b = Spinner::create()
            .with_track_color(GREEN)
            .with_color(RED)
            .with_spinner_size(40);
        let c = Spinner::create()
            .with_color(RED)
            .with_spinner_size(40)
            .with_track_color(GREEN);
        assert_eq!(a, b, "setting the size last changed the result");
        assert_eq!(a, c, "interleaving the setters changed the result");
    }
    #[test]
    fn equality_distinguishes_every_field() {
        let base = Spinner::create();
        assert_ne!(base, Spinner::create().with_spinner_size(25));
        assert_ne!(base, Spinner::create().with_color(RED));
        assert_ne!(base, Spinner::create().with_track_color(RED));
        assert_eq!(base, Spinner::create().with_spinner_size(DEFAULT_SIZE));
    }
    // ==================================================================
    // swap_with_default
    // ==================================================================
    #[test]
    fn swap_with_default_returns_the_original_and_installs_a_default() {
        let mut s = Spinner::with_size(96)
            .with_color(RED)
            .with_track_color(GREEN);
        let expected = s.clone();
        let taken = s.swap_with_default();
        assert_eq!(taken, expected, "the returned spinner is not the original");
        assert_eq!(s, Spinner::create(), "the receiver is not a fresh default");
        // The returned value must own a live style, not a moved-out husk.
        assert_eq!(taken.resolved_spinner_style().len(), DECLARATIONS);
        assert_eq!(
            border_colors(&taken.resolved_spinner_style()),
            [RED, GREEN, GREEN, GREEN]
        );
    }
    #[test]
    fn swapping_twice_leaves_a_default_both_times() {
        let mut s = Spinner::with_size(MAX_ENCODABLE_SIZE);
        let first = s.swap_with_default();
        let second = s.swap_with_default();
        assert_eq!(first.size, MAX_ENCODABLE_SIZE);
        assert_eq!(
            second,
            Spinner::create(),
            "the second swap did not return the default"
        );
        assert_eq!(s, Spinner::create());
    }
    #[test]
    fn swap_on_a_default_is_observationally_a_no_op() {
        let mut s = Spinner::create();
        let taken = s.swap_with_default();
        assert_eq!(taken, Spinner::create());
        assert_eq!(s, Spinner::create());
    }
    // ==================================================================
    // Clone / ownership — the style vec is heap memory behind a C ABI
    // ==================================================================
    #[test]
    fn clone_deep_copies_the_style_buffer() {
        // `CssPropertyWithConditionsVec` is a raw-pointer FFI vec: a shallow clone
        // would alias one allocation into two owners and double-free it.
        // Only a STORED style owns a buffer — a resolved one is built fresh per
        // call and has nothing to alias — so this asks with an explicit style.
        let mut original = Spinner::with_size(32).with_color(RED);
        original.spinner_style =
            OptionCssPropertyWithConditionsVec::Some(build_spinner_style(32, RED, GREEN));
        let copy = original.clone();
        assert_eq!(copy, original);
        let buffer = |s: &Spinner| {
            s.spinner_style
                .as_ref()
                .expect("the fixture stores a style")
                .as_ptr()
        };
        assert_ne!(
            buffer(&original),
            buffer(&copy),
            "the clone shares the original's style buffer",
        );
    }
    #[test]
    fn mutating_a_clone_leaves_the_original_alone() {
        let original = Spinner::with_size(32).with_color(RED);
        let mut copy = original.clone();
        copy.set_size(8);
        copy.set_track_color(GHOST);
        assert_eq!(
            original.size, 32,
            "mutating the clone moved the original's size"
        );
        assert_eq!(original.track_color, DEFAULT_TRACK_COLOR);
        assert_eq!(
            raw(width(&original.resolved_spinner_style())),
            32 * FP_SCALE
        );
        assert_eq!(border_colors(&original.resolved_spinner_style())[0], RED);
    }
    // ==================================================================
    // dom()
    // ==================================================================
    #[test]
    fn dom_is_a_single_classed_div() {
        let dom = Spinner::create().dom();
        assert_eq!(*dom.root.get_node_type(), NodeType::Div);
        assert!(
            dom.children.as_ref().is_empty(),
            "the spinner must be a leaf node"
        );
        assert_eq!(dom.estimated_total_children, 0);
        assert_eq!(dom_classes(&dom), vec!["__azul-native-spinner".to_string()]);
    }
    #[test]
    fn dom_carries_exactly_the_spinner_style() {
        // `with_css_props` turns the vec into one inline rule per declaration;
        // nothing may be dropped, reordered or made conditional on the way.
        for size in SAFE_SIZES {
            let s = Spinner::with_size(size)
                .with_color(RED)
                .with_track_color(GREEN);
            let expected = props(&s.resolved_spinner_style());
            let dom = s.dom();
            assert_eq!(
                dom_props(&dom),
                expected,
                "the DOM lost declarations for size {size}"
            );
            assert!(
                dom.root
                    .style
                    .iter_inline_properties()
                    .all(|(_, c)| c.is_empty()),
                "size {size}: an inline declaration became conditional",
            );
        }
    }
    #[test]
    fn from_impl_matches_the_dom_method() {
        let s = Spinner::with_size(17).with_color(GHOST);
        assert_eq!(Dom::from(s.clone()), s.dom());
    }
    #[test]
    fn dom_is_deterministic_for_equal_inputs() {
        let a = Spinner::with_size(13)
            .with_color(RED)
            .with_track_color(GHOST)
            .dom();
        let b = Spinner::with_size(13)
            .with_color(RED)
            .with_track_color(GHOST)
            .dom();
        assert_eq!(a, b, "two identically-built spinners rendered differently");
    }
    #[test]
    fn dom_survives_every_encodable_size_and_colour() {
        for size in SAFE_SIZES {
            for (color, track) in [(RED, GREEN), (GHOST, GHOST)] {
                let dom = Spinner::with_size(size)
                    .with_color(color)
                    .with_track_color(track)
                    .dom();
                assert_eq!(
                    dom_props(&dom).len(),
                    DECLARATIONS,
                    "shape changed for {size}"
                );
                assert!(dom.children.as_ref().is_empty());
                assert_eq!(dom_classes(&dom).len(), 1);
            }
        }
    }
}