Skip to main content

nsh_core/
effects.rs

1//! Visual effects beyond React Native's classic view styles: layered and
2//! inset box shadows, gradient backgrounds, filters, blend modes, outlines,
3//! cursors, and the transitions / keyframe animations of class styles.
4
5use std::sync::Arc;
6
7use crate::{
8    color::Hsla,
9    geometry::{
10        AbsoluteLength, Bounds, Corners, DefiniteLength, Edges, Percentage, Point, Points,
11        REM_SIZE, Radians, Size, deg, point, size,
12    },
13    style::{BorderStyle, Color, CornerRadii},
14};
15
16/// `clipPath`: CSS's `inset()` shape, a rectangle inset from the view's
17/// border box, its corners rounded (`inset(8px 0 0 50% round 12px)`).
18/// Everything the view draws shows only inside it (its background, borders,
19/// shadows and the views in it), and only there is the view, or anything in
20/// it, hit. It transitions (`transitionProperty: "clip-path"`), each edge and
21/// radius on its own, so a panel can open out of a corner.
22#[derive(Debug, Clone, Copy, PartialEq, Default)]
23#[non_exhaustive]
24pub struct ClipInset {
25    /// How far each edge moves in, in points (negative: out), besides
26    /// [`Self::fractions`].
27    pub offsets: Edges<Points>,
28    /// How far each edge moves in as a fraction of the box's width (left and
29    /// right) or height (top and bottom): CSS's percentages. An edge is at
30    /// its offset plus its fraction of the size, as CSS's `calc()`, which is
31    /// what an inset between a length and a percentage interpolates to.
32    pub fractions: Edges<Percentage>,
33    /// The corners' radii (`round`): circular, scaled down as a border's are
34    /// where they do not fit.
35    pub radii: Corners<Points>,
36}
37
38impl ClipInset {
39    /// No inset and square corners: the border box.
40    pub const fn new() -> Self {
41        Self {
42            offsets: Edges {
43                top: Points::ZERO,
44                right: Points::ZERO,
45                bottom: Points::ZERO,
46                left: Points::ZERO,
47            },
48            fractions: Edges {
49                top: Percentage(0.0),
50                right: Percentage(0.0),
51                bottom: Percentage(0.0),
52                left: Percentage(0.0),
53            },
54            radii: Corners {
55                top_left: Points::ZERO,
56                top_right: Points::ZERO,
57                bottom_right: Points::ZERO,
58                bottom_left: Points::ZERO,
59            },
60        }
61    }
62
63    /// Moves every edge in by `length`.
64    pub fn inset(self, length: impl Into<DefiniteLength>) -> Self {
65        let length = length.into();
66        self.top(length).right(length).bottom(length).left(length)
67    }
68
69    /// Moves the top edge down by `length` (a fraction: of the height).
70    pub fn top(mut self, length: impl Into<DefiniteLength>) -> Self {
71        (self.offsets.top, self.fractions.top) = edge(length.into());
72        self
73    }
74
75    /// Moves the right edge left by `length` (a fraction: of the width).
76    pub fn right(mut self, length: impl Into<DefiniteLength>) -> Self {
77        (self.offsets.right, self.fractions.right) = edge(length.into());
78        self
79    }
80
81    /// Moves the bottom edge up by `length` (a fraction: of the height).
82    pub fn bottom(mut self, length: impl Into<DefiniteLength>) -> Self {
83        (self.offsets.bottom, self.fractions.bottom) = edge(length.into());
84        self
85    }
86
87    /// Moves the left edge right by `length` (a fraction: of the width).
88    pub fn left(mut self, length: impl Into<DefiniteLength>) -> Self {
89        (self.offsets.left, self.fractions.left) = edge(length.into());
90        self
91    }
92
93    /// Rounds every corner by `radius`.
94    pub fn rounded(mut self, radius: impl Into<Points>) -> Self {
95        self.radii = Corners::all(radius.into());
96        self
97    }
98
99    /// Rounds each corner by its own radius.
100    pub fn corner_radii(mut self, radii: Corners<Points>) -> Self {
101        self.radii = radii;
102        self
103    }
104
105    /// The rectangle it clips a box of `size` to, in the box's coordinates,
106    /// and its radii fitted to it. As CSS: two opposite edges that would
107    /// pass each other are moved in proportion until they meet, and radii
108    /// that do not fit are scaled down together.
109    pub fn resolve(&self, size: Size<Points>) -> (Bounds<Points>, CornerRadii) {
110        let (w, h) = (size.width.0.max(0.0), size.height.0.max(0.0));
111        let at = |o: Points, f: Percentage, len: f32| o.0 + f.0 * len;
112        let (mut top, mut bottom) = (
113            at(self.offsets.top, self.fractions.top, h),
114            at(self.offsets.bottom, self.fractions.bottom, h),
115        );
116        let (mut left, mut right) = (
117            at(self.offsets.left, self.fractions.left, w),
118            at(self.offsets.right, self.fractions.right, w),
119        );
120        let meet = |a: &mut f32, b: &mut f32, len: f32| {
121            let sum = *a + *b;
122            if sum > len && sum > 0.0 {
123                let k = len / sum;
124                *a *= k;
125                *b *= k;
126            }
127        };
128        meet(&mut top, &mut bottom, h);
129        meet(&mut left, &mut right, w);
130        let rect = Bounds::new(
131            point(Points(left), Points(top)),
132            size_of((w - left - right).max(0.0), (h - top - bottom).max(0.0)),
133        );
134        let radii = CornerRadii::circular(self.radii.map(|r| r.max(Points::ZERO))).fit(rect.size);
135        (rect, radii)
136    }
137
138    /// The outline of the shape in a box of `size`, clockwise on screen
139    /// from the top edge, its corners circular arcs. Always the same
140    /// segments (a corner of radius 0 is a curve of length 0), so two
141    /// outlines interpolate segment by segment, as Core Animation animates
142    /// a path.
143    pub fn outline(&self, size: Size<Points>, out: &mut impl FnMut(crate::shape::Segment)) {
144        use crate::shape::Segment;
145        // A quarter circle's control points: `4/3 · (√2 − 1)` of the radius
146        // along each tangent.
147        const K: f32 = 0.552_284_8;
148        let (rect, radii) = self.resolve(size);
149        let (x0, y0) = (rect.origin.x.0, rect.origin.y.0);
150        let (x1, y1) = (x0 + rect.size.width.0, y0 + rect.size.height.0);
151        let (tl, tr, br, bl) = (
152            radii.top_left.0,
153            radii.top_right.0,
154            radii.bottom_right.0,
155            radii.bottom_left.0,
156        );
157        let p = |x: f32, y: f32| point(Points(x), Points(y));
158        let c =
159            |c1: Point<Points>, c2: Point<Points>, to: Point<Points>| Segment::Cubic([c1, c2, to]);
160        out(Segment::Move(p(x0 + tl, y0)));
161        out(Segment::Line(p(x1 - tr, y0)));
162        out(c(
163            p(x1 - tr + K * tr, y0),
164            p(x1, y0 + tr - K * tr),
165            p(x1, y0 + tr),
166        ));
167        out(Segment::Line(p(x1, y1 - br)));
168        out(c(
169            p(x1, y1 - br + K * br),
170            p(x1 - br + K * br, y1),
171            p(x1 - br, y1),
172        ));
173        out(Segment::Line(p(x0 + bl, y1)));
174        out(c(
175            p(x0 + bl - K * bl, y1),
176            p(x0, y1 - bl + K * bl),
177            p(x0, y1 - bl),
178        ));
179        out(Segment::Line(p(x0, y0 + tl)));
180        out(c(
181            p(x0, y0 + tl - K * tl),
182            p(x0 + tl - K * tl, y0),
183            p(x0 + tl, y0),
184        ));
185        out(Segment::Close);
186    }
187
188    /// Whether `p` (in the coordinates of a box of `size`) is inside it.
189    pub fn contains(&self, size: Size<Points>, p: Point<Points>) -> bool {
190        let (rect, radii) = self.resolve(size);
191        let (x0, y0) = (rect.origin.x.0, rect.origin.y.0);
192        let (x1, y1) = (x0 + rect.size.width.0, y0 + rect.size.height.0);
193        let (x, y) = (p.x.0, p.y.0);
194        if !(x >= x0 && y >= y0 && x < x1 && y < y1) {
195            return false;
196        }
197        // In a corner's square, the point must be within its circle.
198        let outside = |r: Points, cx: f32, cy: f32, beyond_x: bool, beyond_y: bool| {
199            let r = r.0;
200            r > 0.0 && beyond_x && beyond_y && {
201                let (dx, dy) = (x - cx, y - cy);
202                dx * dx + dy * dy > r * r
203            }
204        };
205        let (tl, tr, br, bl) = (
206            radii.top_left,
207            radii.top_right,
208            radii.bottom_right,
209            radii.bottom_left,
210        );
211        !(outside(tl, x0 + tl.0, y0 + tl.0, x < x0 + tl.0, y < y0 + tl.0)
212            || outside(tr, x1 - tr.0, y0 + tr.0, x > x1 - tr.0, y < y0 + tr.0)
213            || outside(br, x1 - br.0, y1 - br.0, x > x1 - br.0, y > y1 - br.0)
214            || outside(bl, x0 + bl.0, y1 - bl.0, x < x0 + bl.0, y > y1 - bl.0))
215    }
216
217    /// The inset `t` of the way from `self` to `to`, edge by edge and
218    /// corner by corner (`t` beyond 0..1 overshoots, radii stay at 0 or
219    /// more).
220    pub fn lerp(&self, to: &Self, t: f32) -> Self {
221        let l = |a: f32, b: f32| a + (b - a) * t;
222        let lp = |a: Points, b: Points| Points(l(a.0, b.0));
223        let lf = |a: Percentage, b: Percentage| Percentage(l(a.0, b.0));
224        Self {
225            offsets: Edges {
226                top: lp(self.offsets.top, to.offsets.top),
227                right: lp(self.offsets.right, to.offsets.right),
228                bottom: lp(self.offsets.bottom, to.offsets.bottom),
229                left: lp(self.offsets.left, to.offsets.left),
230            },
231            fractions: Edges {
232                top: lf(self.fractions.top, to.fractions.top),
233                right: lf(self.fractions.right, to.fractions.right),
234                bottom: lf(self.fractions.bottom, to.fractions.bottom),
235                left: lf(self.fractions.left, to.fractions.left),
236            },
237            radii: Corners {
238                top_left: lp(self.radii.top_left, to.radii.top_left).max(Points::ZERO),
239                top_right: lp(self.radii.top_right, to.radii.top_right).max(Points::ZERO),
240                bottom_right: lp(self.radii.bottom_right, to.radii.bottom_right).max(Points::ZERO),
241                bottom_left: lp(self.radii.bottom_left, to.radii.bottom_left).max(Points::ZERO),
242            },
243        }
244    }
245}
246
247/// An edge's length as an offset in points and a fraction.
248fn edge(length: DefiniteLength) -> (Points, Percentage) {
249    match length {
250        DefiniteLength::Absolute(a) => (a.to_points(REM_SIZE), Percentage(0.0)),
251        DefiniteLength::Fraction(f) => (Points::ZERO, f),
252    }
253}
254
255fn size_of(width: f32, height: f32) -> Size<Points> {
256    size(Points(width), Points(height))
257}
258
259/// One layer of `boxShadow` (CSS `box-shadow`).
260#[derive(Debug, Clone, Copy, PartialEq, Default)]
261pub struct BoxShadow {
262    /// Horizontal offset.
263    pub offset_x: Points,
264    /// Vertical offset.
265    pub offset_y: Points,
266    /// Blur radius (CSS: twice the Gaussian's standard deviation).
267    pub blur: Points,
268    /// How far the shadow's shape grows (negative: shrinks).
269    pub spread: Points,
270    /// Color.
271    pub color: Color,
272    /// Drawn inside the box, over the background.
273    pub inset: bool,
274}
275
276impl BoxShadow {
277    /// True if the layer draws anything.
278    pub fn is_visible(&self) -> bool {
279        !self.color.is_transparent()
280    }
281}
282
283/// How far a radial gradient reaches.
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
285pub enum GradientSize {
286    /// To the nearest side.
287    ClosestSide,
288    /// To the nearest corner.
289    ClosestCorner,
290    /// To the farthest side.
291    FarthestSide,
292    /// To the farthest corner (CSS default).
293    FarthestCorner,
294}
295
296/// The geometry of a gradient.
297#[derive(Debug, Clone, Copy, PartialEq)]
298pub enum GradientKind {
299    /// Along a line at `angle` (CSS: 0 points up, a quarter turn right).
300    Linear {
301        /// Direction.
302        angle: Radians,
303    },
304    /// Toward a corner (`to top right`): the angle follows the box's
305    /// shape (see [`GradientKind::linear_angle`]).
306    LinearCorner {
307        /// The right corners (else the left ones).
308        right: bool,
309        /// The bottom corners (else the top ones).
310        bottom: bool,
311    },
312    /// Out from a center.
313    Radial {
314        /// A circle (else an ellipse matching the box).
315        circle: bool,
316        /// Ending shape size.
317        size: GradientSize,
318        /// Center, as a fraction of the width.
319        x: Percentage,
320        /// Center, as a fraction of the height.
321        y: Percentage,
322    },
323    /// Around a center, starting at `from`.
324    Conic {
325        /// Start angle (0 is up, clockwise).
326        from: Radians,
327        /// Center, as a fraction of the width.
328        x: Percentage,
329        /// Center, as a fraction of the height.
330        y: Percentage,
331    },
332}
333
334impl GradientKind {
335    /// The CSS angle of a linear gradient over a box of `size`.
336    pub fn linear_angle(&self, size: Size<Points>) -> Option<Radians> {
337        match *self {
338            GradientKind::Linear { angle } => Some(angle),
339            GradientKind::LinearCorner { right, bottom } => {
340                // Perpendicular to the diagonal between the other two
341                // corners (CSS Images 3).
342                let a = (size.height.0.max(f32::EPSILON) / size.width.0.max(f32::EPSILON))
343                    .atan()
344                    .to_degrees();
345                Some(deg(match (right, bottom) {
346                    (true, false) => 90.0 - a,
347                    (true, true) => 90.0 + a,
348                    (false, true) => 270.0 - a,
349                    (false, false) => 270.0 + a,
350                }))
351            }
352            _ => None,
353        }
354    }
355}
356
357/// A stop's position as a fraction of a `line` long: a fraction as it
358/// is, a length (rems at [`REM_SIZE`]) against the line.
359fn stop_fraction(position: DefiniteLength, line: Points) -> f32 {
360    match position {
361        DefiniteLength::Fraction(f) => f.0,
362        DefiniteLength::Absolute(a) => {
363            let p = a.to_points(REM_SIZE);
364            if line.0 > 0.0 {
365                p / line
366            } else if p.0 > 0.0 {
367                // A line of no length (an empty box) draws nothing:
368                // lengths only need to stay in order and finite.
369                1.0
370            } else {
371                0.0
372            }
373        }
374    }
375}
376
377/// A color at a point of a gradient.
378#[derive(Debug, Clone, Copy, PartialEq)]
379pub struct ColorStop {
380    /// Color.
381    pub color: Color,
382    /// Position along the gradient line: a fraction of it (`50%`; a
383    /// conic gradient's angles as fractions of a turn: `90deg` is 0.25),
384    /// or a length from its start (`10px`), resolved against its length
385    /// ([`Gradient::line_length`]) where the box is known. `None` is
386    /// spread evenly between its neighbors.
387    pub position: Option<DefiniteLength>,
388}
389
390/// A gradient image (`backgroundImage`, `maskImage`).
391#[derive(Debug, Clone, PartialEq)]
392pub struct Gradient {
393    /// Geometry.
394    pub kind: GradientKind,
395    /// At least two stops.
396    pub stops: Vec<ColorStop>,
397    /// Repeats past the last stop.
398    pub repeating: bool,
399}
400
401/// A stop at no position of its own: spread evenly between its neighbors.
402impl From<Hsla> for ColorStop {
403    fn from(color: Hsla) -> Self {
404        ColorStop {
405            color: color.into(),
406            position: None,
407        }
408    }
409}
410
411/// A stop at a fraction of the gradient line (`percentage(0.2)`) or a
412/// length from its start (`px(12.0)`).
413impl<P: Into<DefiniteLength>> From<(Hsla, P)> for ColorStop {
414    fn from((color, position): (Hsla, P)) -> Self {
415        ColorStop {
416            color: color.into(),
417            position: Some(position.into()),
418        }
419    }
420}
421
422impl<T: Into<ColorStop>, const N: usize> crate::element::IntoReactive<Vec<ColorStop>> for [T; N] {
423    fn into_reactive(self) -> crate::element::Reactive<Vec<ColorStop>> {
424        crate::element::Reactive::Static(self.into_iter().map(Into::into).collect())
425    }
426}
427
428impl<T: Into<ColorStop>> crate::element::IntoReactive<Vec<ColorStop>> for Vec<T> {
429    fn into_reactive(self) -> crate::element::Reactive<Vec<ColorStop>> {
430        crate::element::Reactive::Static(self.into_iter().map(Into::into).collect())
431    }
432}
433
434impl Gradient {
435    /// The gradient `t` of the way to `to` (`t` beyond 0..1 overshoots):
436    /// each stop's color (in premultiplied RGBA, as CSS mixes them) and
437    /// position, and the geometry's angle and center. `None` when the two
438    /// do not interpolate and `to` applies at once, as CSS's discrete
439    /// interpolation does: different kinds, sizes or repeating, a different
440    /// number of stops, a linear gradient toward a different corner, or a
441    /// stop placed in one and not the other, or as a fraction in one and a
442    /// length in the other.
443    pub fn lerp(&self, to: &Self, t: f32) -> Option<Self> {
444        if self.repeating != to.repeating || self.stops.len() != to.stops.len() {
445            return None;
446        }
447        let l = |a: f32, b: f32| a + (b - a) * t;
448        let kind = match (self.kind, to.kind) {
449            (GradientKind::Linear { angle: a }, GradientKind::Linear { angle: b }) => {
450                GradientKind::Linear {
451                    angle: Radians(l(a.0, b.0)),
452                }
453            }
454            (a @ GradientKind::LinearCorner { .. }, b) if a == b => a,
455            (
456                GradientKind::Radial {
457                    circle,
458                    size,
459                    x: ax,
460                    y: ay,
461                },
462                GradientKind::Radial {
463                    circle: bc,
464                    size: bs,
465                    x: bx,
466                    y: by,
467                },
468            ) if circle == bc && size == bs => GradientKind::Radial {
469                circle,
470                size,
471                x: Percentage(l(ax.0, bx.0)),
472                y: Percentage(l(ay.0, by.0)),
473            },
474            (
475                GradientKind::Conic {
476                    from: af,
477                    x: ax,
478                    y: ay,
479                },
480                GradientKind::Conic {
481                    from: bf,
482                    x: bx,
483                    y: by,
484                },
485            ) => GradientKind::Conic {
486                from: Radians(l(af.0, bf.0)),
487                x: Percentage(l(ax.0, bx.0)),
488                y: Percentage(l(ay.0, by.0)),
489            },
490            _ => return None,
491        };
492        let stops = self
493            .stops
494            .iter()
495            .zip(&to.stops)
496            .map(|(a, b)| {
497                let position = match (a.position, b.position) {
498                    (None, None) => None,
499                    (Some(DefiniteLength::Fraction(pa)), Some(DefiniteLength::Fraction(pb))) => {
500                        Some(DefiniteLength::Fraction(Percentage(l(pa.0, pb.0))))
501                    }
502                    (Some(DefiniteLength::Absolute(pa)), Some(DefiniteLength::Absolute(pb))) => {
503                        let (pa, pb) = (pa.to_points(REM_SIZE), pb.to_points(REM_SIZE));
504                        Some(DefiniteLength::Absolute(AbsoluteLength::Points(Points(l(
505                            pa.0, pb.0,
506                        )))))
507                    }
508                    _ => return None,
509                };
510                Some(ColorStop {
511                    color: crate::transition::lerp_color(a.color, b.color, t),
512                    position,
513                })
514            })
515            .collect::<Option<Vec<_>>>()?;
516        Some(Gradient {
517            kind,
518            stops,
519            repeating: self.repeating,
520        })
521    }
522
523    /// Whether a stop is placed in points, so the stops depend on the
524    /// size of the box ([`Gradient::resolved_stops`]).
525    pub fn has_lengths(&self) -> bool {
526        self.stops
527            .iter()
528            .any(|s| matches!(s.position, Some(DefiniteLength::Absolute(_))))
529    }
530
531    /// The length of the gradient line over a box of `size`, what
532    /// lengths of stops are fractions of (CSS Images 3): a linear
533    /// gradient's line through the center, long enough that the corners
534    /// get the end colors; a radial gradient's ray to the right, from the
535    /// center to the ending shape; 0 for a conic gradient, whose stops
536    /// are angles.
537    pub fn line_length(&self, size: Size<Points>) -> Points {
538        let (w, h) = (size.width.0, size.height.0);
539        Points(match self.kind {
540            GradientKind::Radial {
541                circle,
542                size: shape,
543                x,
544                y,
545            } => radial_radii(circle, shape, x.0 * w, y.0 * h, w, h).0,
546            GradientKind::Conic { .. } => 0.0,
547            kind => {
548                let angle = kind.linear_angle(size).unwrap_or(deg(180.0));
549                let (s, c) = angle.sin_cos();
550                (w * s).abs() + (h * c).abs()
551            }
552        })
553    }
554
555    /// Stop positions over a box of `size` as fractions of the gradient
556    /// line, resolved as CSS does: lengths against the line's length,
557    /// missing ones spread evenly, each at least the one before it.
558    pub fn resolved_stops(&self, size: Size<Points>) -> Vec<(Color, Percentage)> {
559        let mut out = Vec::with_capacity(self.stops.len());
560        self.resolve_stops(size, &mut out);
561        out
562    }
563
564    /// [`Gradient::resolved_stops`] into a reused buffer.
565    pub fn resolve_stops(&self, size: Size<Points>, out: &mut Vec<(Color, Percentage)>) {
566        let line = if self.has_lengths() {
567            self.line_length(size)
568        } else {
569            Points::ZERO
570        };
571        out.clear();
572        out.extend(self.stops.iter().map(|s| {
573            let at = s.position.map_or(f32::NAN, |p| stop_fraction(p, line));
574            (s.color, Percentage(at))
575        }));
576        let n = out.len();
577        if n == 0 {
578            return;
579        }
580        if out[0].1.is_nan() {
581            out[0].1 = Percentage(0.0);
582        }
583        if out[n - 1].1.is_nan() {
584            out[n - 1].1 = Percentage(1.0);
585        }
586        // From 0, not -∞: released apps' negative stops resolve to 0, as
587        // they always have (docs/dev/compatibility.md, rule 4).
588        let mut max = Percentage(0.0);
589        for s in out.iter_mut().filter(|s| !s.1.is_nan()) {
590            max = max.max(s.1);
591            s.1 = max;
592        }
593        let mut i = 1;
594        while i < n {
595            if !out[i].1.is_nan() {
596                i += 1;
597                continue;
598            }
599            let start = i - 1;
600            let mut end = i;
601            while out[end].1.is_nan() {
602                end += 1;
603            }
604            let (a, b) = (out[start].1, out[end].1);
605            for (k, s) in out[i..end].iter_mut().enumerate() {
606                s.1 = Percentage(a.0 + (b.0 - a.0) * (k + 1) as f32 / (end - start) as f32);
607            }
608            i = end;
609        }
610    }
611
612    /// The stops over a box of `size` as a toolkit gradient that repeats
613    /// nothing and takes stops within `0..=1` (Core Animation's, Android's
614    /// shaders) draws them over `0..reach` of the gradient line (1: the
615    /// whole line of a linear or conic gradient; a radial gradient's rings
616    /// go on past its ending shape, to the box's farthest corner): the
617    /// positions as fractions of `reach`. A repeating gradient's stops are
618    /// repeated over all of it, with period last − first, both ways (CSS
619    /// Images 3), and cut at both ends with the colors there. A
620    /// non-repeating gradient's, or one whose period is too short to
621    /// repeat, are [`Gradient::resolved_stops`].
622    pub fn unrolled_stops(
623        &self,
624        size: Size<Points>,
625        reach: Percentage,
626    ) -> Vec<(Color, Percentage)> {
627        let stops = self.resolved_stops(size);
628        let reach = reach.0.max(f32::EPSILON);
629        let mut out = match self
630            .repeating
631            .then(|| repeat_stops(&stops, reach))
632            .flatten()
633        {
634            Some(tiled) => cut_stops(&tiled, Percentage(reach)),
635            None => stops,
636        };
637        if reach != 1.0 {
638            for s in &mut out {
639                s.1 = Percentage(s.1.0 / reach);
640            }
641        }
642        out
643    }
644}
645
646/// Most stops [`Gradient::unrolled_stops`] repeats a gradient's into: a
647/// period of 1pt along a long line fits, a vanishing one is drawn once.
648const MAX_UNROLLED_STOPS: usize = 16_384;
649
650/// The copies of `stops` (ascending fractions of the line), one period
651/// (last − first) apart, that reach into `0..reach`: from the one ending
652/// before it to the one starting after it. `None` for a period too short
653/// to repeat, or more copies than [`MAX_UNROLLED_STOPS`] holds.
654fn repeat_stops(stops: &[(Color, Percentage)], reach: f32) -> Option<Vec<(Color, Percentage)>> {
655    let (first, last) = (stops.first()?.1.0, stops.last()?.1.0);
656    let period = last - first;
657    if period <= 1e-4 {
658        return None;
659    }
660    let start = ((0.0 - last) / period).floor();
661    let end = ((reach - first) / period).ceil();
662    let copies = end - start + 1.0;
663    if copies * stops.len() as f32 > MAX_UNROLLED_STOPS as f32 {
664        return None;
665    }
666    let mut out: Vec<(Color, Percentage)> = (start as i32..=end as i32)
667        .flat_map(|k| {
668            let shift = k as f32 * period;
669            stops
670                .iter()
671                .map(move |&(c, p)| (c, Percentage(p.0 + shift)))
672        })
673        .collect();
674    // A copy's first stop may round to a hair before the last one's.
675    let mut max = Percentage(f32::NEG_INFINITY);
676    for s in &mut out {
677        max = max.max(s.1);
678        s.1 = max;
679    }
680    Some(out)
681}
682
683/// `stops` (ascending positions) cut to `0..=reach`: those inside as they
684/// are, and at each end the color there, between the stops around it (at
685/// a hard edge, two stops at one position, the later one's).
686pub(crate) fn cut_stops(
687    stops: &[(Color, Percentage)],
688    reach: Percentage,
689) -> Vec<(Color, Percentage)> {
690    let color_at = |t: f32| {
691        let Some(i) = stops.iter().rposition(|s| s.1.0 <= t) else {
692            return stops.first().map_or(Color::TRANSPARENT, |s| s.0);
693        };
694        match stops.get(i + 1) {
695            Some(&(c, p)) if p.0 > stops[i].1.0 => {
696                mix(stops[i].0, c, (t - stops[i].1.0) / (p.0 - stops[i].1.0))
697            }
698            _ => stops[i].0,
699        }
700    };
701    let mut out = Vec::with_capacity(stops.len() + 2);
702    out.push((color_at(0.0), Percentage(0.0)));
703    out.extend(stops.iter().copied().filter(|s| s.1.0 > 0.0 && s.1 < reach));
704    out.push((color_at(reach.0), reach));
705    out
706}
707
708/// `a` mixed with `b` by `t` (0: `a`) with premultiplied alpha, as CSS
709/// interpolates gradients: a fade to transparent keeps its hue.
710fn mix(a: Color, b: Color, t: f32) -> Color {
711    let channel = |c: Color, shift: u32| ((c.0 >> shift) & 0xff) as f32;
712    let (alpha_a, alpha_b) = (channel(a, 0), channel(b, 0));
713    let alpha = alpha_a + (alpha_b - alpha_a) * t;
714    let color = |shift: u32| {
715        if alpha <= 0.0 {
716            return 0;
717        }
718        let (x, y) = (channel(a, shift) * alpha_a, channel(b, shift) * alpha_b);
719        ((x + (y - x) * t) / alpha).round().clamp(0.0, 255.0) as u32
720    };
721    let alpha_byte = alpha.round().clamp(0.0, 255.0) as u32;
722    Color((color(24) << 24) | (color(16) << 16) | (color(8) << 8) | alpha_byte)
723}
724
725/// The radii of a radial gradient's ending shape centered at `cx`, `cy`
726/// in a `w` × `h` box.
727fn radial_radii(circle: bool, size: GradientSize, cx: f32, cy: f32, w: f32, h: f32) -> (f32, f32) {
728    let near = (cx.min(w - cx).abs(), cy.min(h - cy).abs());
729    let far = (cx.max(w - cx).abs(), cy.max(h - cy).abs());
730    if circle {
731        let r = match size {
732            GradientSize::ClosestSide => near.0.min(near.1),
733            GradientSize::FarthestSide => far.0.max(far.1),
734            GradientSize::ClosestCorner => near.0.hypot(near.1),
735            GradientSize::FarthestCorner => far.0.hypot(far.1),
736        };
737        return (r, r);
738    }
739    // An ellipse to a corner keeps the side ellipse's aspect ratio.
740    let s = std::f32::consts::SQRT_2;
741    match size {
742        GradientSize::ClosestSide => near,
743        GradientSize::FarthestSide => far,
744        GradientSize::ClosestCorner => (near.0 * s, near.1 * s),
745        GradientSize::FarthestCorner => (far.0 * s, far.1 * s),
746    }
747}
748
749/// One function of `filter` / `backdropFilter`.
750#[derive(Debug, Clone, Copy, PartialEq)]
751pub enum Filter {
752    /// Gaussian blur radius.
753    Blur(Points),
754    /// 1 is unchanged.
755    Brightness(f32),
756    /// 1 is unchanged.
757    Contrast(f32),
758    /// 0..1.
759    Grayscale(f32),
760    /// The hue's rotation.
761    HueRotate(Radians),
762    /// 0..1.
763    Invert(f32),
764    /// 0..1.
765    Opacity(f32),
766    /// 1 is unchanged.
767    Saturate(f32),
768    /// 0..1.
769    Sepia(f32),
770    /// A shadow of the content's shape.
771    DropShadow {
772        /// Horizontal offset.
773        offset_x: Points,
774        /// Vertical offset.
775        offset_y: Points,
776        /// Blur radius.
777        blur: Points,
778        /// Color.
779        color: Color,
780    },
781}
782
783impl Filter {
784    /// The 4×5 color matrix (row major, sRGB, offsets in 0..1) of a color
785    /// filter; `None` for blur and drop shadows.
786    pub fn color_matrix(&self) -> Option<[f32; 20]> {
787        let id = |r: [f32; 3], g: [f32; 3], b: [f32; 3]| {
788            [
789                r[0], r[1], r[2], 0.0, 0.0, g[0], g[1], g[2], 0.0, 0.0, b[0], b[1], b[2], 0.0, 0.0,
790                0.0, 0.0, 0.0, 1.0, 0.0,
791            ]
792        };
793        Some(match *self {
794            Filter::Brightness(v) => id([v, 0.0, 0.0], [0.0, v, 0.0], [0.0, 0.0, v]),
795            Filter::Contrast(v) => {
796                let t = (1.0 - v) / 2.0;
797                [
798                    v, 0.0, 0.0, 0.0, t, 0.0, v, 0.0, 0.0, t, 0.0, 0.0, v, 0.0, t, 0.0, 0.0, 0.0,
799                    1.0, 0.0,
800                ]
801            }
802            Filter::Grayscale(v) => {
803                let a = 1.0 - v;
804                id(
805                    [
806                        0.2126 + 0.7874 * a,
807                        0.7152 - 0.7152 * a,
808                        0.0722 - 0.0722 * a,
809                    ],
810                    [
811                        0.2126 - 0.2126 * a,
812                        0.7152 + 0.2848 * a,
813                        0.0722 - 0.0722 * a,
814                    ],
815                    [
816                        0.2126 - 0.2126 * a,
817                        0.7152 - 0.7152 * a,
818                        0.0722 + 0.9278 * a,
819                    ],
820                )
821            }
822            Filter::Sepia(v) => {
823                let a = 1.0 - v;
824                id(
825                    [0.393 + 0.607 * a, 0.769 - 0.769 * a, 0.189 - 0.189 * a],
826                    [0.349 - 0.349 * a, 0.686 + 0.314 * a, 0.168 - 0.168 * a],
827                    [0.272 - 0.272 * a, 0.534 - 0.534 * a, 0.131 + 0.869 * a],
828                )
829            }
830            Filter::Saturate(s) => id(
831                [0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s],
832                [0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s],
833                [0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s],
834            ),
835            Filter::HueRotate(angle) => {
836                let (s, c) = angle.sin_cos();
837                id(
838                    [
839                        0.213 + c * 0.787 - s * 0.213,
840                        0.715 - c * 0.715 - s * 0.715,
841                        0.072 - c * 0.072 + s * 0.928,
842                    ],
843                    [
844                        0.213 - c * 0.213 + s * 0.143,
845                        0.715 + c * 0.285 + s * 0.140,
846                        0.072 - c * 0.072 - s * 0.283,
847                    ],
848                    [
849                        0.213 - c * 0.213 - s * 0.787,
850                        0.715 - c * 0.715 + s * 0.715,
851                        0.072 + c * 0.928 + s * 0.072,
852                    ],
853                )
854            }
855            Filter::Invert(v) => {
856                let m = 1.0 - 2.0 * v;
857                [
858                    m, 0.0, 0.0, 0.0, v, 0.0, m, 0.0, 0.0, v, 0.0, 0.0, m, 0.0, v, 0.0, 0.0, 0.0,
859                    1.0, 0.0,
860                ]
861            }
862            Filter::Opacity(v) => [
863                1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
864                0.0, 0.0, v, 0.0,
865            ],
866            Filter::Blur(_) | Filter::DropShadow { .. } => return None,
867        })
868    }
869}
870
871/// The color matrices of `filters` composed in order (the first applies
872/// first), or `None` when none changes colors.
873pub fn compose_color_matrices(filters: &[Filter]) -> Option<[f32; 20]> {
874    let mut out: Option<[f32; 20]> = None;
875    for m in filters.iter().filter_map(Filter::color_matrix) {
876        out = Some(match out {
877            None => m,
878            Some(prev) => {
879                // `m · prev`, with the offset column treated as a 5th
880                // homogeneous coordinate.
881                let mut r = [0.0; 20];
882                for row in 0..4 {
883                    for col in 0..5 {
884                        let mut v = if col == 4 { m[row * 5 + 4] } else { 0.0 };
885                        for k in 0..4 {
886                            v += m[row * 5 + k] * prev[k * 5 + col];
887                        }
888                        r[row * 5 + col] = v;
889                    }
890                }
891                r
892            }
893        });
894    }
895    out
896}
897
898/// The total blur radius of `filters`.
899pub fn blur_radius(filters: &[Filter]) -> Points {
900    filters
901        .iter()
902        .map(|f| match f {
903            Filter::Blur(r) => *r,
904            _ => Points::ZERO,
905        })
906        .sum()
907}
908
909/// `ios={{ backdropMaterial }}`: the system material a `backdropFilter` blur draws.
910///
911/// iOS blurs a backdrop with a material rather than a plain Gaussian blur:
912/// each one blurs and tints by a fixed amount, and the thicker it is, the
913/// less of what is behind it comes through. A navigation bar over scrolling
914/// content usually wants a thicker one than the thinnest, which on its own
915/// is too faint to keep its contents legible.
916///
917/// There is no CSS for this -- `backdrop-filter` only describes filters --
918/// so the names follow Apple's `UIBlurEffectStyle.system*Material`.
919///
920/// Read on iOS, where it picks the material; the blur's radius still sets
921/// how strongly it is applied, as an approximation rather than a Gaussian radius.
922#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
923pub enum BackdropMaterial {
924    /// The thinnest material, the most of what is behind coming through.
925    #[default]
926    UltraThin,
927    /// Thin.
928    Thin,
929    /// The standard material.
930    Regular,
931    /// Thick, letting little through.
932    Thick,
933    /// The material of system chrome, such as a toolbar.
934    Chrome,
935}
936
937impl BackdropMaterial {
938    /// The iOS prop name ([`BackdropMaterial::parse`]'s input).
939    pub fn name(self) -> &'static str {
940        match self {
941            BackdropMaterial::UltraThin => "ultraThin",
942            BackdropMaterial::Thin => "thin",
943            BackdropMaterial::Regular => "regular",
944            BackdropMaterial::Thick => "thick",
945            BackdropMaterial::Chrome => "chrome",
946        }
947    }
948
949    /// Parses a material name.
950    pub fn parse(s: &str) -> Option<BackdropMaterial> {
951        Some(match s {
952            "ultraThin" => BackdropMaterial::UltraThin,
953            "thin" => BackdropMaterial::Thin,
954            "regular" => BackdropMaterial::Regular,
955            "thick" => BackdropMaterial::Thick,
956            "chrome" => BackdropMaterial::Chrome,
957            _ => return None,
958        })
959    }
960}
961
962/// `macos={{ backdrop }}`: the `NSVisualEffectView` material a view draws with
963/// on macOS.
964///
965/// Unlike iOS's [`BackdropMaterial`], which always blurs a `backdropFilter`,
966/// this is a material of its own: an explicit backdrop draws its native
967/// view whether or not the style has a blur, and it wins over
968/// [`GlassEffect`] and `backdropFilter` on macOS. Its fields default to
969/// `popover`, `withinWindow` and `active`, the blur macOS has always drawn.
970///
971/// There is no CSS for this -- `backdrop-filter` only describes filters --
972/// so the names follow AppKit's `NSVisualEffectMaterial`,
973/// `NSVisualEffectBlendingMode` and `NSVisualEffectState` in camel case.
974///
975/// Fields may be added: start with [`Self::default`] and set what it
976/// needs.
977#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
978#[non_exhaustive]
979pub struct MacOsBackdrop {
980    /// The material: what is blurred and how it is tinted.
981    pub material: MacOsBackdropMaterial,
982    /// What it blurs: the view's window, or what is behind the window.
983    pub blending: MacOsBackdropBlending,
984    /// Whether it follows the window's active state, or is always active
985    /// or inactive.
986    pub state: MacOsBackdropState,
987}
988
989/// `NSVisualEffectMaterial`: the material of a [`MacOsBackdrop`].
990///
991/// The roles AppKit still documents: the newer content and under-window
992/// roles, and the older named roles apps still use (which AppKit marks
993/// deprecated in favor of the newer ones).
994#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
995pub enum MacOsBackdropMaterial {
996    /// The title bar's material.
997    Titlebar,
998    /// The selected content's material.
999    Selection,
1000    /// A menu's material.
1001    Menu,
1002    /// A popover's material.
1003    #[default]
1004    Popover,
1005    /// A source list's (sidebar's) material.
1006    Sidebar,
1007    /// A table header's material.
1008    HeaderView,
1009    /// A sheet's material.
1010    Sheet,
1011    /// The window's background material.
1012    WindowBackground,
1013    /// A heads-up display's material.
1014    HudWindow,
1015    /// A full-screen UI's material.
1016    FullScreenUI,
1017    /// A tooltip's material.
1018    ToolTip,
1019    /// The content's background material.
1020    ContentBackground,
1021    /// The material under the window's background.
1022    UnderWindowBackground,
1023    /// The material under a page's background.
1024    UnderPageBackground,
1025}
1026
1027/// `NSVisualEffectBlendingMode`: what a [`MacOsBackdrop`] blurs.
1028#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
1029pub enum MacOsBackdropBlending {
1030    /// What is in the view's window behind it.
1031    #[default]
1032    WithinWindow,
1033    /// What is behind the window, so the window must be transparent for
1034    /// it to show.
1035    BehindWindow,
1036}
1037
1038/// `NSVisualEffectState`: whether a [`MacOsBackdrop`] follows the window's
1039/// active state.
1040#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
1041pub enum MacOsBackdropState {
1042    /// Active while the window is, inactive otherwise.
1043    FollowsWindowActiveState,
1044    /// Always active.
1045    #[default]
1046    Active,
1047    /// Always inactive.
1048    Inactive,
1049}
1050
1051/// `windows={{ backdrop }}`: a system backdrop drawn under the view's box
1052/// and corners on Windows 11 and later, below everything the window draws;
1053/// the view's own background draws over it, and tints it when translucent.
1054/// Nothing elsewhere, nor in a window that is not transparent.
1055#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1056#[non_exhaustive]
1057pub struct WindowsBackdrop {
1058    /// The system material to draw behind the view.
1059    pub material: WindowsBackdropMaterial,
1060}
1061
1062/// The material of a [`WindowsBackdrop`].
1063#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
1064#[non_exhaustive]
1065pub enum WindowsBackdropMaterial {
1066    /// The system's blur of what is behind the window, with no tint of its
1067    /// own (a host backdrop brush).
1068    #[default]
1069    Blur,
1070}
1071
1072/// `glassEffect`: a glass material drawn behind the view's content.
1073///
1074/// Apple's "Liquid Glass", new in iOS 26. No CSS property describes it --
1075/// Safari keeps it to the private `-apple-visual-effect`, and the W3C has
1076/// yet to define backdrop refraction (w3c/svgwg#1142) -- so this follows
1077/// React Native's `expo-glass-effect` instead.
1078///
1079/// Drawn on iOS 26 and later. Earlier iOS, and every other platform, draw
1080/// the view's `backdropFilter` as before, so give a glass view a blur to
1081/// fall back to.
1082#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1083pub enum GlassEffect {
1084    /// No glass: `backdropFilter` alone decides what is drawn behind.
1085    #[default]
1086    None,
1087    /// The standard glass material.
1088    Regular,
1089    /// Clearer glass, taking less color from what is behind it.
1090    Clear,
1091}
1092
1093impl GlassEffect {
1094    /// The style name ([`GlassEffect::parse`]'s input).
1095    pub fn name(self) -> &'static str {
1096        match self {
1097            GlassEffect::None => "none",
1098            GlassEffect::Regular => "regular",
1099            GlassEffect::Clear => "clear",
1100        }
1101    }
1102
1103    /// Parses a glass effect name.
1104    pub fn parse(s: &str) -> Option<GlassEffect> {
1105        Some(match s {
1106            "none" => GlassEffect::None,
1107            "regular" => GlassEffect::Regular,
1108            "clear" => GlassEffect::Clear,
1109            _ => return None,
1110        })
1111    }
1112}
1113
1114/// `mixBlendMode`: how the view composites with what is behind it.
1115#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1116#[allow(missing_docs)]
1117pub enum BlendMode {
1118    #[default]
1119    Normal,
1120    Multiply,
1121    Screen,
1122    Overlay,
1123    Darken,
1124    Lighten,
1125    ColorDodge,
1126    ColorBurn,
1127    HardLight,
1128    SoftLight,
1129    Difference,
1130    Exclusion,
1131    Hue,
1132    Saturation,
1133    Color,
1134    Luminosity,
1135    PlusDarker,
1136    PlusLighter,
1137}
1138
1139impl BlendMode {
1140    /// The CSS name ([`BlendMode::parse`]'s input).
1141    pub fn name(self) -> &'static str {
1142        match self {
1143            BlendMode::Normal => "normal",
1144            BlendMode::Multiply => "multiply",
1145            BlendMode::Screen => "screen",
1146            BlendMode::Overlay => "overlay",
1147            BlendMode::Darken => "darken",
1148            BlendMode::Lighten => "lighten",
1149            BlendMode::ColorDodge => "color-dodge",
1150            BlendMode::ColorBurn => "color-burn",
1151            BlendMode::HardLight => "hard-light",
1152            BlendMode::SoftLight => "soft-light",
1153            BlendMode::Difference => "difference",
1154            BlendMode::Exclusion => "exclusion",
1155            BlendMode::Hue => "hue",
1156            BlendMode::Saturation => "saturation",
1157            BlendMode::Color => "color",
1158            BlendMode::Luminosity => "luminosity",
1159            BlendMode::PlusDarker => "plus-darker",
1160            BlendMode::PlusLighter => "plus-lighter",
1161        }
1162    }
1163
1164    /// Parses a CSS blend mode name.
1165    pub fn parse(s: &str) -> Option<BlendMode> {
1166        Some(match s {
1167            "normal" => BlendMode::Normal,
1168            "multiply" => BlendMode::Multiply,
1169            "screen" => BlendMode::Screen,
1170            "overlay" => BlendMode::Overlay,
1171            "darken" => BlendMode::Darken,
1172            "lighten" => BlendMode::Lighten,
1173            "color-dodge" => BlendMode::ColorDodge,
1174            "color-burn" => BlendMode::ColorBurn,
1175            "hard-light" => BlendMode::HardLight,
1176            "soft-light" => BlendMode::SoftLight,
1177            "difference" => BlendMode::Difference,
1178            "exclusion" => BlendMode::Exclusion,
1179            "hue" => BlendMode::Hue,
1180            "saturation" => BlendMode::Saturation,
1181            "color" => BlendMode::Color,
1182            "luminosity" => BlendMode::Luminosity,
1183            "plus-darker" => BlendMode::PlusDarker,
1184            "plus-lighter" => BlendMode::PlusLighter,
1185            _ => return None,
1186        })
1187    }
1188}
1189
1190/// `outline*`: a line around the border box, outside the layout.
1191#[derive(Debug, Clone, Copy, PartialEq)]
1192pub struct Outline {
1193    /// Width (0: none).
1194    pub width: Points,
1195    /// Color.
1196    pub color: Color,
1197    /// Line style.
1198    pub style: BorderStyle,
1199    /// Gap between the border box and the outline (negative: inside).
1200    pub offset: Points,
1201}
1202
1203impl Outline {
1204    /// No outline.
1205    pub const NONE: Outline = Outline {
1206        width: Points::ZERO,
1207        color: Color::BLACK,
1208        style: BorderStyle::Solid,
1209        offset: Points::ZERO,
1210    };
1211
1212    /// True if the outline draws anything.
1213    pub fn is_visible(&self) -> bool {
1214        self.width > Points::ZERO && !self.color.is_transparent()
1215    }
1216}
1217
1218impl Default for Outline {
1219    fn default() -> Self {
1220        Self::NONE
1221    }
1222}
1223
1224/// The pointer's look over a view (`cursor`; iPad, Mac Catalyst and
1225/// Android with a mouse).
1226#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1227#[allow(missing_docs)]
1228pub enum Cursor {
1229    #[default]
1230    Auto,
1231    Default,
1232    Pointer,
1233    Text,
1234    Wait,
1235    Progress,
1236    Help,
1237    Crosshair,
1238    Move,
1239    Grab,
1240    Grabbing,
1241    NotAllowed,
1242    ZoomIn,
1243    ZoomOut,
1244    ColResize,
1245    RowResize,
1246    None,
1247    /// Resize along the northwest–southeast diagonal (`nwse-resize`).
1248    NwseResize,
1249    /// Resize along the northeast–southwest diagonal (`nesw-resize`).
1250    NeswResize,
1251}
1252
1253impl Cursor {
1254    /// Its CSS name ([`Cursor::parse`]'s input).
1255    pub fn name(self) -> &'static str {
1256        match self {
1257            Cursor::Auto => "auto",
1258            Cursor::Default => "default",
1259            Cursor::Pointer => "pointer",
1260            Cursor::Text => "text",
1261            Cursor::Wait => "wait",
1262            Cursor::Progress => "progress",
1263            Cursor::Help => "help",
1264            Cursor::Crosshair => "crosshair",
1265            Cursor::Move => "move",
1266            Cursor::Grab => "grab",
1267            Cursor::Grabbing => "grabbing",
1268            Cursor::NotAllowed => "not-allowed",
1269            Cursor::ZoomIn => "zoom-in",
1270            Cursor::ZoomOut => "zoom-out",
1271            Cursor::ColResize => "col-resize",
1272            Cursor::RowResize => "row-resize",
1273            Cursor::None => "none",
1274            Cursor::NwseResize => "nwse-resize",
1275            Cursor::NeswResize => "nesw-resize",
1276        }
1277    }
1278
1279    /// Parses a CSS cursor name (resize directions map to their axis).
1280    pub fn parse(s: &str) -> Option<Cursor> {
1281        Some(match s {
1282            "auto" => Cursor::Auto,
1283            "default" | "context-menu" | "alias" | "copy" | "cell" => Cursor::Default,
1284            "pointer" => Cursor::Pointer,
1285            "text" | "vertical-text" => Cursor::Text,
1286            "wait" => Cursor::Wait,
1287            "progress" => Cursor::Progress,
1288            "help" => Cursor::Help,
1289            "crosshair" => Cursor::Crosshair,
1290            "move" | "all-scroll" => Cursor::Move,
1291            "grab" => Cursor::Grab,
1292            "grabbing" => Cursor::Grabbing,
1293            "not-allowed" | "no-drop" => Cursor::NotAllowed,
1294            "zoom-in" => Cursor::ZoomIn,
1295            "zoom-out" => Cursor::ZoomOut,
1296            "col-resize" | "e-resize" | "w-resize" | "ew-resize" => Cursor::ColResize,
1297            "row-resize" | "n-resize" | "s-resize" | "ns-resize" => Cursor::RowResize,
1298            "nw-resize" | "se-resize" | "nwse-resize" => Cursor::NwseResize,
1299            "ne-resize" | "sw-resize" | "nesw-resize" => Cursor::NeswResize,
1300            "none" => Cursor::None,
1301            _ => return None,
1302        })
1303    }
1304}
1305
1306/// Which property groups a [`Transition`] animates.
1307#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1308pub struct TransitionProps(pub u8);
1309
1310impl TransitionProps {
1311    /// Background, border, outline, shadow and text colors.
1312    pub const COLORS: u8 = 1;
1313    /// `opacity`.
1314    pub const OPACITY: u8 = 2;
1315    /// `transform`.
1316    pub const TRANSFORM: u8 = 4;
1317    /// Box shadows.
1318    pub const SHADOW: u8 = 8;
1319    /// Corner radii and border widths.
1320    pub const SHAPE: u8 = 16;
1321    /// `clipPath` (CSS's `clip-path`).
1322    pub const CLIP_PATH: u8 = 32;
1323    /// `maskImage` (CSS's `mask-image`): gradients of the same shape and
1324    /// stop count, stop by stop.
1325    pub const MASK: u8 = 64;
1326    /// Everything that can transition.
1327    pub const ALL: u8 = 0x7f;
1328
1329    /// True if `group` is included.
1330    #[inline]
1331    pub fn has(self, group: u8) -> bool {
1332        self.0 & group != 0
1333    }
1334}
1335
1336/// `transition*`: style changes animate natively instead of jumping.
1337#[derive(Debug, Clone, Copy, PartialEq)]
1338#[non_exhaustive]
1339pub struct Transition {
1340    /// Properties that animate.
1341    pub properties: TransitionProps,
1342    /// Milliseconds.
1343    pub duration: f32,
1344    /// Milliseconds before it starts.
1345    pub delay: f32,
1346    /// Cubic Bézier `x1, y1, x2, y2` (a `y` outside 0..1 overshoots).
1347    pub easing: [f32; 4],
1348    /// A spring's physics it runs on instead of `easing`
1349    /// (`transitionTimingFunction: "spring(stiffness, damping, mass)"`),
1350    /// released at rest: it times itself, lasting until it settles
1351    /// ([`Spring::settle_ms`](crate::element::Spring::settle_ms)), so
1352    /// `duration` is not used, nor the spring's `velocity` and
1353    /// `frame_rate`. A change that arrives mid-way starts again from what
1354    /// is on screen, at rest.
1355    pub spring: Option<crate::element::Spring>,
1356}
1357
1358impl Default for Transition {
1359    /// CSS's initial values: every property, no time, `ease`.
1360    fn default() -> Self {
1361        Self {
1362            properties: TransitionProps(TransitionProps::ALL),
1363            duration: 0.0,
1364            delay: 0.0,
1365            easing: Self::EASE,
1366            spring: None,
1367        }
1368    }
1369}
1370
1371impl Transition {
1372    /// CSS's default curve (`ease`).
1373    pub const EASE: [f32; 4] = [0.25, 0.1, 0.25, 1.0];
1374
1375    /// How long it runs once started, in milliseconds: the duration, or
1376    /// the time its spring takes to settle (its delay not included).
1377    pub fn run_ms(&self) -> f32 {
1378        match self.spring {
1379            Some(spring) => spring.settle_ms(),
1380            None => self.duration.max(0.0),
1381        }
1382    }
1383}
1384
1385/// A built-in keyframe animation (Tailwind's `animate-*`).
1386#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1387pub enum Keyframes {
1388    /// One turn clockwise.
1389    Spin,
1390    /// Scales up to 2× and fades out.
1391    Ping,
1392    /// Fades to half opacity and back.
1393    Pulse,
1394    /// Jumps up by a quarter of its height and lands.
1395    Bounce,
1396}
1397
1398/// `animation*`: a keyframe animation running natively, forever by default.
1399#[derive(Debug, Clone, Copy, PartialEq)]
1400pub struct KeyframeAnimation {
1401    /// What runs.
1402    pub keyframes: Keyframes,
1403    /// Milliseconds per iteration.
1404    pub duration: f32,
1405    /// Milliseconds before it starts.
1406    pub delay: f32,
1407    /// Cubic Bézier `x1, y1, x2, y2` (Bounce uses its own per half).
1408    pub easing: [f32; 4],
1409    /// `None` repeats forever.
1410    pub iterations: Option<u32>,
1411    /// The highest frame rate it needs, in Hz (`animationFrameRate`);
1412    /// `None`: the screen's highest. Platforms that can lower their frame
1413    /// rate honor it.
1414    pub frame_rate: Option<f32>,
1415}
1416
1417impl KeyframeAnimation {
1418    /// `keyframes` as TS's `animationName` alone runs them: a second per
1419    /// iteration at a constant pace, forever.
1420    pub const fn new(keyframes: Keyframes) -> Self {
1421        Self {
1422            keyframes,
1423            duration: 1000.0,
1424            delay: 0.0,
1425            easing: [0.0, 0.0, 1.0, 1.0],
1426            iterations: None,
1427            frame_rate: None,
1428        }
1429    }
1430
1431    /// `ms` milliseconds per iteration.
1432    pub const fn duration(mut self, ms: f32) -> Self {
1433        self.duration = ms;
1434        self
1435    }
1436
1437    /// Starts after `ms` milliseconds.
1438    pub const fn delay(mut self, ms: f32) -> Self {
1439        self.delay = ms;
1440        self
1441    }
1442
1443    /// Along the cubic Bézier curve `x1, y1, x2, y2`.
1444    pub const fn easing(mut self, curve: [f32; 4]) -> Self {
1445        self.easing = curve;
1446        self
1447    }
1448
1449    /// `count` iterations, then it stops.
1450    pub const fn iterations(mut self, count: u32) -> Self {
1451        self.iterations = Some(count);
1452        self
1453    }
1454
1455    /// Needs at most `hz` frames per second (a slow spinner: 30), so the
1456    /// screen may refresh less often while it is all that moves.
1457    pub const fn frame_rate(mut self, hz: f32) -> Self {
1458        self.frame_rate = Some(hz);
1459        self
1460    }
1461}
1462
1463/// The list-valued effects of a view, shared between equal styles.
1464#[derive(Debug, Clone, PartialEq, Default)]
1465pub struct Effects {
1466    /// Box shadows, top layer first (CSS order).
1467    pub box_shadows: Vec<BoxShadow>,
1468    /// Gradient backgrounds, top layer first, over `backgroundColor`.
1469    pub background_images: Vec<Gradient>,
1470    /// Filters applied to the view and its content, in order.
1471    pub filters: Vec<Filter>,
1472    /// Filters applied to what is behind the view (blur only on iOS).
1473    pub backdrop_filters: Vec<Filter>,
1474    /// `maskImage`: gradients whose alpha decides how much of the view is
1475    /// drawn, top layer first (CSS order). Only gradients: CSS also takes
1476    /// images and shapes here, which no platform of NSH draws yet.
1477    pub mask_images: Vec<Gradient>,
1478    /// `clipPath`: the inset rounded rectangle everything the view draws is
1479    /// clipped to, and outside which nothing of it is hit.
1480    pub clip_path: Option<ClipInset>,
1481}
1482
1483impl Effects {
1484    /// True if nothing is set.
1485    pub fn is_empty(&self) -> bool {
1486        self.box_shadows.is_empty()
1487            && self.background_images.is_empty()
1488            && self.filters.is_empty()
1489            && self.backdrop_filters.is_empty()
1490            && self.mask_images.is_empty()
1491            && self.clip_path.is_none()
1492    }
1493}
1494
1495/// [`Effects`] behind a cheap shared pointer (`None` when empty).
1496pub(crate) fn shared(effects: Effects) -> Option<Arc<Effects>> {
1497    (!effects.is_empty()).then(|| Arc::new(effects))
1498}
1499
1500#[cfg(test)]
1501mod tests {
1502    use super::*;
1503    use crate::geometry::{percentage, px, size};
1504
1505    #[test]
1506    fn a_clip_inset_resolves_as_css_does() {
1507        let at =
1508            |x: f32, y: f32, w: f32, h: f32| Bounds::new(point(px(x), px(y)), size(px(w), px(h)));
1509        let box_ = size(px(200.0), px(100.0));
1510        // Percentages of the width (left, right) and the height (top, bottom).
1511        let clip = ClipInset::new()
1512            .top(percentage(0.1))
1513            .right(px(20.0))
1514            .bottom(px(30.0))
1515            .left(percentage(0.25));
1516        assert_eq!(clip.resolve(box_).0, at(50.0, 10.0, 130.0, 60.0));
1517        // Opposite edges that would pass each other meet, in proportion.
1518        let past = ClipInset::new()
1519            .left(percentage(0.75))
1520            .right(percentage(0.75));
1521        assert_eq!(past.resolve(box_).0, at(100.0, 0.0, 0.0, 100.0));
1522        // Negative edges reach out of the box.
1523        assert_eq!(
1524            ClipInset::new().inset(px(-8.0)).resolve(box_).0,
1525            at(-8.0, -8.0, 216.0, 116.0)
1526        );
1527        // Radii that do not fit are scaled down together, as a border's.
1528        let pill = ClipInset::new().top(px(40.0)).rounded(px(100.0));
1529        let (rect, radii) = pill.resolve(box_);
1530        assert_eq!(rect, at(0.0, 40.0, 200.0, 60.0));
1531        assert!(
1532            radii.to_array().iter().all(|r| (r.0 - 30.0).abs() < 1e-4),
1533            "{radii:?}"
1534        );
1535    }
1536
1537    #[test]
1538    fn a_clip_inset_contains_what_its_rounded_corners_leave() {
1539        let box_ = size(px(100.0), px(100.0));
1540        let clip = ClipInset::new().inset(px(10.0)).rounded(px(20.0));
1541        assert!(clip.contains(box_, point(px(50.0), px(50.0))));
1542        // The inset edges.
1543        assert!(!clip.contains(box_, point(px(5.0), px(50.0))));
1544        assert!(!clip.contains(box_, point(px(50.0), px(95.0))));
1545        // Each corner's square, outside its circle and inside it.
1546        for (out, inside) in [
1547            ((12.0, 12.0), (18.0, 18.0)),
1548            ((88.0, 12.0), (82.0, 18.0)),
1549            ((88.0, 88.0), (82.0, 82.0)),
1550            ((12.0, 88.0), (18.0, 82.0)),
1551        ] {
1552            assert!(!clip.contains(box_, point(px(out.0), px(out.1))), "{out:?}");
1553            assert!(
1554                clip.contains(box_, point(px(inside.0), px(inside.1))),
1555                "{inside:?}"
1556            );
1557        }
1558        // Shut to nothing, nothing is inside.
1559        let shut = ClipInset::new()
1560            .bottom(percentage(1.0))
1561            .left(percentage(1.0));
1562        assert!(!shut.contains(box_, point(px(99.0), px(0.0))));
1563    }
1564
1565    #[test]
1566    fn a_clip_inset_outline_keeps_its_segments() {
1567        use crate::shape::Segment;
1568        let kinds = |clip: ClipInset| {
1569            let mut out = Vec::new();
1570            clip.outline(size(px(100.0), px(50.0)), &mut |s| {
1571                out.push(std::mem::discriminant(&s));
1572            });
1573            out
1574        };
1575        // Shut to nothing with square corners, or open and rounded: the
1576        // same segments, so a path animates from one to the other.
1577        let shut = ClipInset::new()
1578            .bottom(percentage(1.0))
1579            .left(percentage(1.0));
1580        let open = ClipInset::new().rounded(px(12.0));
1581        assert_eq!(kinds(shut), kinds(open));
1582        assert_eq!(kinds(open).len(), 10);
1583        let mut last = None;
1584        open.outline(size(px(100.0), px(50.0)), &mut |s| {
1585            if let Segment::Cubic([_, _, to]) = s {
1586                last = Some(to);
1587            }
1588        });
1589        // It ends where it started, past the top left corner's arc.
1590        assert_eq!(last, Some(point(px(12.0), px(0.0))));
1591    }
1592
1593    #[test]
1594    fn a_clip_inset_interpolates_lengths_and_percentages_together() {
1595        let from = ClipInset::new()
1596            .bottom(percentage(1.0))
1597            .left(px(40.0))
1598            .rounded(px(0.0));
1599        let to = ClipInset::new().bottom(px(10.0)).rounded(px(16.0));
1600        let half = from.lerp(&to, 0.5);
1601        // CSS's calc(): half of each, the length and the percentage apart.
1602        assert_eq!(
1603            (half.offsets.bottom, half.fractions.bottom),
1604            (px(5.0), percentage(0.5))
1605        );
1606        assert_eq!(
1607            (half.offsets.left, half.fractions.left),
1608            (px(20.0), percentage(0.0))
1609        );
1610        assert_eq!(half.radii, Corners::all(px(8.0)));
1611        assert_eq!(
1612            half.resolve(size(px(100.0), px(100.0))).0.size.height,
1613            px(45.0)
1614        );
1615        // An overshooting curve never makes a radius negative.
1616        assert_eq!(from.lerp(&to, -0.5).radii, Corners::all(px(0.0)));
1617        assert_eq!(from.lerp(&to, 1.0), to);
1618    }
1619
1620    #[test]
1621    fn stops_spread_evenly() {
1622        let c = Color::BLACK;
1623        let g = Gradient {
1624            kind: GradientKind::Linear { angle: deg(90.0) },
1625            stops: vec![
1626                ColorStop {
1627                    color: c,
1628                    position: None,
1629                },
1630                ColorStop {
1631                    color: c,
1632                    position: None,
1633                },
1634                ColorStop {
1635                    color: c,
1636                    position: Some(DefiniteLength::from(percentage(0.8))),
1637                },
1638                ColorStop {
1639                    color: c,
1640                    position: Some(DefiniteLength::from(percentage(0.5))),
1641                },
1642            ],
1643            repeating: false,
1644        };
1645        let p: Vec<f32> = g
1646            .resolved_stops(size(px(100.0), px(100.0)))
1647            .into_iter()
1648            .map(|(_, p)| p.0)
1649            .collect();
1650        assert_eq!(p, [0.0, 0.4, 0.8, 0.8]);
1651    }
1652
1653    #[test]
1654    fn negative_stops_resolve_to_zero() {
1655        let stop = |p: f32| ColorStop {
1656            color: Color::BLACK,
1657            position: Some(DefiniteLength::from(percentage(p))),
1658        };
1659        let mut g = Gradient {
1660            kind: GradientKind::Linear { angle: deg(180.0) },
1661            stops: vec![stop(-0.5), stop(1.0)],
1662            repeating: false,
1663        };
1664        let positions = |g: &Gradient| -> Vec<f32> {
1665            g.resolved_stops(size(px(100.0), px(40.0)))
1666                .into_iter()
1667                .map(|(_, p)| p.0)
1668                .collect()
1669        };
1670        assert_eq!(positions(&g), [0.0, 1.0]);
1671        g.stops = vec![
1672            stop(-0.5),
1673            ColorStop {
1674                color: Color::BLACK,
1675                position: Some(DefiniteLength::from(px(-20.0))),
1676            },
1677            stop(1.0),
1678        ];
1679        assert_eq!(positions(&g), [0.0, 0.0, 1.0]);
1680    }
1681
1682    #[test]
1683    fn lengths_resolve_against_the_line() {
1684        let c = Color::BLACK;
1685        let stop = |p: Option<DefiniteLength>| ColorStop {
1686            color: c,
1687            position: p,
1688        };
1689        let mut g = Gradient {
1690            kind: GradientKind::Linear { angle: deg(90.0) },
1691            stops: vec![
1692                stop(Some(DefiniteLength::from(px(0.0)))),
1693                stop(Some(DefiniteLength::from(px(10.0)))),
1694                stop(None),
1695                stop(Some(DefiniteLength::from(percentage(0.5)))),
1696            ],
1697            repeating: true,
1698        };
1699        assert!(g.has_lengths());
1700        // Across a 200 × 50 box: the line is the width.
1701        let p: Vec<f32> = g
1702            .resolved_stops(size(px(200.0), px(50.0)))
1703            .into_iter()
1704            .map(|(_, p)| p.0)
1705            .collect();
1706        assert_eq!(p, [0.0, 0.05, 0.275, 0.5]);
1707        // Down: the height.
1708        g.kind = GradientKind::Linear { angle: deg(180.0) };
1709        assert!((g.resolved_stops(size(px(200.0), px(50.0)))[1].1.0 - 0.2).abs() < 1e-6);
1710        // Diagonal over a square: the diagonal.
1711        g.kind = GradientKind::Linear { angle: deg(45.0) };
1712        let line = g.line_length(size(px(100.0), px(100.0)));
1713        assert!((line.0 - 100.0 * std::f32::consts::SQRT_2).abs() < 1e-3);
1714        // Radial: the ray to the ending shape (a circle to the farthest
1715        // side of a 200 × 100 box from its center is 100 points).
1716        g.kind = GradientKind::Radial {
1717            circle: true,
1718            size: GradientSize::FarthestSide,
1719            x: percentage(0.5),
1720            y: percentage(0.5),
1721        };
1722        assert!((g.line_length(size(px(200.0), px(100.0))).0 - 100.0).abs() < 1e-4);
1723        assert!((g.resolved_stops(size(px(200.0), px(100.0)))[1].1.0 - 0.1).abs() < 1e-6);
1724        // An empty box puts lengths at the start or past the end, still
1725        // in order.
1726        g.kind = GradientKind::Linear { angle: deg(90.0) };
1727        let p: Vec<f32> = g
1728            .resolved_stops(size(px(0.0), px(0.0)))
1729            .into_iter()
1730            .map(|(_, p)| p.0)
1731            .collect();
1732        assert_eq!(p[0], 0.0);
1733        assert!(p.windows(2).all(|w| w[0] <= w[1]));
1734    }
1735
1736    /// A linear gradient of the stops `stops` (colors at fractions of the
1737    /// line).
1738    fn bands(stops: &[(Color, f32)], repeating: bool) -> Gradient {
1739        Gradient {
1740            kind: GradientKind::Linear { angle: deg(90.0) },
1741            stops: stops
1742                .iter()
1743                .map(|&(color, p)| ColorStop {
1744                    color,
1745                    position: Some(DefiniteLength::from(percentage(p))),
1746                })
1747                .collect(),
1748            repeating,
1749        }
1750    }
1751
1752    /// A repeating gradient's stops over the whole line, within `0..=1`:
1753    /// a band of 0..0.1 again every tenth, the ends cut at the colors
1754    /// there; over more than the line (a radial gradient's rings past its
1755    /// ending shape) as fractions of that.
1756    #[test]
1757    fn repeating_stops_unroll_over_the_line() {
1758        let (red, blue) = (Color(0xff00_00ff), Color(0x0000_ffff));
1759        let box_size = size(px(100.0), px(100.0));
1760        let g = bands(&[(red, 0.0), (blue, 0.1)], true);
1761        let stops = g.unrolled_stops(box_size, percentage(1.0));
1762        assert!(stops.iter().all(|s| (0.0..=1.0).contains(&s.1.0)));
1763        assert!(stops.windows(2).all(|w| w[0].1 <= w[1].1));
1764        assert_eq!(stops[0], (red, percentage(0.0)));
1765        assert_eq!(stops[stops.len() - 1].1, percentage(1.0));
1766        for k in 1..10 {
1767            let at = |c: Color| {
1768                stops
1769                    .iter()
1770                    .any(|s| s.0 == c && (s.1.0 - k as f32 * 0.1).abs() < 1e-4)
1771            };
1772            assert!(at(red) && at(blue), "{k}: {stops:?}");
1773        }
1774        // Half a band later, both ways: the ends cut halfway through a
1775        // band, at the color between.
1776        let g = bands(&[(red, 0.125), (blue, 0.375)], true);
1777        let stops = g.unrolled_stops(box_size, percentage(1.0));
1778        let purple = Color(0x8000_80ff);
1779        assert_eq!(stops[0], (purple, percentage(0.0)));
1780        assert_eq!(stops[stops.len() - 1], (purple, percentage(1.0)));
1781        assert!(stops.windows(2).all(|w| w[0].1 <= w[1].1));
1782        // A fade to transparent keeps its hue where it is cut.
1783        let g = bands(&[(red, 0.0), (Color::TRANSPARENT, 0.3)], true);
1784        let stops = g.unrolled_stops(box_size, percentage(1.0));
1785        assert_eq!(stops[stops.len() - 1].0.0 & 0xffff_ff00, 0xff00_0000);
1786        // Over twice the line.
1787        let g = bands(&[(red, 0.0), (blue, 0.1)], true);
1788        let stops = g.unrolled_stops(box_size, percentage(2.0));
1789        assert_eq!(stops[stops.len() - 1].1, percentage(1.0));
1790        let blue_at = |p: f32| {
1791            stops
1792                .iter()
1793                .any(|s| s.0 == blue && (s.1.0 - p).abs() < 1e-4)
1794        };
1795        assert!(blue_at(0.05) && blue_at(0.95), "{stops:?}");
1796    }
1797
1798    /// A hatch's copies stay in order over any box: a copy's first stop,
1799    /// shifted by whole periods, rounds a hair before the one ending the
1800    /// copy before it on most line lengths, and CoreGraphics draws stops
1801    /// out of order as a smeared band.
1802    #[test]
1803    fn repeating_stops_stay_in_order() {
1804        let (red, clear) = (Color(0xff00_004d), Color::TRANSPARENT);
1805        let stop = |color, at: f32| ColorStop {
1806            color,
1807            position: Some(DefiniteLength::from(px(at))),
1808        };
1809        let hatch = Gradient {
1810            kind: GradientKind::Linear { angle: deg(-45.0) },
1811            stops: vec![
1812                stop(red, 0.0),
1813                stop(red, 1.0),
1814                stop(clear, 1.0),
1815                stop(clear, 6.0),
1816            ],
1817            repeating: true,
1818        };
1819        for width in 100..400 {
1820            let box_size = size(px(width as f32 * 0.75), px(140.0));
1821            let stops = hatch.unrolled_stops(box_size, percentage(1.0));
1822            assert!(
1823                stops.windows(2).all(|w| w[0].1 <= w[1].1),
1824                "{width}: {stops:?}"
1825            );
1826        }
1827    }
1828
1829    /// Stops that do not repeat come out as resolved: a gradient that is
1830    /// not repeating (stops past the end too), and one whose period
1831    /// vanishes; a period of 1pt along a long line still repeats.
1832    #[test]
1833    fn other_stops_unroll_as_resolved() {
1834        let (red, blue) = (Color(0xff00_00ff), Color(0x0000_ffff));
1835        let box_size = size(px(100.0), px(100.0));
1836        for g in [
1837            bands(&[(red, 0.0), (blue, 0.1)], false),
1838            bands(&[(red, 0.0), (blue, 1.5)], false),
1839            bands(&[(red, 0.5), (blue, 0.5)], true),
1840        ] {
1841            assert_eq!(
1842                g.unrolled_stops(box_size, percentage(1.0)),
1843                g.resolved_stops(box_size)
1844            );
1845        }
1846        let hatch = Gradient {
1847            stops: vec![
1848                ColorStop {
1849                    color: red,
1850                    position: Some(DefiniteLength::from(px(0.0))),
1851                },
1852                ColorStop {
1853                    color: blue,
1854                    position: Some(DefiniteLength::from(px(1.0))),
1855                },
1856            ],
1857            ..bands(&[], true)
1858        };
1859        let stops = hatch.unrolled_stops(size(px(4000.0), px(10.0)), percentage(1.0));
1860        assert!(stops.len() > 4000, "{}", stops.len());
1861    }
1862
1863    #[test]
1864    fn matrices_compose_in_order() {
1865        let m = compose_color_matrices(&[Filter::Invert(1.0), Filter::Brightness(0.5)]).unwrap();
1866        // White inverted is black; halved stays black. Black: 1 * 0.5.
1867        let apply = |c: f32| m[0] * c + m[4];
1868        assert!((apply(1.0) - 0.0).abs() < 1e-6);
1869        assert!((apply(0.0) - 0.5).abs() < 1e-6);
1870        assert!(compose_color_matrices(&[Filter::Blur(px(2.0))]).is_none());
1871    }
1872
1873    #[test]
1874    fn corner_angles() {
1875        let k = GradientKind::LinearCorner {
1876            right: true,
1877            bottom: false,
1878        };
1879        assert!(
1880            (k.linear_angle(size(px(100.0), px(100.0)))
1881                .unwrap()
1882                .to_degrees()
1883                - 45.0)
1884                .abs()
1885                < 1e-4
1886        );
1887        let k = GradientKind::LinearCorner {
1888            right: true,
1889            bottom: true,
1890        };
1891        assert!(
1892            (k.linear_angle(size(px(100.0), px(100.0)))
1893                .unwrap()
1894                .to_degrees()
1895                - 135.0)
1896                .abs()
1897                < 1e-4
1898        );
1899    }
1900}