1
//! Divider (separator) widget — a thin rule line. A stateless single styled
2
//! node with no callback, a near-clone of [`crate::widgets::label::Label`].
3
//! Supports a horizontal (default) or vertical orientation.
4
//!
5
//! Key types: [`Divider`], [`DividerOrientation`].
6

            
7
use azul_core::dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec};
8
use azul_css::{
9
    dynamic_selector::{
10
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
11
    },
12
    props::{
13
        basic::ColorU,
14
        layout::{
15
            LayoutAlignSelf, LayoutDisplay, LayoutFlexGrow, LayoutHeight, LayoutMarginBottom,
16
            LayoutMarginLeft, LayoutMarginRight, LayoutMarginTop, LayoutWidth,
17
        },
18
        property::{CssProperty, *},
19
        style::{StyleBackgroundContent, StyleBackgroundContentVec},
20
    },
21
    AzString,
22
};
23

            
24
/// Orientation of a [`Divider`].
25
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
26
#[repr(C)]
27
pub enum DividerOrientation {
28
    /// A full-width horizontal rule (1px tall) — the default.
29
    #[default]
30
    Horizontal,
31
    /// A full-height vertical rule (1px wide).
32
    Vertical,
33
}
34

            
35
/// A thin separator rule. Stateless; renders a single styled `div`.
36
#[derive(Debug, Clone, PartialEq, Eq)]
37
#[repr(C)]
38
pub struct Divider {
39
    pub orientation: DividerOrientation,
40
    /// The rule's CSS, or `None` for "no opinion" — in which case the style is
41
    /// derived from `orientation` at render time.
42
    ///
43
    /// `None` and `Some(empty)` are different answers: the first means the
44
    /// widget picks, the second means the caller asked for no properties at all
45
    /// and gets none.
46
    pub divider_style: OptionCssPropertyWithConditionsVec,
47
}
48

            
49
/// Default rule colour (#dddddd), matching the frame widget's border colour.
50
const DIVIDER_COLOR: ColorU = ColorU {
51
    r: 221,
52
    g: 221,
53
    b: 221,
54
    a: 255,
55
};
56
const DIVIDER_BG_ITEMS: &[StyleBackgroundContent] = &[StyleBackgroundContent::Color(DIVIDER_COLOR)];
57
const DIVIDER_BG: StyleBackgroundContentVec =
58
    StyleBackgroundContentVec::from_const_slice(DIVIDER_BG_ITEMS);
59

            
60
static DIVIDER_STYLE_HORIZONTAL: &[CssPropertyWithConditions] = &[
61
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
62
    CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(1))),
63
    // Stretch across the parent's cross axis so the rule spans the full width.
64
    CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Stretch)),
65
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
66
    CssPropertyWithConditions::simple(CssProperty::const_margin_top(LayoutMarginTop::const_px(4))),
67
    CssPropertyWithConditions::simple(CssProperty::const_margin_bottom(
68
        LayoutMarginBottom::const_px(4),
69
    )),
70
    CssPropertyWithConditions::simple(CssProperty::const_background_content(DIVIDER_BG)),
71
];
72

            
73
static DIVIDER_STYLE_VERTICAL: &[CssPropertyWithConditions] = &[
74
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
75
    CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(1))),
76
    // Stretch across the parent's cross axis so the rule spans the full height.
77
    CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Stretch)),
78
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
79
    CssPropertyWithConditions::simple(CssProperty::const_margin_left(LayoutMarginLeft::const_px(
80
        4,
81
    ))),
82
    CssPropertyWithConditions::simple(CssProperty::const_margin_right(
83
        LayoutMarginRight::const_px(4),
84
    )),
85
    CssPropertyWithConditions::simple(CssProperty::const_background_content(DIVIDER_BG)),
86
];
87

            
88
impl Divider {
89
    /// Creates a new horizontal divider with default styling.
90
    #[inline]
91
    #[must_use]
92
834
    pub const fn create() -> Self {
93
834
        Self::create_with_orientation(DividerOrientation::Horizontal)
94
834
    }
95

            
96
    /// Creates a new divider with the given orientation and default styling.
97
    #[inline]
98
    #[must_use]
99
1079
    pub const fn create_with_orientation(orientation: DividerOrientation) -> Self {
100
1079
        Self {
101
1079
            orientation,
102
1079
            divider_style: OptionCssPropertyWithConditionsVec::None,
103
1079
        }
104
1079
    }
105

            
106
    /// The rule CSS this divider renders with.
107
    ///
108
    /// `None` means no opinion, so the orientation decides — the same answer
109
    /// both themes give, asked in one place so they cannot drift. It is also why
110
    /// `set_orientation` is a plain field write: there is no cached vec left
111
    /// that could still describe the other axis.
112
    #[must_use]
113
3775
    pub fn resolved_divider_style(&self) -> CssPropertyWithConditionsVec {
114
3775
        self.divider_style
115
3775
            .clone()
116
3775
            .into_option()
117
3775
            .unwrap_or_else(|| match self.orientation {
118
                DividerOrientation::Horizontal => {
119
2186
                    CssPropertyWithConditionsVec::from_const_slice(DIVIDER_STYLE_HORIZONTAL)
120
                }
121
                DividerOrientation::Vertical => {
122
1581
                    CssPropertyWithConditionsVec::from_const_slice(DIVIDER_STYLE_VERTICAL)
123
                }
124
3767
            })
125
3775
    }
126

            
127
    /// Sets the orientation.
128
    ///
129
    /// Does not touch `divider_style`: the axis-dependent geometry is resolved
130
    /// from `orientation` when the DOM is built. Writing it here would also
131
    /// overwrite a caller's explicit style, which it used to do.
132
    #[inline]
133
718
    pub const fn set_orientation(&mut self, orientation: DividerOrientation) {
134
718
        self.orientation = orientation;
135
718
    }
136

            
137
    /// Builder-style setter for the orientation.
138
    #[inline]
139
    #[must_use]
140
505
    pub const fn with_orientation(mut self, orientation: DividerOrientation) -> Self {
141
505
        self.set_orientation(orientation);
142
505
        self
143
505
    }
144

            
145
    /// Replaces `self` with a default horizontal divider and returns the original.
146
    #[inline]
147
    #[must_use]
148
104
    pub const fn swap_with_default(&mut self) -> Self {
149
104
        let mut s = Self::create();
150
104
        core::mem::swap(&mut s, self);
151
104
        s
152
104
    }
153

            
154
    /// Converts this divider into a DOM node with the `__azul-native-divider` class.
155
    #[inline]
156
    #[must_use]
157
520
    pub fn dom(self) -> Dom {
158
        static DIVIDER_CLASS: &[IdOrClass] =
159
            &[Class(AzString::from_const_str("__azul-native-divider"))];
160

            
161
520
        Dom::create_div()
162
520
            .with_ids_and_classes(IdOrClassVec::from_const_slice(DIVIDER_CLASS))
163
520
            .with_css_props(self.resolved_divider_style())
164
520
    }
165
}
166

            
167
impl Default for Divider {
168
206
    fn default() -> Self {
169
206
        Self::create()
170
206
    }
171
}
172

            
173
impl From<Divider> for Dom {
174
2
    fn from(d: Divider) -> Self {
175
2
        d.dom()
176
2
    }
177
}
178

            
179
#[cfg(test)]
180
mod autotest_generated {
181
    use std::collections::HashSet;
182

            
183
    use azul_core::dom::NodeType;
184
    use azul_css::props::basic::{length::SizeMetric, pixel::PixelValue};
185

            
186
    use super::*;
187

            
188
    // ------------------------------------------------------------------
189
    // Helpers
190
    // ------------------------------------------------------------------
191

            
192
    /// Every variant of `DividerOrientation` — the complete input domain of
193
    /// `create_with_orientation`, `set_orientation` and `with_orientation`.
194
    const ALL_ORIENTATIONS: [DividerOrientation; 2] =
195
        [DividerOrientation::Horizontal, DividerOrientation::Vertical];
196

            
197
    /// The number of declarations each built-in style is expected to carry.
198
    const DECL_COUNT: usize = 7;
199

            
200
    /// The declared properties of a style vec, in declaration order.
201
    fn properties(v: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
202
        v.as_ref().iter().map(|p| p.property.clone()).collect()
203
    }
204

            
205
    /// The `f32` of a `PixelValue`, asserting it is an absolute `px` length. A
206
    /// rule declared in `em`/`%` would resolve against the parent font/box and
207
    /// either vanish or blow up instead of staying a hairline.
208
    fn px(pv: &PixelValue) -> f32 {
209
        assert_eq!(
210
            pv.metric,
211
            SizeMetric::Px,
212
            "divider lengths must be absolute px, got {:?}",
213
            pv.metric
214
        );
215
        pv.number.get()
216
    }
217

            
218
    fn height_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
219
        v.as_ref().iter().find_map(|p| match &p.property {
220
            CssProperty::Height(h) => match h.get_property() {
221
                Some(LayoutHeight::Px(pv)) => Some(px(pv)),
222
                Some(other) => panic!("divider height must be a px length, got {other:?}"),
223
                None => None,
224
            },
225
            _ => None,
226
        })
227
    }
228

            
229
    fn width_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
230
        v.as_ref().iter().find_map(|p| match &p.property {
231
            CssProperty::Width(w) => match w.get_property() {
232
                Some(LayoutWidth::Px(pv)) => Some(px(pv)),
233
                Some(other) => panic!("divider width must be a px length, got {other:?}"),
234
                None => None,
235
            },
236
            _ => None,
237
        })
238
    }
239

            
240
    /// The four margins in `(top, bottom, left, right)` order.
241
    fn margins_px(
242
        v: &CssPropertyWithConditionsVec,
243
    ) -> (Option<f32>, Option<f32>, Option<f32>, Option<f32>) {
244
        let find = |f: &dyn Fn(&CssProperty) -> Option<f32>| {
245
            v.as_ref().iter().find_map(|p| f(&p.property))
246
        };
247
        (
248
            find(&|p| match p {
249
                CssProperty::MarginTop(x) => x.get_property().map(|x| px(&x.inner)),
250
                _ => None,
251
            }),
252
            find(&|p| match p {
253
                CssProperty::MarginBottom(x) => x.get_property().map(|x| px(&x.inner)),
254
                _ => None,
255
            }),
256
            find(&|p| match p {
257
                CssProperty::MarginLeft(x) => x.get_property().map(|x| px(&x.inner)),
258
                _ => None,
259
            }),
260
            find(&|p| match p {
261
                CssProperty::MarginRight(x) => x.get_property().map(|x| px(&x.inner)),
262
                _ => None,
263
            }),
264
        )
265
    }
266

            
267
    fn flex_grow(v: &CssPropertyWithConditionsVec) -> Option<f32> {
268
        v.as_ref().iter().find_map(|p| match &p.property {
269
            CssProperty::FlexGrow(f) => f.get_property().map(|f| f.inner.get()),
270
            _ => None,
271
        })
272
    }
273

            
274
    /// The single background layer of a style vec, asserting there is exactly one
275
    /// and that it is a flat colour (a gradient would not be a `Color`).
276
    fn background_color(v: &CssPropertyWithConditionsVec) -> Option<ColorU> {
277
        let bg = v.as_ref().iter().find_map(|p| match &p.property {
278
            CssProperty::BackgroundContent(b) => b.get_property(),
279
            _ => None,
280
        })?;
281
        assert_eq!(
282
            bg.as_ref().len(),
283
            1,
284
            "a divider must declare exactly one background layer"
285
        );
286
        match &bg.as_ref()[0] {
287
            StyleBackgroundContent::Color(c) => Some(*c),
288
            other => panic!("divider background is not a flat colour: {other:?}"),
289
        }
290
    }
291

            
292
    /// Every `PixelValue` a style vec mentions (thickness + margins).
293
    fn all_pixel_values(v: &CssPropertyWithConditionsVec) -> Vec<PixelValue> {
294
        v.as_ref()
295
            .iter()
296
            .filter_map(|p| match &p.property {
297
                CssProperty::Height(h) => match h.get_property() {
298
                    Some(LayoutHeight::Px(pv)) => Some(*pv),
299
                    _ => None,
300
                },
301
                CssProperty::Width(w) => match w.get_property() {
302
                    Some(LayoutWidth::Px(pv)) => Some(*pv),
303
                    _ => None,
304
                },
305
                CssProperty::MarginTop(x) => x.get_property().map(|x| x.inner),
306
                CssProperty::MarginBottom(x) => x.get_property().map(|x| x.inner),
307
                CssProperty::MarginLeft(x) => x.get_property().map(|x| x.inner),
308
                CssProperty::MarginRight(x) => x.get_property().map(|x| x.inner),
309
                _ => None,
310
            })
311
            .collect()
312
    }
313

            
314
    /// True if `node` carries the CSS class `name`.
315
    fn has_class(node: &Dom, name: &str) -> bool {
316
        node.root
317
            .get_ids_and_classes()
318
            .as_ref()
319
            .iter()
320
            .any(|c| matches!(c, Class(s) if s.as_str() == name))
321
    }
322

            
323
    /// The properties of a rendered node's *inline* style, in declaration order.
324
    fn inline_properties(node: &Dom) -> Vec<CssProperty> {
325
        node.root
326
            .style
327
            .iter_inline_properties()
328
            .map(|(p, _)| p.clone())
329
            .collect()
330
    }
331

            
332
    /// `(property, number-of-conditions)` for a rendered node, in declaration order.
333
    fn inline_properties_with_condition_counts(node: &Dom) -> Vec<(CssProperty, usize)> {
334
        node.root
335
            .style
336
            .iter_inline_properties()
337
            .map(|(p, c)| (p.clone(), c.as_ref().len()))
338
            .collect()
339
    }
340

            
341
    // ------------------------------------------------------------------
342
    // DividerOrientation
343
    // ------------------------------------------------------------------
344

            
345
    #[test]
346
    fn orientation_default_is_horizontal_and_the_two_variants_are_distinct() {
347
        assert_eq!(
348
            DividerOrientation::default(),
349
            DividerOrientation::Horizontal
350
        );
351
        assert_ne!(DividerOrientation::Horizontal, DividerOrientation::Vertical);
352
        // `Copy` must not alias into something else: a copy compares equal to the
353
        // original and to itself.
354
        for o in ALL_ORIENTATIONS {
355
            let copy = o;
356
            assert_eq!(o, copy, "{o:?}: a copy diverged from the original");
357
        }
358
        assert_eq!(
359
            ALL_ORIENTATIONS.len(),
360
            2,
361
            "a new orientation was added without updating these tests"
362
        );
363
    }
364

            
365
    // ------------------------------------------------------------------
366
    // Divider::create / Divider::create_with_orientation  (constructors)
367
    // ------------------------------------------------------------------
368

            
369
    #[test]
370
    fn create_is_the_horizontal_constructor_and_the_default() {
371
        let created = Divider::create();
372
        assert_eq!(created.orientation, DividerOrientation::Horizontal);
373
        assert_eq!(
374
            created,
375
            Divider::create_with_orientation(DividerOrientation::Horizontal)
376
        );
377
        assert_eq!(created, Divider::default());
378
        // `Clone` must preserve equality — the style vec is backed by a `'static`
379
        // slice, so a shallow/deep clone mix-up would show up here first.
380
        assert_eq!(created.clone(), created);
381
    }
382

            
383
    #[test]
384
    fn create_with_orientation_stores_exactly_the_orientation_it_was_given() {
385
        for o in ALL_ORIENTATIONS {
386
            let d = Divider::create_with_orientation(o);
387
            assert_eq!(
388
                d.orientation, o,
389
                "{o:?}: the orientation field does not match the argument"
390
            );
391
            // Two builds of the same orientation must be indistinguishable.
392
            assert_eq!(
393
                d,
394
                Divider::create_with_orientation(o),
395
                "{o:?}: construction is not deterministic"
396
            );
397
        }
398
    }
399

            
400
    #[test]
401
    fn constructed_style_vecs_have_consistent_length_and_capacity() {
402
        for o in ALL_ORIENTATIONS {
403
            let d = Divider::create_with_orientation(o);
404
            let v = &d.resolved_divider_style();
405
            assert_eq!(
406
                v.len(),
407
                v.as_ref().len(),
408
                "{o:?}: len() disagrees with the slice view"
409
            );
410
            assert!(
411
                v.capacity() >= v.len(),
412
                "{o:?}: capacity {} < len {}",
413
                v.capacity(),
414
                v.len()
415
            );
416
            assert!(
417
                !v.is_empty(),
418
                "{o:?}: a divider with no declarations paints nothing"
419
            );
420
            assert_eq!(
421
                v.len(),
422
                DECL_COUNT,
423
                "{o:?}: unexpected number of declarations"
424
            );
425
        }
426
    }
427

            
428
    // ------------------------------------------------------------------
429
    // The two built-in styles
430
    // ------------------------------------------------------------------
431

            
432
    #[test]
433
    fn horizontal_style_is_a_one_pixel_tall_rule_with_vertical_breathing_room() {
434
        let style = Divider::create().resolved_divider_style();
435

            
436
        assert_eq!(
437
            height_px(&style),
438
            Some(1.0),
439
            "a horizontal rule must be exactly 1px tall"
440
        );
441
        // A declared width would pin the rule to a fixed size and defeat the
442
        // `align-self: stretch` that is supposed to span the parent.
443
        assert_eq!(
444
            width_px(&style),
445
            None,
446
            "a horizontal rule must not declare a width"
447
        );
448
        assert_eq!(
449
            margins_px(&style),
450
            (Some(4.0), Some(4.0), None, None),
451
            "a horizontal rule takes 4px above/below and nothing on the sides"
452
        );
453
    }
454

            
455
    #[test]
456
    fn vertical_style_is_a_one_pixel_wide_rule_with_horizontal_breathing_room() {
457
        let style =
458
            Divider::create_with_orientation(DividerOrientation::Vertical).resolved_divider_style();
459

            
460
        assert_eq!(
461
            width_px(&style),
462
            Some(1.0),
463
            "a vertical rule must be exactly 1px wide"
464
        );
465
        // The copy-paste hazard this widget is most exposed to: a `height: 1px`
466
        // left over from the horizontal style would collapse the vertical rule
467
        // into a 1x1 dot.
468
        assert_eq!(
469
            height_px(&style),
470
            None,
471
            "a vertical rule must not declare a height"
472
        );
473
        assert_eq!(
474
            margins_px(&style),
475
            (None, None, Some(4.0), Some(4.0)),
476
            "a vertical rule takes 4px left/right and nothing above/below"
477
        );
478
    }
479

            
480
    #[test]
481
    fn both_orientations_share_the_colour_and_the_box_model_flags() {
482
        for o in ALL_ORIENTATIONS {
483
            let style = Divider::create_with_orientation(o).resolved_divider_style();
484
            let props = properties(&style);
485
            let has = |p: &CssProperty| props.contains(p);
486

            
487
            assert!(
488
                has(&CssProperty::const_display(LayoutDisplay::Block)),
489
                "{o:?}: not a block box"
490
            );
491
            // Both halves of the "span the parent" contract: stretch on the cross
492
            // axis, no growth on the main axis.
493
            assert!(
494
                has(&CssProperty::align_self(LayoutAlignSelf::Stretch)),
495
                "{o:?}: rule does not stretch"
496
            );
497
            assert!(
498
                has(&CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
499
                "{o:?}: rule grows on the main axis and would eat sibling space"
500
            );
501
            assert_eq!(
502
                background_color(&style),
503
                Some(DIVIDER_COLOR),
504
                "{o:?}: wrong rule colour"
505
            );
506
        }
507
    }
508

            
509
    #[test]
510
    fn the_rule_colour_is_the_documented_opaque_grey() {
511
        // A translucent or non-grey rule is a visible regression, and the doc
512
        // comment pins it to #dddddd.
513
        assert_eq!(
514
            DIVIDER_COLOR,
515
            ColorU {
516
                r: 221,
517
                g: 221,
518
                b: 221,
519
                a: 255
520
            }
521
        );
522
        assert_eq!(
523
            DIVIDER_COLOR.a, 255,
524
            "a translucent rule lets the background bleed through"
525
        );
526
        assert_eq!(
527
            DIVIDER_COLOR.r, DIVIDER_COLOR.g,
528
            "the rule colour is not neutral grey"
529
        );
530
        assert_eq!(
531
            DIVIDER_COLOR.g, DIVIDER_COLOR.b,
532
            "the rule colour is not neutral grey"
533
        );
534
        assert_eq!(
535
            DIVIDER_BG_ITEMS.len(),
536
            1,
537
            "the rule must be a single flat layer"
538
        );
539
    }
540

            
541
    #[test]
542
    fn orientation_actually_changes_the_emitted_style() {
543
        // If the two static tables were ever wired to the same slice the
544
        // `orientation` argument would silently become a no-op.
545
        let h = Divider::create_with_orientation(DividerOrientation::Horizontal)
546
            .resolved_divider_style();
547
        let v =
548
            Divider::create_with_orientation(DividerOrientation::Vertical).resolved_divider_style();
549
        assert_ne!(
550
            properties(&h),
551
            properties(&v),
552
            "both orientations produce an identical style"
553
        );
554
        assert_eq!(
555
            h.len(),
556
            v.len(),
557
            "the two orientations declare a different number of properties"
558
        );
559

            
560
        // The axis-defining declarations must be mirror images of each other.
561
        assert!(height_px(&h).is_some() && width_px(&h).is_none());
562
        assert!(width_px(&v).is_some() && height_px(&v).is_none());
563
        assert_eq!(
564
            height_px(&h),
565
            width_px(&v),
566
            "the two rules are not the same thickness"
567
        );
568
    }
569

            
570
    #[test]
571
    fn every_declaration_is_unconditional() {
572
        // A divider is stateless — a declaration gated on `:hover`/`:active`
573
        // would simply never paint.
574
        for o in ALL_ORIENTATIONS {
575
            for p in Divider::create_with_orientation(o)
576
                .resolved_divider_style()
577
                .as_ref()
578
            {
579
                assert!(
580
                    p.apply_if.as_ref().is_empty(),
581
                    "{o:?}: {:?} is conditional on a stateless widget",
582
                    p.property
583
                );
584
            }
585
        }
586
    }
587

            
588
    #[test]
589
    fn no_property_is_declared_twice() {
590
        // A duplicated declaration is a last-one-wins ambiguity: two heights or
591
        // two backgrounds would make one of them silently dead.
592
        for o in ALL_ORIENTATIONS {
593
            let props = properties(&Divider::create_with_orientation(o).resolved_divider_style());
594
            let mut seen = HashSet::new();
595
            for p in &props {
596
                assert!(
597
                    seen.insert(core::mem::discriminant(p)),
598
                    "{o:?}: duplicate declaration of {p:?}"
599
                );
600
            }
601
            assert_eq!(seen.len(), props.len());
602
        }
603
    }
604

            
605
    #[test]
606
    fn every_length_is_a_finite_non_negative_absolute_px() {
607
        // Guard the `isize` -> `PixelValue` conversions: a NaN/inf/negative
608
        // length must never reach the layout solver.
609
        for o in ALL_ORIENTATIONS {
610
            let values =
611
                all_pixel_values(&Divider::create_with_orientation(o).resolved_divider_style());
612
            assert_eq!(
613
                values.len(),
614
                3,
615
                "{o:?}: expected one thickness + two margins"
616
            );
617
            for pv in values {
618
                let n = px(&pv); // also asserts SizeMetric::Px
619
                assert!(n.is_finite(), "{o:?}: non-finite length {n}");
620
                assert!(!n.is_nan(), "{o:?}: NaN length");
621
                assert!(n >= 0.0, "{o:?}: negative length {n}");
622
                assert!(
623
                    n <= 64.0,
624
                    "{o:?}: implausibly large length {n} for a hairline rule"
625
                );
626
            }
627
        }
628
    }
629

            
630
    #[test]
631
    fn the_rule_is_thick_enough_to_be_visible_and_thin_enough_to_be_a_rule() {
632
        for o in ALL_ORIENTATIONS {
633
            let style = Divider::create_with_orientation(o).resolved_divider_style();
634
            let thickness = height_px(&style)
635
                .or_else(|| width_px(&style))
636
                .expect("a divider must declare a thickness on one axis");
637
            assert!(thickness > 0.0, "{o:?}: a 0px rule is invisible");
638
            assert!(
639
                thickness <= 4.0,
640
                "{o:?}: {thickness}px is a bar, not a rule"
641
            );
642
        }
643
    }
644

            
645
    #[test]
646
    fn flex_grow_is_exactly_zero_and_not_a_rounding_artefact() {
647
        // `FloatValue` stores a fixed-point `isize`; a botched encode/decode
648
        // would show up as 0.001 or -0.0 rather than a clean 0.
649
        for o in ALL_ORIENTATIONS {
650
            let g = flex_grow(&Divider::create_with_orientation(o).resolved_divider_style())
651
                .expect("flex-grow must be declared");
652
            assert!(g.is_finite(), "{o:?}: non-finite flex-grow {g}");
653
            assert_eq!(g, 0.0, "{o:?}: flex-grow is {g}, not 0");
654
            assert!(g.is_sign_positive(), "{o:?}: flex-grow decoded as -0.0");
655
        }
656
    }
657

            
658
    #[test]
659
    fn the_fixed_point_length_encoding_round_trips() {
660
        // encode == decode for every constant this file bakes in.
661
        assert_eq!(PixelValue::const_px(1).number.get(), 1.0);
662
        assert_eq!(PixelValue::const_px(4).number.get(), 4.0);
663
        assert_eq!(LayoutFlexGrow::const_new(0).inner.get(), 0.0);
664

            
665
        // ...and the values that actually landed in the built styles are the
666
        // ones the constructors asked for.
667
        let h = properties(&Divider::create().resolved_divider_style());
668
        assert!(h.contains(&CssProperty::const_height(LayoutHeight::const_px(1))));
669
        assert!(h.contains(&CssProperty::const_margin_top(LayoutMarginTop::const_px(4))));
670
        assert!(h.contains(&CssProperty::const_margin_bottom(
671
            LayoutMarginBottom::const_px(4)
672
        )));
673

            
674
        let v = properties(
675
            &Divider::create_with_orientation(DividerOrientation::Vertical)
676
                .resolved_divider_style(),
677
        );
678
        assert!(v.contains(&CssProperty::const_width(LayoutWidth::const_px(1))));
679
        assert!(
680
            v.contains(&CssProperty::const_margin_left(LayoutMarginLeft::const_px(
681
                4
682
            )))
683
        );
684
        assert!(v.contains(&CssProperty::const_margin_right(
685
            LayoutMarginRight::const_px(4)
686
        )));
687
    }
688

            
689
    #[test]
690
    fn cloning_and_dropping_never_corrupts_the_shared_static_style() {
691
        // The style vec borrows a `'static` slice (`NoDestructor`). A clone that
692
        // wrongly claims ownership, or a `Drop` that frees the static, would
693
        // corrupt every future divider — so churn hard and re-check the source.
694
        for o in ALL_ORIENTATIONS {
695
            let base = Divider::create_with_orientation(o);
696
            let expected = properties(&base.resolved_divider_style());
697
            for round in 0..1000 {
698
                let c = base.clone();
699
                assert_eq!(
700
                    properties(&c.resolved_divider_style()),
701
                    expected,
702
                    "{o:?}: clone {round} diverged"
703
                );
704
                drop(c);
705
            }
706
            assert_eq!(
707
                properties(&base.resolved_divider_style()),
708
                expected,
709
                "{o:?}: the original was damaged"
710
            );
711
            assert_eq!(
712
                properties(&Divider::create_with_orientation(o).resolved_divider_style()),
713
                expected,
714
                "{o:?}: a freshly built divider disagrees after 1000 clone/drop cycles"
715
            );
716
        }
717
    }
718

            
719
    // ------------------------------------------------------------------
720
    // Divider::set_orientation
721
    // ------------------------------------------------------------------
722

            
723
    #[test]
724
    fn set_orientation_replaces_the_style_and_never_grows_it() {
725
        // A push-instead-of-replace bug would grow the vec on every flip and
726
        // leave the previous axis's `height`/`width` behind, turning the rule
727
        // into a 1x1 dot.
728
        let mut d = Divider::create();
729
        for round in 0..200 {
730
            let o = ALL_ORIENTATIONS[round % ALL_ORIENTATIONS.len()];
731
            d.set_orientation(o);
732

            
733
            assert_eq!(
734
                d.orientation, o,
735
                "round {round}: orientation field not updated"
736
            );
737
            assert_eq!(
738
                d.resolved_divider_style().len(),
739
                DECL_COUNT,
740
                "round {round}: style vec changed length"
741
            );
742
            assert_eq!(
743
                d,
744
                Divider::create_with_orientation(o),
745
                "round {round}: not equal to a fresh build"
746
            );
747
            match o {
748
                DividerOrientation::Horizontal => {
749
                    assert_eq!(
750
                        width_px(&d.resolved_divider_style()),
751
                        None,
752
                        "round {round}: stale vertical width"
753
                    );
754
                    assert_eq!(
755
                        height_px(&d.resolved_divider_style()),
756
                        Some(1.0),
757
                        "round {round}"
758
                    );
759
                }
760
                DividerOrientation::Vertical => {
761
                    assert_eq!(
762
                        height_px(&d.resolved_divider_style()),
763
                        None,
764
                        "round {round}: stale horizontal height"
765
                    );
766
                    assert_eq!(
767
                        width_px(&d.resolved_divider_style()),
768
                        Some(1.0),
769
                        "round {round}"
770
                    );
771
                }
772
            }
773
        }
774
    }
775

            
776
    #[test]
777
    fn set_orientation_is_idempotent() {
778
        for o in ALL_ORIENTATIONS {
779
            let mut d = Divider::create_with_orientation(o);
780
            let before = d.clone();
781
            d.set_orientation(o);
782
            assert_eq!(
783
                d, before,
784
                "{o:?}: re-setting the same orientation changed the divider"
785
            );
786
            d.set_orientation(o);
787
            assert_eq!(d, before, "{o:?}: the second re-set changed the divider");
788
        }
789
    }
790

            
791
    #[test]
792
    fn set_orientation_discards_a_custom_style_as_documented() {
793
        // Documented behaviour: "resetting the style to the matching default".
794
        // A caller who styled the rule loses that styling even when the
795
        // orientation does not change — assert it so the contract is explicit.
796
        let custom =
797
            CssPropertyWithConditionsVec::from_vec(vec![CssPropertyWithConditions::simple(
798
                CssProperty::const_height(LayoutHeight::const_px(42)),
799
            )]);
800
        let mut d = Divider {
801
            orientation: DividerOrientation::Horizontal,
802
            divider_style: OptionCssPropertyWithConditionsVec::Some(custom),
803
        };
804
        d.set_orientation(DividerOrientation::Horizontal);
805
        assert_ne!(
806
            d,
807
            Divider::create(),
808
            "an explicit style must not be reset by set_orientation"
809
        );
810
        assert_eq!(
811
            height_px(&d.resolved_divider_style()),
812
            Some(42.0),
813
            "the 42px override was discarded"
814
        );
815
    }
816

            
817
    #[test]
818
    fn a_hand_built_divider_cannot_contradict_its_own_orientation() {
819
        // Both fields are `pub`, and the style used to be stored, so a caller
820
        // could build a divider whose `orientation` said Vertical while its
821
        // `divider_style` was the horizontal rule — and `set_orientation` had to
822
        // rebuild the vec to heal it. With no opinion stored there is nothing to
823
        // contradict: the resolver reads the orientation every time.
824
        let mut d = Divider {
825
            orientation: DividerOrientation::Vertical,
826
            divider_style: OptionCssPropertyWithConditionsVec::None,
827
        };
828
        assert_eq!(
829
            properties(&d.resolved_divider_style()),
830
            properties(
831
                &Divider::create_with_orientation(DividerOrientation::Vertical)
832
                    .resolved_divider_style()
833
            ),
834
        );
835
        assert_eq!(
836
            height_px(&d.resolved_divider_style()),
837
            None,
838
            "a vertical rule must not declare the horizontal height"
839
        );
840

            
841
        // An explicit style is the caller's answer and is honoured rather than
842
        // healed — that is what `Some` means.
843
        d.divider_style = OptionCssPropertyWithConditionsVec::Some(
844
            CssPropertyWithConditionsVec::from_const_slice(DIVIDER_STYLE_HORIZONTAL),
845
        );
846
        d.set_orientation(DividerOrientation::Vertical);
847
        assert_eq!(
848
            height_px(&d.resolved_divider_style()),
849
            Some(1.0),
850
            "an explicit horizontal style must survive set_orientation"
851
        );
852
    }
853

            
854
    // ------------------------------------------------------------------
855
    // Divider::with_orientation  (constructor / builder)
856
    // ------------------------------------------------------------------
857

            
858
    #[test]
859
    fn with_orientation_invariants_hold_for_every_orientation() {
860
        for o in ALL_ORIENTATIONS {
861
            let d = Divider::create().with_orientation(o);
862
            assert_eq!(d.orientation, o, "{o:?}: field does not match the argument");
863
            assert_eq!(
864
                d,
865
                Divider::create_with_orientation(o),
866
                "{o:?}: builder != constructor"
867
            );
868
            assert_eq!(
869
                d.resolved_divider_style().len(),
870
                d.resolved_divider_style().as_ref().len()
871
            );
872
            assert!(d.resolved_divider_style().capacity() >= d.resolved_divider_style().len());
873
            assert_eq!(d.resolved_divider_style().len(), DECL_COUNT);
874
        }
875
    }
876

            
877
    #[test]
878
    fn with_orientation_agrees_with_set_orientation_and_is_last_call_wins() {
879
        let chained = Divider::create()
880
            .with_orientation(DividerOrientation::Vertical)
881
            .with_orientation(DividerOrientation::Horizontal)
882
            .with_orientation(DividerOrientation::Vertical);
883

            
884
        let mut mutated = Divider::create();
885
        mutated.set_orientation(DividerOrientation::Vertical);
886
        mutated.set_orientation(DividerOrientation::Horizontal);
887
        mutated.set_orientation(DividerOrientation::Vertical);
888

            
889
        assert_eq!(chained, mutated, "the builder and the mutator must agree");
890
        assert_eq!(chained.orientation, DividerOrientation::Vertical);
891
        // In particular the intermediate horizontal `height` must be gone.
892
        assert_eq!(
893
            height_px(&chained.resolved_divider_style()),
894
            None,
895
            "a stale horizontal height survived the chain"
896
        );
897
        assert_eq!(width_px(&chained.resolved_divider_style()), Some(1.0));
898
    }
899

            
900
    #[test]
901
    fn a_long_builder_chain_does_not_accumulate_declarations() {
902
        let mut d = Divider::create();
903
        for round in 0..500 {
904
            d = d.with_orientation(ALL_ORIENTATIONS[round % ALL_ORIENTATIONS.len()]);
905
            assert_eq!(
906
                d.resolved_divider_style().len(),
907
                DECL_COUNT,
908
                "round {round}: the style vec grew"
909
            );
910
        }
911
        assert_eq!(
912
            d,
913
            Divider::create_with_orientation(DividerOrientation::Vertical)
914
        );
915
    }
916

            
917
    // ------------------------------------------------------------------
918
    // Divider::swap_with_default
919
    // ------------------------------------------------------------------
920

            
921
    #[test]
922
    fn swap_with_default_returns_the_original_and_leaves_a_horizontal_default() {
923
        let mut d = Divider::create_with_orientation(DividerOrientation::Vertical);
924
        let taken = d.swap_with_default();
925

            
926
        // The returned value is the *original*, intact.
927
        assert_eq!(taken.orientation, DividerOrientation::Vertical);
928
        assert_eq!(width_px(&taken.resolved_divider_style()), Some(1.0));
929
        assert_eq!(
930
            taken,
931
            Divider::create_with_orientation(DividerOrientation::Vertical)
932
        );
933

            
934
        // What is left behind is a *default* — in particular the vertical
935
        // `width` must not have survived the swap.
936
        assert_eq!(d, Divider::default());
937
        assert_eq!(d.orientation, DividerOrientation::Horizontal);
938
        assert_eq!(
939
            width_px(&d.resolved_divider_style()),
940
            None,
941
            "the vertical width survived the swap"
942
        );
943
        assert_eq!(height_px(&d.resolved_divider_style()), Some(1.0));
944
    }
945

            
946
    #[test]
947
    fn swap_with_default_is_idempotent_on_an_already_default_divider() {
948
        let mut d = Divider::default();
949
        let first = d.swap_with_default();
950
        let second = d.swap_with_default();
951
        assert_eq!(first, Divider::default());
952
        assert_eq!(second, Divider::default());
953
        assert_eq!(d, Divider::default());
954
    }
955

            
956
    #[test]
957
    fn repeated_swaps_never_corrupt_the_static_backed_style() {
958
        // `mem::swap` moves a vec that borrows a `'static` slice; 100 rounds of
959
        // swap-and-drop would surface a double free or a dangling `ptr`.
960
        let mut d = Divider::create_with_orientation(DividerOrientation::Vertical);
961
        for round in 0..100 {
962
            let taken = d.swap_with_default();
963
            if round == 0 {
964
                assert_eq!(
965
                    taken.orientation,
966
                    DividerOrientation::Vertical,
967
                    "round 0: wrong value returned"
968
                );
969
            } else {
970
                assert_eq!(
971
                    taken,
972
                    Divider::default(),
973
                    "round {round}: the emptied slot was not a default"
974
                );
975
            }
976
            assert_eq!(
977
                d,
978
                Divider::default(),
979
                "round {round}: what was left behind is not a default"
980
            );
981
            assert_eq!(
982
                d.resolved_divider_style().len(),
983
                DECL_COUNT,
984
                "round {round}: the style vec changed length"
985
            );
986
        }
987
    }
988

            
989
    #[test]
990
    fn swap_with_default_returns_a_custom_style_untouched() {
991
        let custom =
992
            CssPropertyWithConditionsVec::from_vec(vec![CssPropertyWithConditions::simple(
993
                CssProperty::const_width(LayoutWidth::const_px(9)),
994
            )]);
995
        let mut d = Divider {
996
            orientation: DividerOrientation::Vertical,
997
            divider_style: OptionCssPropertyWithConditionsVec::Some(custom),
998
        };
999
        let taken = d.swap_with_default();
        assert_eq!(taken.orientation, DividerOrientation::Vertical);
        assert_eq!(
            taken.resolved_divider_style().len(),
            1,
            "the custom style was rewritten on the way out"
        );
        assert_eq!(width_px(&taken.resolved_divider_style()), Some(9.0));
        assert_eq!(d, Divider::default());
    }
    // ------------------------------------------------------------------
    // Divider::dom  (round-trip: divider -> DOM)
    // ------------------------------------------------------------------
    #[test]
    fn dom_is_a_single_classed_div_with_no_children_or_callbacks() {
        for o in ALL_ORIENTATIONS {
            let divider = Divider::create_with_orientation(o);
            let expected = properties(&divider.resolved_divider_style());
            let dom = divider.dom();
            assert!(
                has_class(&dom, "__azul-native-divider"),
                "{o:?}: missing the widget class"
            );
            assert_eq!(
                dom.root.get_node_type(),
                &NodeType::Div,
                "{o:?}: a rule must be a plain div"
            );
            assert!(
                dom.children.as_ref().is_empty(),
                "{o:?}: a divider is a leaf, not a subtree"
            );
            assert!(
                dom.root.callbacks.as_ref().is_empty(),
                "{o:?}: a stateless widget must not bind callbacks"
            );
            assert_eq!(
                inline_properties(&dom),
                expected,
                "{o:?}: the rule lost its computed style"
            );
            assert_eq!(
                dom.root.get_ids_and_classes().as_ref().len(),
                1,
                "{o:?}: expected exactly one class and no ids"
            );
        }
    }
    #[test]
    fn dom_renders_the_orientation_the_divider_was_last_set_to() {
        // `dom()` consumes the *cached* style, so a `set_orientation` that forgot
        // to recompute would paint the previous axis here and nowhere else.
        for o in ALL_ORIENTATIONS {
            let mut divider = Divider::create();
            divider.set_orientation(DividerOrientation::Vertical);
            divider.set_orientation(o);
            let expected =
                properties(&Divider::create_with_orientation(o).resolved_divider_style());
            assert_eq!(
                inline_properties(&divider.dom()),
                expected,
                "{o:?}: the DOM shows a stale axis"
            );
        }
    }
    #[test]
    fn dom_of_the_two_orientations_differ_but_carry_the_same_class() {
        let h = Divider::create().dom();
        let v = Divider::create_with_orientation(DividerOrientation::Vertical).dom();
        assert_ne!(
            inline_properties(&h),
            inline_properties(&v),
            "both orientations render identically"
        );
        // Both share one class, so a stylesheet cannot tell them apart by class
        // alone — pinned here so a future split is a deliberate change.
        assert!(has_class(&h, "__azul-native-divider"));
        assert!(has_class(&v, "__azul-native-divider"));
        assert_eq!(
            h.root.get_ids_and_classes().as_ref(),
            v.root.get_ids_and_classes().as_ref(),
            "the two orientations were expected to share their class list"
        );
    }
    #[test]
    fn the_widget_class_is_a_namespaced_ascii_css_identifier() {
        let dom = Divider::create().dom();
        let classes = dom.root.get_ids_and_classes();
        let name = classes
            .as_ref()
            .iter()
            .find_map(|c| match c {
                Class(s) => Some(s.as_str().to_string()),
                IdOrClass::Id(_) => None,
            })
            .expect("the divider must carry a class");
        assert_eq!(name, "__azul-native-divider");
        assert!(!name.is_empty(), "empty class name");
        assert!(name.is_ascii(), "non-ASCII class name {name:?}");
        assert!(
            name.starts_with("__azul-native-"),
            "unnamespaced class {name:?}"
        );
        // A space, a dot or a `#` would silently split/re-target the selector.
        assert!(
            name.chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'),
            "class name {name:?} contains a CSS-significant character"
        );
    }
    #[test]
    fn from_divider_for_dom_is_exactly_dom() {
        for o in ALL_ORIENTATIONS {
            let divider = Divider::create_with_orientation(o);
            let via_into: Dom = divider.clone().into();
            let via_dom = divider.dom();
            assert_eq!(
                inline_properties(&via_into),
                inline_properties(&via_dom),
                "{o:?}: `From` diverges from `dom()`"
            );
            assert_eq!(
                via_into.root.get_node_type(),
                via_dom.root.get_node_type(),
                "{o:?}: `From` built a different node"
            );
            assert_eq!(
                via_into.root.get_ids_and_classes().as_ref(),
                via_dom.root.get_ids_and_classes().as_ref(),
                "{o:?}: `From` produced a different class list"
            );
        }
    }
    #[test]
    fn dom_renders_the_style_field_and_ignores_the_orientation_field() {
        // `dom()` only consumes `divider_style`. A hand-built divider whose
        // `orientation` contradicts its style therefore renders the *style* —
        // pinned so the divergence is documented rather than surprising.
        let desynced = Divider {
            orientation: DividerOrientation::Vertical,
            divider_style: OptionCssPropertyWithConditionsVec::Some(
                CssPropertyWithConditionsVec::from_const_slice(DIVIDER_STYLE_HORIZONTAL),
            ),
        };
        let rendered = inline_properties(&desynced.dom());
        assert_eq!(
            rendered,
            properties(&Divider::create().resolved_divider_style()),
            "dom() did not render the style it was handed"
        );
    }
    #[test]
    fn dom_of_an_empty_style_is_still_a_classed_div() {
        // Boundary case: zero declarations. Must not panic and must keep the
        // class, otherwise the node becomes untargetable *and* invisible.
        let d = Divider {
            orientation: DividerOrientation::Horizontal,
            divider_style: OptionCssPropertyWithConditionsVec::Some(
                CssPropertyWithConditionsVec::new(),
            ),
        };
        let dom = d.dom();
        assert!(has_class(&dom, "__azul-native-divider"));
        assert_eq!(dom.root.get_node_type(), &NodeType::Div);
        assert!(
            inline_properties(&dom).is_empty(),
            "properties appeared out of an empty style vec"
        );
        assert!(dom.children.as_ref().is_empty());
    }
    #[test]
    fn dom_preserves_a_huge_custom_style_verbatim_and_in_order() {
        // 10k declarations through the `CssPropertyWithConditionsVec` -> `Css`
        // bridge: a bug that dropped, truncated or reordered entries (the very
        // failure that bridge's comment describes) would show up here.
        let big: Vec<CssPropertyWithConditions> = (0..10_000_isize)
            .map(|i| {
                CssPropertyWithConditions::simple(CssProperty::const_margin_top(
                    LayoutMarginTop::const_px(i),
                ))
            })
            .collect();
        let expected: Vec<CssProperty> = big.iter().map(|p| p.property.clone()).collect();
        let d = Divider {
            orientation: DividerOrientation::Horizontal,
            divider_style: OptionCssPropertyWithConditionsVec::Some(
                CssPropertyWithConditionsVec::from_vec(big),
            ),
        };
        let rendered = inline_properties(&d.dom());
        assert_eq!(
            rendered.len(),
            10_000,
            "declarations were dropped on the way into the DOM"
        );
        assert_eq!(rendered, expected, "declaration order was not preserved");
    }
    #[test]
    fn dom_preserves_the_conditions_attached_to_each_declaration() {
        // The bridge promises "the original conditions intact"; a lost condition
        // would turn a `:hover` override into an unconditional one.
        let props = vec![
            CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
            CssPropertyWithConditions::on_hover(CssProperty::const_height(LayoutHeight::const_px(
                3,
            ))),
        ];
        let d = Divider {
            orientation: DividerOrientation::Horizontal,
            divider_style: OptionCssPropertyWithConditionsVec::Some(
                CssPropertyWithConditionsVec::from_vec(props),
            ),
        };
        let pairs = inline_properties_with_condition_counts(&d.dom());
        assert_eq!(pairs.len(), 2, "a declaration was dropped");
        assert_eq!(pairs[0].0, CssProperty::const_display(LayoutDisplay::Block));
        assert_eq!(
            pairs[0].1, 0,
            "an unconditional declaration gained a condition"
        );
        assert_eq!(
            pairs[1].0,
            CssProperty::const_height(LayoutHeight::const_px(3))
        );
        assert_eq!(pairs[1].1, 1, "the :hover condition was dropped");
    }
    #[test]
    fn building_many_doms_is_stable() {
        // Every divider borrows the same `'static` style table; building and
        // dropping many DOMs from it must not perturb later ones.
        let expected = properties(&Divider::create().resolved_divider_style());
        for round in 0..500 {
            let dom = Divider::create().dom();
            assert_eq!(
                inline_properties(&dom),
                expected,
                "round {round}: the shared style drifted"
            );
            drop(dom);
        }
        assert_eq!(
            properties(&Divider::create().resolved_divider_style()),
            expected
        );
    }
    // ------------------------------------------------------------------
    // Equality
    // ------------------------------------------------------------------
    #[test]
    fn equality_sees_both_fields() {
        assert_ne!(
            Divider::create_with_orientation(DividerOrientation::Horizontal),
            Divider::create_with_orientation(DividerOrientation::Vertical),
            "dividers of different orientation must not compare equal"
        );
        // Same orientation, different style => not equal.
        let styled = Divider {
            orientation: DividerOrientation::Horizontal,
            divider_style: OptionCssPropertyWithConditionsVec::Some(
                CssPropertyWithConditionsVec::new(),
            ),
        };
        assert_ne!(
            styled,
            Divider::create(),
            "the style field must affect equality"
        );
        // Same style, different orientation => not equal.
        let rotated = Divider {
            orientation: DividerOrientation::Vertical,
            divider_style: OptionCssPropertyWithConditionsVec::None,
        };
        assert_ne!(
            rotated,
            Divider::create(),
            "the orientation field must affect equality"
        );
    }
}