frus-core 0.2.1

frus — shared foundation types (geometry, colour)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! The **box decoration** model: the vocabulary for painting a rectangle
//! (background, gradient, border, rounded corners, shadow), independent of any
//! widget or theme.
//!
//! A [`BoxDecoration`] is a pure `Copy` value that a widget assembles at paint
//! time, then **lowers** into [`Scene`] primitives through
//! [`BoxDecoration::paint_into`], in a **fixed order**: shadow → background
//! (colour or gradient) → border. It feeds layout too:
//! [`BoxDecoration::content_padding`] reserves room for the border on taffy's
//! behalf.

use crate::{Color, Insets, Rect, Scene, TextDirection};

/// Corner radii, **per corner** (logical px). `From<f32>` covers the uniform case:
/// anywhere a radius is expected, a plain `10.0` still works.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct BorderRadius {
    /// The top-left corner's radius, in logical pixels.
    pub top_left: f32,
    /// The top-right corner's radius, in logical pixels.
    pub top_right: f32,
    /// The bottom-right corner's radius, in logical pixels.
    pub bottom_right: f32,
    /// The bottom-left corner's radius, in logical pixels.
    pub bottom_left: f32,
}

/// **A corner radius named by the reading direction rather than by the wall**
/// (`border_radius.dart:621`).
///
/// A [`BorderRadius`] says *top left*. This says *top start* — the corner where the text
/// begins, which is the left one in English and the right one in Arabic. [`resolve`] turns
/// one into the other once the direction is known.
///
/// The distinction is not decorative. A drawer rounds its **inner** edge, the one facing
/// the page: for a leading drawer that is the *end* side in either direction, and a radius
/// written as *right* is correct in English and wrong in Arabic. Every asymmetric radius
/// in an interface that mirrors has this question, and answering it by hand at each site
/// is how one of them ends up answered differently.
///
/// The reference has one type hierarchy for this (`BorderRadiusGeometry`, with a resolved
/// and an unresolved subclass); this is two plain types and a `resolve`, because a widget
/// here is handed a `&Theme` and so always has a direction available when it needs one.
///
/// [`resolve`]: Self::resolve
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct BorderRadiusDirectional {
    /// The corner at the top of the line's **beginning**.
    pub top_start: f32,
    /// The corner at the top of the line's **end**.
    pub top_end: f32,
    /// The corner at the bottom of the line's **end**.
    pub bottom_end: f32,
    /// The corner at the bottom of the line's **beginning**.
    pub bottom_start: f32,
}

impl BorderRadiusDirectional {
    /// No rounding at all.
    pub const ZERO: Self = Self::uniform(0.0);

    /// The same radius on all four corners — which needs no direction, and is here so a
    /// caller can write one without changing type halfway through an expression.
    pub const fn uniform(radius: f32) -> Self {
        Self {
            top_start: radius,
            top_end: radius,
            bottom_end: radius,
            bottom_start: radius,
        }
    }

    /// The two corners at the line's **beginning** — the left pair in English, the right
    /// pair in Arabic.
    pub const fn start(radius: f32) -> Self {
        Self {
            top_start: radius,
            top_end: 0.0,
            bottom_end: 0.0,
            bottom_start: radius,
        }
    }

    /// The two corners at the line's **end**.
    pub const fn end(radius: f32) -> Self {
        Self {
            top_start: 0.0,
            top_end: radius,
            bottom_end: radius,
            bottom_start: 0.0,
        }
    }

    /// Both sides at once, each with its own radius — the reference's
    /// `BorderRadiusDirectional.horizontal`.
    pub const fn horizontal(start: f32, end: f32) -> Self {
        Self {
            top_start: start,
            top_end: end,
            bottom_end: end,
            bottom_start: start,
        }
    }

    /// The top pair and the bottom pair. Neither depends on the direction, so this is the
    /// same as [`BorderRadius`]'s — and is here for the same reason as
    /// [`uniform`](Self::uniform).
    pub const fn vertical(top: f32, bottom: f32) -> Self {
        Self {
            top_start: top,
            top_end: top,
            bottom_end: bottom,
            bottom_start: bottom,
        }
    }

    /// **The concrete radius**, once the direction is known: `start` becomes left where
    /// the text runs left to right, and right where it does not.
    pub const fn resolve(self, direction: TextDirection) -> BorderRadius {
        match direction {
            TextDirection::Ltr => BorderRadius {
                top_left: self.top_start,
                top_right: self.top_end,
                bottom_right: self.bottom_end,
                bottom_left: self.bottom_start,
            },
            TextDirection::Rtl => BorderRadius {
                top_left: self.top_end,
                top_right: self.top_start,
                bottom_right: self.bottom_start,
                bottom_left: self.bottom_end,
            },
        }
    }
}

impl From<f32> for BorderRadiusDirectional {
    fn from(radius: f32) -> Self {
        Self::uniform(radius)
    }
}

impl BorderRadius {
    /// Each corner `t` of the way from `self` to `other`.
    ///
    /// Not clamped: a corner past its target is what a spring asks for at the end of its
    /// travel, and the one rule for a radius in flight is this one — an animated container
    /// and a decoration transition both go through it.
    #[must_use]
    pub fn lerp(self, other: BorderRadius, t: f32) -> BorderRadius {
        let mix = |a: f32, b: f32| a + (b - a) * t;
        BorderRadius {
            top_left: mix(self.top_left, other.top_left),
            top_right: mix(self.top_right, other.top_right),
            bottom_right: mix(self.bottom_right, other.bottom_right),
            bottom_left: mix(self.bottom_left, other.bottom_left),
        }
    }

    /// No rounding at all.
    pub const ZERO: Self = Self::uniform(0.0);

    /// The same radius on all four corners.
    pub const fn uniform(radius: f32) -> Self {
        Self {
            top_left: radius,
            top_right: radius,
            bottom_right: radius,
            bottom_left: radius,
        }
    }

    /// Only the **top** corners rounded (headers, rising sheets).
    pub const fn top(radius: f32) -> Self {
        Self {
            top_left: radius,
            top_right: radius,
            bottom_right: 0.0,
            bottom_left: 0.0,
        }
    }

    /// Only the **bottom** corners rounded.
    pub const fn bottom(radius: f32) -> Self {
        Self {
            top_left: 0.0,
            top_right: 0.0,
            bottom_right: radius,
            bottom_left: radius,
        }
    }

    /// Only the **left** corners rounded.
    pub const fn left(radius: f32) -> Self {
        Self {
            top_left: radius,
            top_right: 0.0,
            bottom_right: 0.0,
            bottom_left: radius,
        }
    }

    /// Only the **right** corners rounded.
    ///
    /// With [`left`](Self::left) this completes the set: a shape rounded on one
    /// **vertical** edge is what a side panel wants — square where it meets the window,
    /// round where it meets the content — and until now only the horizontal pair
    /// ([`top`](Self::top), [`bottom`](Self::bottom)) existed.
    pub const fn right(radius: f32) -> Self {
        Self {
            top_left: 0.0,
            top_right: radius,
            bottom_right: radius,
            bottom_left: 0.0,
        }
    }

    /// Radii **clamped at zero** — a negative radius is meaningless when painting.
    pub fn clamped(self) -> Self {
        Self {
            top_left: self.top_left.max(0.0),
            top_right: self.top_right.max(0.0),
            bottom_right: self.bottom_right.max(0.0),
            bottom_left: self.bottom_left.max(0.0),
        }
    }

    /// Every corner grown by `by` — the envelope of a blurred shadow.
    pub fn inflate(self, by: f32) -> Self {
        Self {
            top_left: self.top_left + by,
            top_right: self.top_right + by,
            bottom_right: self.bottom_right + by,
            bottom_left: self.bottom_left + by,
        }
    }

    /// Every radius multiplied by `factor` (DPI scaling).
    pub fn scale(self, factor: f32) -> Self {
        Self {
            top_left: self.top_left * factor,
            top_right: self.top_right * factor,
            bottom_right: self.bottom_right * factor,
            bottom_left: self.bottom_left * factor,
        }
    }

    /// `[tl, tr, br, bl]`, ready for the GPU.
    pub fn to_array(self) -> [f32; 4] {
        [
            self.top_left,
            self.top_right,
            self.bottom_right,
            self.bottom_left,
        ]
    }
}

impl From<f32> for BorderRadius {
    fn from(radius: f32) -> Self {
        Self::uniform(radius)
    }
}

/// A uniform border — the same width and colour on all four sides.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Border {
    /// Width, in logical pixels.
    pub width: f32,
    /// The line's colour.
    pub color: Color,
}

impl Border {
    /// A uniform border.
    pub const fn new(width: f32, color: Color) -> Self {
        Self { width, color }
    }

    /// `true` when the border is visible — non-zero width and non-zero alpha.
    pub fn is_visible(&self) -> bool {
        self.width > 0.0 && self.color.a > 0.0
    }
}

/// A **linear** gradient: from the background (`BoxDecoration::color`) to `end`,
/// along `direction`, expressed in `[0,1]²` space (`[0,1]` = top→bottom, `[1,0]` =
/// left→right).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LinearGradient {
    /// The end colour; the start colour is the decoration's background.
    pub end: Color,
    /// The gradient's direction, in `[0,1]²` space.
    pub direction: [f32; 2],
}

impl LinearGradient {
    /// A linear gradient towards `end`, in the given direction.
    pub const fn new(end: Color, direction: [f32; 2]) -> Self {
        Self { end, direction }
    }
}

/// A soft drop shadow.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BoxShadow {
    /// Colour; its alpha sets the intensity.
    pub color: Color,
    /// Offset `(dx, dy)`, in logical pixels.
    pub offset: (f32, f32),
    /// Blur radius.
    pub blur: f32,
    /// How far the shadow grows beyond the box, before blurring.
    pub spread: f32,
}

impl BoxShadow {
    /// A shadow offset by `(dx, dy)` with `blur`, and no spread.
    pub const fn new(dx: f32, dy: f32, blur: f32, color: Color) -> Self {
        Self {
            color,
            offset: (dx, dy),
            blur,
            spread: 0.0,
        }
    }

    /// Sets the `spread`.
    pub const fn spread(mut self, spread: f32) -> Self {
        self.spread = spread;
        self
    }

    /// The rectangle the shadow occupies around `rect` (offset + blur + spread).
    pub fn bounds(&self, rect: Rect) -> Rect {
        let grow = self.blur + self.spread;
        Rect::new(
            rect.x + self.offset.0 - grow,
            rect.y + self.offset.1 - grow,
            rect.width + 2.0 * grow,
            rect.height + 2.0 * grow,
        )
    }
}

/// The complete decoration of a rectangular box.
///
/// The paint order is **fixed**: shadow → background → border. The background is
/// either flat (`color`) or a gradient (`color` → `gradient.end`). A border with no
/// background paints an outline over transparency; a wholly empty decoration paints
/// nothing at all.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct BoxDecoration {
    /// Background colour, which doubles as the start colour of any gradient.
    pub color: Option<Color>,
    /// A linear gradient for the background.
    pub gradient: Option<LinearGradient>,
    /// A uniform border.
    pub border: Option<Border>,
    /// Corner radii, per corner.
    pub radius: BorderRadius,
    /// Drop shadow.
    pub shadow: Option<BoxShadow>,
}

/// A colour that may be absent on either side, `t` of the way across.
///
/// Absent means **nothing painted**, so a colour on one side only fades: it keeps its hue
/// and only its alpha travels. Interpolating towards `Color::TRANSPARENT` instead would be
/// interpolating towards transparent *black* — a red fill fading out would go dark red on
/// the way, in a movement that was only ever about disappearing.
fn fade_between(a: Option<Color>, b: Option<Color>, t: f32) -> Option<Color> {
    match (a, b) {
        (Some(a), Some(b)) => Some(a.lerp(b, t)),
        (Some(a), None) => Some(a.fade(1.0 - t)),
        (None, Some(b)) => Some(b.fade(t)),
        (None, None) => None,
    }
}

impl BoxDecoration {
    /// The decoration `t` of the way from `self` to `other` — what a decoration transition
    /// paints mid-flight. Each part has its own rule, and the rules are the point:
    ///
    /// - **Colours mix** where both sides have one, in the space colours are stated in,
    ///   as every animated colour in this framework does.
    /// - **A part on one side only arrives or leaves; it does not come from nowhere.** A
    ///   fill fades, keeping its hue. A border thickens from nought in its own colour. A
    ///   shadow grows from under the box as it fades in. Each is the part scaled by how far
    ///   along it is, which is also what the reference does with a part one side lacks.
    /// - **A flat fill is a gradient whose two ends agree**, so flat to graded spreads the
    ///   far end out of the fill rather than laying a gradient over it. Here a gradient
    ///   *starts* at the fill colour, so the two always arrive and leave together.
    /// - **Corners** travel one by one.
    ///
    /// The absent colour here is **not** the absent colour of a text style, and the two
    /// rules differ for that reason. A text style that names no colour is asking the theme
    /// for one — a real, visible colour — so it holds still rather than fade. A decoration
    /// that names no fill paints nothing, so fading is exactly what reaching it means.
    ///
    /// `t` is clamped to `0..=1`, and a `t` that is not a number is no progress: past its
    /// ends a colour has nowhere to go, and a decoration whose colours stopped at the end
    /// while its corners kept going would be two clocks. At `0` and `1` the answer is the
    /// end itself, exactly.
    #[must_use]
    pub fn lerp(self, other: BoxDecoration, t: f32) -> BoxDecoration {
        if t.is_nan() || t <= 0.0 {
            return self;
        }
        if t >= 1.0 {
            return other;
        }
        let mix = |a: f32, b: f32| a + (b - a) * t;
        let gradient = match (self.gradient, other.gradient) {
            (Some(a), Some(b)) => Some(LinearGradient {
                end: a.end.lerp(b.end, t),
                direction: [
                    mix(a.direction[0], b.direction[0]),
                    mix(a.direction[1], b.direction[1]),
                ],
            }),
            // The side without a gradient is a flat fill: its far end is its own colour.
            (Some(a), None) => {
                fade_between(Some(a.end), other.color, t).map(|end| LinearGradient {
                    end,
                    direction: a.direction,
                })
            }
            (None, Some(b)) => fade_between(self.color, Some(b.end), t).map(|end| LinearGradient {
                end,
                direction: b.direction,
            }),
            (None, None) => None,
        };
        let border = match (self.border, other.border) {
            (Some(a), Some(b)) => Some(Border {
                width: mix(a.width, b.width),
                color: a.color.lerp(b.color, t),
            }),
            (Some(a), None) => Some(Border {
                width: a.width * (1.0 - t),
                ..a
            }),
            (None, Some(b)) => Some(Border {
                width: b.width * t,
                ..b
            }),
            (None, None) => None,
        };
        // A shadow on one side only, scaled: it grows out from under the box as it fades
        // in. Scaling the geometry alone would leave a hard-edged block of shadow colour
        // under a box whose own fill may be fading too.
        let grown = |s: BoxShadow, f: f32| BoxShadow {
            color: s.color.fade(f),
            offset: (s.offset.0 * f, s.offset.1 * f),
            blur: s.blur * f,
            spread: s.spread * f,
        };
        let shadow = match (self.shadow, other.shadow) {
            (Some(a), Some(b)) => Some(BoxShadow {
                color: a.color.lerp(b.color, t),
                offset: (mix(a.offset.0, b.offset.0), mix(a.offset.1, b.offset.1)),
                blur: mix(a.blur, b.blur),
                spread: mix(a.spread, b.spread),
            }),
            (Some(a), None) => Some(grown(a, 1.0 - t)),
            (None, Some(b)) => Some(grown(b, t)),
            (None, None) => None,
        };
        BoxDecoration {
            color: fade_between(self.color, other.color, t),
            gradient,
            border,
            radius: self.radius.lerp(other.radius, t),
            shadow,
        }
    }
}

impl BoxDecoration {
    /// A decoration with a flat background.
    pub fn filled(color: Color) -> Self {
        Self {
            color: Some(color),
            ..Default::default()
        }
    }

    /// Sets the corner radii — uniform through `f32`, per corner through
    /// [`BorderRadius`].
    pub fn radius(mut self, radius: impl Into<BorderRadius>) -> Self {
        self.radius = radius.into();
        self
    }

    /// Adds a uniform border.
    pub fn border(mut self, border: Border) -> Self {
        self.border = Some(border);
        self
    }

    /// Adds a shadow.
    pub fn shadow(mut self, shadow: BoxShadow) -> Self {
        self.shadow = Some(shadow);
        self
    }

    /// Adds a linear gradient to the background.
    pub fn gradient(mut self, gradient: LinearGradient) -> Self {
        self.gradient = Some(gradient);
        self
    }

    /// The inner margin the border needs — add it to the padding so the content is
    /// not eaten by the line. This is what feeds taffy.
    pub fn content_padding(&self) -> Insets {
        match self.border {
            Some(b) if b.is_visible() => Insets::uniform(b.width),
            _ => Insets::ZERO,
        }
    }

    /// Lowers the decoration into `scene` primitives, in the fixed order
    /// shadow → background → border. `opacity` (`0..=1`) modulates **every** colour,
    /// which is how a fade-in works. `rect` is the box in absolute coordinates.
    pub fn paint_into(&self, scene: &mut Scene, rect: Rect, opacity: f32) {
        // 1) The shadow, behind everything else.
        if let Some(shadow) = self.shadow {
            scene.shadow(
                shadow.bounds(rect),
                shadow.color.fade(opacity),
                self.radius.inflate(shadow.blur + shadow.spread),
                shadow.blur,
            );
        }

        // 2/3) Background (flat or gradient) plus border, in a single primitive.
        let (border_width, border_color) = match self.border {
            Some(b) => (b.width, b.color.fade(opacity)),
            None => (0.0, Color::TRANSPARENT),
        };
        let has_border = self.border.map(|b| b.is_visible()).unwrap_or(false);

        match (self.color, self.gradient) {
            (Some(color), Some(gradient)) => scene.gradient_rect(
                rect,
                color.fade(opacity),
                gradient.end.fade(opacity),
                gradient.direction,
                self.radius,
                border_width,
                border_color,
            ),
            (Some(color), None) => scene.draw_rect(
                rect,
                color.fade(opacity),
                self.radius,
                border_width,
                border_color,
            ),
            // Border only, with no background: an outline over transparency.
            (None, _) if has_border => scene.draw_rect(
                rect,
                Color::TRANSPARENT,
                self.radius,
                border_width,
                border_color,
            ),
            // Nothing to paint.
            (None, _) => {}
        }
    }
}

#[cfg(test)]
mod tests {
    /// **A directional radius names the corner by the line, not by the wall**
    /// (`border_radius.dart:621`), and `resolve` says which wall that is.
    #[test]
    fn a_directional_radius_follows_the_reading_direction() {
        let end = BorderRadiusDirectional::end(16.0);
        assert_eq!(
            end.resolve(TextDirection::Ltr),
            BorderRadius::right(16.0),
            "the line ends on the right in English"
        );
        assert_eq!(
            end.resolve(TextDirection::Rtl),
            BorderRadius::left(16.0),
            "and on the left in Arabic"
        );

        let start = BorderRadiusDirectional::start(16.0);
        assert_eq!(start.resolve(TextDirection::Ltr), BorderRadius::left(16.0));
        assert_eq!(start.resolve(TextDirection::Rtl), BorderRadius::right(16.0));

        // Both sides at once, each keeping its own number across the mirror.
        let both = BorderRadiusDirectional::horizontal(4.0, 12.0);
        assert_eq!(
            both.resolve(TextDirection::Ltr),
            BorderRadius {
                top_left: 4.0,
                top_right: 12.0,
                bottom_right: 12.0,
                bottom_left: 4.0,
            }
        );
        assert_eq!(
            both.resolve(TextDirection::Rtl),
            BorderRadius {
                top_left: 12.0,
                top_right: 4.0,
                bottom_right: 4.0,
                bottom_left: 12.0,
            }
        );

        // What has no side does not move.
        for direction in [TextDirection::Ltr, TextDirection::Rtl] {
            assert_eq!(
                BorderRadiusDirectional::uniform(8.0).resolve(direction),
                BorderRadius::uniform(8.0)
            );
            assert_eq!(
                BorderRadiusDirectional::vertical(8.0, 0.0).resolve(direction),
                BorderRadius::top(8.0)
            );
        }
    }
    use super::*;
    use crate::Primitive;

    fn rect() -> Rect {
        Rect::new(10.0, 20.0, 100.0, 40.0)
    }

    #[test]
    fn content_padding_reserves_the_border() {
        let deco = BoxDecoration::filled(Color::WHITE).border(Border::new(2.0, Color::BLACK));
        assert_eq!(deco.content_padding(), Insets::uniform(2.0));
        // An invisible border (zero width) → no padding.
        let none = BoxDecoration::filled(Color::WHITE).border(Border::new(0.0, Color::BLACK));
        assert_eq!(none.content_padding(), Insets::ZERO);
    }

    #[test]
    fn empty_decoration_paints_nothing() {
        let mut scene = Scene::new();
        BoxDecoration::default().paint_into(&mut scene, rect(), 1.0);
        assert!(scene.is_empty());
    }

    #[test]
    fn fixed_paint_order_shadow_then_fill() {
        let mut scene = Scene::new();
        let deco = BoxDecoration::filled(Color::WHITE)
            .radius(6.0)
            .shadow(BoxShadow::new(
                0.0,
                4.0,
                8.0,
                Color::rgba(0.0, 0.0, 0.0, 0.5),
            ));
        deco.paint_into(&mut scene, rect(), 1.0);
        // Two primitives: the shadow first, then the background.
        assert_eq!(scene.len(), 2);
        match scene.primitives()[0] {
            Primitive::Rect { blur, .. } => {
                assert!(blur > 0.0, "first primitive = the blurred shadow")
            }
            _ => panic!("expected a rectangle"),
        }
        match scene.primitives()[1] {
            Primitive::Rect { blur, color, .. } => {
                assert_eq!(blur, 0.0, "second primitive = the crisp background");
                assert_eq!(color, Color::WHITE);
            }
            _ => panic!("expected a rectangle"),
        }
    }

    #[test]
    fn opacity_fades_all_colours() {
        let mut scene = Scene::new();
        BoxDecoration::filled(Color::rgb(1.0, 0.0, 0.0))
            .border(Border::new(2.0, Color::rgb(0.0, 1.0, 0.0)))
            .paint_into(&mut scene, rect(), 0.5);
        match scene.primitives()[0] {
            Primitive::Rect {
                color,
                border_color,
                ..
            } => {
                assert_eq!(color.a, 0.5);
                assert_eq!(border_color.a, 0.5);
            }
            _ => panic!("expected a rectangle"),
        }
    }

    #[test]
    fn border_only_paints_transparent_fill_with_stroke() {
        let mut scene = Scene::new();
        BoxDecoration::default()
            .border(Border::new(1.0, Color::WHITE))
            .paint_into(&mut scene, rect(), 1.0);
        assert_eq!(scene.len(), 1);
        match scene.primitives()[0] {
            Primitive::Rect {
                color,
                border_width,
                ..
            } => {
                assert_eq!(color, Color::TRANSPARENT);
                assert_eq!(border_width, 1.0);
            }
            _ => panic!("expected a rectangle"),
        }
    }

    #[test]
    fn shadow_bounds_grow_with_blur_and_spread() {
        let s = BoxShadow::new(0.0, 0.0, 4.0, Color::BLACK).spread(2.0);
        let b = s.bounds(Rect::new(0.0, 0.0, 10.0, 10.0));
        // grow = blur + spread = 6 on every side.
        assert_eq!(b, Rect::new(-6.0, -6.0, 22.0, 22.0));
    }
}

/// The decoration in flight (milestone 501): one rule per part, and the ends exact.
#[cfg(test)]
mod lerp_tests {
    use super::*;

    const RED: Color = Color {
        r: 1.0,
        g: 0.0,
        b: 0.0,
        a: 1.0,
    };
    const BLUE: Color = Color {
        r: 0.0,
        g: 0.0,
        b: 1.0,
        a: 1.0,
    };

    /// **The ends are the ends, exactly** — and past them, and at a progress that is not a
    /// number, the nearer end.
    #[test]
    fn the_ends_are_the_ends_exactly() {
        let a = BoxDecoration::filled(RED).radius(4.0);
        let b = BoxDecoration::filled(BLUE).border(Border::new(2.0, RED));
        assert_eq!(a.lerp(b, 0.0), a);
        assert_eq!(a.lerp(b, 1.0), b);
        assert_eq!(a.lerp(b, -0.5), a, "an undershoot stops at the start");
        assert_eq!(a.lerp(b, 1.5), b, "an overshoot stops at the end");
        assert_eq!(a.lerp(b, f32::NAN), a, "and no progress is no progress");
    }

    /// **A fill fading out keeps its hue.** The obvious interpolation — towards
    /// `Color::TRANSPARENT` — is towards transparent *black*, and half-way there a red is a
    /// half-opaque dark red: a movement that was only about disappearing darkens on the way.
    #[test]
    fn a_fill_fading_out_does_not_pass_through_black() {
        let mid = BoxDecoration::filled(RED).lerp(BoxDecoration::default(), 0.5);
        let c = mid.color.expect("still painted, half faded");
        assert_eq!((c.r, c.g, c.b), (1.0, 0.0, 0.0), "the same red");
        assert!((c.a - 0.5).abs() < 1e-6, "at half its opacity: {c:?}");
        let naive = RED.lerp(Color::TRANSPARENT, 0.5);
        assert!(naive.r < 0.6, "the trap this avoids: {naive:?}");
    }

    /// And one fading in arrives in its own colour, only fainter.
    #[test]
    fn a_fill_fading_in_arrives_in_its_own_colour() {
        let c = BoxDecoration::default()
            .lerp(BoxDecoration::filled(BLUE), 0.25)
            .color
            .expect("already there, faintly");
        assert_eq!((c.r, c.g, c.b), (0.0, 0.0, 1.0));
        assert!((c.a - 0.25).abs() < 1e-6, "{c:?}");
    }

    /// **A flat fill is a gradient whose two ends agree**, so flat to graded spreads the
    /// far end out of the fill: the start does not move and the end travels.
    #[test]
    fn a_flat_fill_spreads_into_a_gradient() {
        let flat = BoxDecoration::filled(RED);
        let graded = BoxDecoration::filled(RED).gradient(LinearGradient::new(BLUE, [0.0, 1.0]));
        let mid = flat.lerp(graded, 0.5);
        assert_eq!(mid.color, Some(RED), "the start does not move");
        let g = mid.gradient.expect("a gradient half-way to its far colour");
        assert_eq!(g.end, RED.lerp(BLUE, 0.5));
        assert_eq!(g.direction, [0.0, 1.0]);
    }

    /// **A border arrives by thickening, in its own colour** — not as a colour on its way
    /// from nowhere.
    #[test]
    fn a_border_arrives_by_thickening_in_its_own_colour() {
        let lined = BoxDecoration::filled(RED).border(Border::new(4.0, BLUE));
        let quarter = BoxDecoration::filled(RED)
            .lerp(lined, 0.25)
            .border
            .expect("a line already");
        assert_eq!(quarter.width, 1.0);
        assert_eq!(quarter.color, BLUE);
    }

    /// **A shadow arrives by growing out from under the box as it fades in.**
    #[test]
    fn a_shadow_grows_and_fades_in() {
        let raised = BoxDecoration::filled(RED).shadow(BoxShadow::new(
            0.0,
            8.0,
            16.0,
            Color::rgba(0.0, 0.0, 0.0, 0.4),
        ));
        let half = BoxDecoration::filled(RED)
            .lerp(raised, 0.5)
            .shadow
            .expect("a shadow already");
        assert_eq!(half.offset, (0.0, 4.0));
        assert_eq!(half.blur, 8.0);
        assert!((half.color.a - 0.2).abs() < 1e-6, "{:?}", half.color);
    }

    /// Corners travel one by one, each from its own start.
    #[test]
    fn corners_travel_one_by_one() {
        let r = BoxDecoration::default()
            .radius(BorderRadius::top(8.0))
            .lerp(BoxDecoration::default().radius(16.0), 0.5)
            .radius;
        assert_eq!((r.top_left, r.bottom_left), (12.0, 8.0));
    }
}