Skip to main content

nsh_core/
css.rs

1//! CSS value syntax shared by style strings and Tailwind classes: colors
2//! (hex, `rgb()`, `hsl()`, `oklch()`, `oklab()`, named, and `color-mix()`
3//! of any of them in `srgb`, `srgb-linear`, `xyz`, `oklab`, `oklch` or
4//! `hsl`, as CSS Color 5 mixes), lengths, angles,
5//! and the lists of `box-shadow`, `filter` and gradients. Lengths are
6//! points: `px` and bare numbers are points, `rem` is 16 points.
7
8use crate::style::Color;
9
10/// Points per `rem` in style strings.
11pub(crate) const REM: f32 = 16.0;
12
13/// Splits `s` at `sep` outside parentheses and brackets.
14pub(crate) fn split_top(s: &str, sep: char) -> Vec<&str> {
15    let mut parts = Vec::new();
16    let mut depth = 0i32;
17    let mut start = 0;
18    for (i, c) in s.char_indices() {
19        match c {
20            '(' | '[' => depth += 1,
21            ')' | ']' => depth -= 1,
22            c if c == sep && depth == 0 => {
23                parts.push(s[start..i].trim());
24                start = i + c.len_utf8();
25            }
26            _ => {}
27        }
28    }
29    parts.push(s[start..].trim());
30    parts
31}
32
33/// The whitespace-separated words of `s`, keeping functions (`rgb(0 0 0)`)
34/// whole.
35pub(crate) fn words(s: &str) -> Vec<&str> {
36    let mut out = Vec::new();
37    let mut depth = 0i32;
38    let mut start: Option<usize> = None;
39    for (i, c) in s.char_indices() {
40        match c {
41            '(' | '[' => {
42                depth += 1;
43                start.get_or_insert(i);
44            }
45            ')' | ']' => depth -= 1,
46            c if c.is_whitespace() && depth == 0 => {
47                if let Some(st) = start.take() {
48                    out.push(&s[st..i]);
49                }
50            }
51            _ => {
52                start.get_or_insert(i);
53            }
54        }
55    }
56    if let Some(st) = start {
57        out.push(&s[st..]);
58    }
59    out
60}
61
62/// A number, with an optional `%` (as a fraction when `percent` is set).
63pub(crate) fn number(s: &str) -> Option<f32> {
64    s.trim().parse::<f32>().ok().filter(|n| n.is_finite())
65}
66
67/// A length in points: `4`, `4px`, `0.5rem`, `1pt` (CSS's point, 4/3 of
68/// a pixel).
69pub(crate) fn length(s: &str) -> Option<f32> {
70    let s = s.trim();
71    if let Some(n) = s.strip_suffix("px") {
72        return number(n);
73    }
74    if let Some(n) = s.strip_suffix("pt") {
75        return number(n).map(|n| n * 4.0 / 3.0);
76    }
77    if let Some(n) = s.strip_suffix("rem") {
78        return number(n).map(|n| n * REM);
79    }
80    number(s)
81}
82
83/// A length (in points) or a percentage (a fraction).
84pub(crate) fn length_or_percent(s: &str) -> Option<DefiniteLength> {
85    match s.trim().strip_suffix('%') {
86        Some(p) => number(p).map(|p| percentage(p / 100.0).into()),
87        None => length(s).map(|l| px(l).into()),
88    }
89}
90
91/// An angle in degrees: `45deg`, `0.5turn`, `1rad`, `100grad`, `0`.
92pub(crate) fn angle(s: &str) -> Option<f32> {
93    let s = s.trim();
94    if let Some(n) = s.strip_suffix("deg") {
95        return number(n);
96    }
97    if let Some(n) = s.strip_suffix("grad") {
98        return number(n).map(|n| n * 0.9);
99    }
100    if let Some(n) = s.strip_suffix("rad") {
101        return number(n).map(f32::to_degrees);
102    }
103    if let Some(n) = s.strip_suffix("turn") {
104        return number(n).map(|n| n * 360.0);
105    }
106    number(s).filter(|&n| n == 0.0)
107}
108
109/// A number or a percentage, as a factor: `1.2`, `120%`.
110pub(crate) fn amount(s: &str) -> Option<f32> {
111    match s.trim().strip_suffix('%') {
112        Some(p) => number(p).map(|p| p / 100.0),
113        None => number(s),
114    }
115}
116
117// --- Flex -----------------------------------------------------------------
118
119/// CSS's `flex` shorthand, `none | <grow> <shrink>? || <basis>` and the
120/// keywords: its grow and shrink factors and its basis as written (`None`:
121/// 0, which a shorthand without one sets). Factors are unitless numbers of
122/// at least 0; a unitless 0 is a factor unless two came before it.
123pub(crate) fn flex(s: &str) -> Option<(f32, f32, Option<&str>)> {
124    let factor = |w: &str| number(w).filter(|n| *n >= 0.0);
125    let w = words(s);
126    Some(match w.as_slice() {
127        ["none"] => (0.0, 0.0, Some("auto")),
128        ["auto"] => (1.0, 1.0, Some("auto")),
129        ["initial"] => (0.0, 1.0, Some("auto")),
130        [a] => match factor(a) {
131            Some(g) => (g, 1.0, None),
132            None => (1.0, 1.0, Some(basis(a)?)),
133        },
134        [a, b] => match (factor(a), factor(b)) {
135            (Some(g), Some(sh)) => (g, sh, None),
136            (Some(g), None) => (g, 1.0, Some(basis(b)?)),
137            (None, Some(g)) => (g, 1.0, Some(basis(a)?)),
138            (None, None) => return None,
139        },
140        [a, b, c] => match (factor(a), factor(b), factor(c)) {
141            // After two factors, a unitless 0 is the basis.
142            (Some(g), Some(sh), Some(0.0)) => (g, sh, None),
143            (Some(g), Some(sh), _) => (g, sh, Some(basis(c)?)),
144            (None, Some(g), Some(sh)) => (g, sh, Some(basis(a)?)),
145            _ => return None,
146        },
147        _ => return None,
148    })
149}
150
151/// A `flex` word that can only be its basis: not a number (a unitless
152/// one is a factor) and not a negative length.
153fn basis(w: &str) -> Option<&str> {
154    (number(w).is_none() && !w.starts_with('-')).then_some(w)
155}
156
157// --- Colors ---------------------------------------------------------------
158
159/// Whether `s` is CSS's `currentColor` keyword (ASCII case insensitive, as
160/// CSS keywords are).
161pub(crate) fn is_current_color(s: &str) -> bool {
162    s.trim().eq_ignore_ascii_case("currentcolor")
163}
164
165/// The spans of `s` that are the word `currentColor` (in any case), not
166/// part of a longer name.
167fn current_color_spans(s: &str) -> impl Iterator<Item = usize> + '_ {
168    const WORD: &[u8] = b"currentcolor";
169    let bytes = s.as_bytes();
170    let name = |b: u8| b.is_ascii_alphanumeric() || b == b'-' || b == b'_';
171    (0..bytes.len().saturating_sub(WORD.len() - 1)).filter(move |&i| {
172        bytes[i..i + WORD.len()].eq_ignore_ascii_case(WORD)
173            && (i == 0 || !name(bytes[i - 1]))
174            && bytes.get(i + WORD.len()).is_none_or(|&b| !name(b))
175    })
176}
177
178/// Whether the value `s` writes `currentColor` somewhere in it (a
179/// gradient's stop, a `color-mix()`, a shadow's color).
180pub(crate) fn mentions_current_color(s: &str) -> bool {
181    current_color_spans(s).next().is_some()
182}
183
184/// `s` with every `currentColor` in it written as `color`, to parse once
185/// the color is known.
186pub(crate) fn with_current_color(s: &str, color: Color) -> String {
187    let hex = format!("#{:08x}", color.0);
188    let mut out = String::with_capacity(s.len());
189    let mut at = 0;
190    for i in current_color_spans(s) {
191        out.push_str(&s[at..i]);
192        out.push_str(&hex);
193        at = i + "currentcolor".len();
194    }
195    out.push_str(&s[at..]);
196    out
197}
198
199/// Parses a CSS color.
200pub(crate) fn color(s: &str) -> Option<Color> {
201    let s = s.trim();
202    if let Some(hex) = s.strip_prefix('#') {
203        return parse_hex(hex.as_bytes());
204    }
205    if let Some(open) = s.find('(') {
206        let name = s[..open].trim().to_ascii_lowercase();
207        let args = s[open + 1..].strip_suffix(')')?;
208        return match name.as_str() {
209            "rgb" | "rgba" => rgb(args),
210            "hsl" | "hsla" => hsl(args),
211            "oklch" => oklab(args, true),
212            "oklab" => oklab(args, false),
213            "color-mix" => color_mix(args),
214            _ => None,
215        };
216    }
217    let lower;
218    let name = if s.bytes().any(|b| b.is_ascii_uppercase()) {
219        lower = s.to_ascii_lowercase();
220        lower.as_str()
221    } else {
222        s
223    };
224    if name == "transparent" {
225        return Some(Color::TRANSPARENT);
226    }
227    crate::css_named::NAMED
228        .binary_search_by(|(n, _)| (*n).cmp(name))
229        .ok()
230        .map(|i| Color(crate::css_named::NAMED[i].1))
231}
232
233#[inline]
234fn hex_digit(b: u8) -> Option<u32> {
235    match b {
236        b'0'..=b'9' => Some((b - b'0') as u32),
237        b'a'..=b'f' => Some((b - b'a' + 10) as u32),
238        b'A'..=b'F' => Some((b - b'A' + 10) as u32),
239        _ => None,
240    }
241}
242
243fn parse_hex(hex: &[u8]) -> Option<Color> {
244    let mut v = 0u32;
245    for &b in hex {
246        v = v << 4 | hex_digit(b)?;
247    }
248    Some(match hex.len() {
249        3 | 4 => {
250            // Expand each nibble: 0xabc -> 0xaabbcc.
251            let (rgb, a) = if hex.len() == 3 {
252                (v, 0xf)
253            } else {
254                (v >> 4, v & 0xf)
255            };
256            let r = (rgb >> 8) & 0xf;
257            let g = (rgb >> 4) & 0xf;
258            let b = rgb & 0xf;
259            Color((r * 0x11) << 24 | (g * 0x11) << 16 | (b * 0x11) << 8 | (a * 0x11))
260        }
261        6 => Color(v << 8 | 0xff),
262        8 => Color(v),
263        _ => return None,
264    })
265}
266
267/// The channels of a color function, either legacy (`1, 2, 3, 0.5`) or
268/// modern (`1 2 3 / 50%`), and the alpha (1 when absent).
269fn channels(args: &str) -> Option<([&str; 3], f32)> {
270    let (main, alpha) = match args.split_once('/') {
271        Some((m, a)) => (m, Some(a.trim())),
272        None => (args, None),
273    };
274    let parts: Vec<&str> = if main.contains(',') {
275        main.split(',').map(str::trim).collect()
276    } else {
277        main.split_whitespace().collect()
278    };
279    let (c, alpha) = match (parts.as_slice(), alpha) {
280        ([a, b, c], alpha) => ([*a, *b, *c], alpha),
281        ([a, b, c, d], None) => ([*a, *b, *c], Some(*d)),
282        _ => return None,
283    };
284    let alpha = match alpha {
285        Some(a) => amount(a)?.clamp(0.0, 1.0),
286        None => 1.0,
287    };
288    Some((c, alpha))
289}
290
291fn rgb(args: &str) -> Option<Color> {
292    let (c, a) = channels(args)?;
293    let channel = |s: &str| -> Option<f32> {
294        match s.strip_suffix('%') {
295            Some(p) => number(p).map(|p| p / 100.0),
296            None => number(s).map(|n| n / 255.0),
297        }
298    };
299    Some(from_unit(channel(c[0])?, channel(c[1])?, channel(c[2])?, a))
300}
301
302fn hsl(args: &str) -> Option<Color> {
303    let (c, a) = channels(args)?;
304    let h = angle(c[0]).or_else(|| number(c[0]))?.rem_euclid(360.0);
305    let pct = |s: &str| -> Option<f32> {
306        number(s.strip_suffix('%').unwrap_or(s)).map(|v| (v / 100.0).clamp(0.0, 1.0))
307    };
308    let (s, l) = (pct(c[1])?, pct(c[2])?);
309    let (r, g, b) = crate::color::hsl_to_rgb(h, s, l);
310    Some(from_unit(r, g, b, a))
311}
312
313/// `oklch(L C H)` (`polar`) or `oklab(L a b)`, to sRGB with clamped
314/// channels.
315fn oklab(args: &str, polar: bool) -> Option<Color> {
316    let (c, alpha) = channels(args)?;
317    let l = match c[0].strip_suffix('%') {
318        Some(p) => number(p)? / 100.0,
319        None => number(c[0])?,
320    };
321    let (a, b) = if polar {
322        let chroma = match c[1].strip_suffix('%') {
323            Some(p) => number(p)? / 100.0 * 0.4,
324            None => number(c[1])?,
325        };
326        let h = angle(c[2])
327            .or_else(|| number(c[2]))
328            .unwrap_or(0.0)
329            .to_radians();
330        (chroma * h.cos(), chroma * h.sin())
331    } else {
332        let axis = |s: &str| -> Option<f32> {
333            match s.strip_suffix('%') {
334                Some(p) => number(p).map(|p| p / 100.0 * 0.4),
335                None => number(s),
336            }
337        };
338        (axis(c[1])?, axis(c[2])?)
339    };
340    Some(oklab_to_color(l, a, b, alpha))
341}
342
343/// OKLab to sRGB (Björn Ottosson's matrices).
344pub(crate) fn oklab_to_color(l: f32, a: f32, b: f32, alpha: f32) -> Color {
345    let (r, g, b) = crate::color::oklab_to_rgb(l, a, b);
346    from_unit(r, g, b, alpha)
347}
348
349fn from_unit(r: f32, g: f32, b: f32, a: f32) -> Color {
350    use crate::color::byte;
351    Color::rgba(byte(r), byte(g), byte(b), byte(a))
352}
353
354/// The color space `color-mix()` interpolates in.
355#[derive(Clone, Copy, PartialEq)]
356enum MixSpace {
357    Srgb,
358    /// Also `xyz`, `xyz-d65` and `xyz-d50`: they are linear transforms of
359    /// linear sRGB, and a linear transform commutes with the (premultiplied)
360    /// interpolation, so mixing in them gives the same color.
361    SrgbLinear,
362    Oklab,
363    Oklch,
364    Hsl,
365}
366
367/// How `color-mix()` interpolates a hue (CSS Color 4 "hue-interpolation").
368#[derive(Clone, Copy, PartialEq)]
369enum HueMethod {
370    Shorter,
371    Longer,
372    Increasing,
373    Decreasing,
374}
375
376/// A chroma (OKLCh) or saturation (HSL) below which the hue is powerless:
377/// colors arrive packed to 8 bits, so a grey's chroma is float noise, not 0.
378const ACHROMATIC: f32 = 1e-4;
379
380/// `color-mix(in <space> [<hue-method> hue]?, <color> <pct>?, <color>
381/// <pct>?)`, as CSS Color 5 defines it: percentages normalized (both
382/// omitted 50 / 50, one omitted the rest of 100%, a sum other than 100%
383/// scaled to it and a sum below 100% kept as an alpha factor), channels
384/// interpolated with premultiplied alpha, a powerless hue taking the other
385/// color's.
386fn color_mix(args: &str) -> Option<Color> {
387    let [method, first, second] = split_top(args, ',')[..] else {
388        return None;
389    };
390    let (space, hue) = mix_method(method)?;
391    let (c1, p1) = mix_color(first)?;
392    let (c2, p2) = mix_color(second)?;
393    let (p1, p2) = match (p1, p2) {
394        (None, None) => (0.5, 0.5),
395        (Some(p1), None) => (p1, 1.0 - p1),
396        (None, Some(p2)) => (1.0 - p2, p2),
397        (Some(p1), Some(p2)) => (p1, p2),
398    };
399    let sum = p1 + p2;
400    if sum <= 0.0 {
401        return None;
402    }
403    let w1 = p1 / sum;
404    let (out, alpha) = mix_coords(c1, c2, w1, space, hue);
405    // A sum below 100% leaves the rest transparent.
406    let alpha = alpha * sum.min(1.0);
407    Some(from_mix_space(out, alpha, space))
408}
409
410/// `c1` and `c2` mixed in `space`, `w1` of `c1`: the coordinates and the
411/// alpha, channels interpolated with premultiplied alpha, a powerless
412/// hue taking the other color's.
413fn mix_coords(
414    c1: Color,
415    c2: Color,
416    w1: f32,
417    space: MixSpace,
418    hue: Option<HueMethod>,
419) -> ([f32; 3], f32) {
420    let (mut v1, a1, missing1) = to_mix_space(c1, space);
421    let (mut v2, a2, missing2) = to_mix_space(c2, space);
422    let alpha = a1 * w1 + a2 * (1.0 - w1);
423    let hue_index = match space {
424        MixSpace::Oklch => Some(2),
425        MixSpace::Hsl => Some(0),
426        _ => None,
427    };
428    let mut out = [0.0; 3];
429    for i in 0..3 {
430        out[i] = if hue_index == Some(i) {
431            // A missing hue takes the other color's, so mixing with a grey
432            // keeps the hue instead of sweeping from red (hue 0).
433            match (missing1, missing2) {
434                (true, false) => v1[i] = v2[i],
435                (false, true) => v2[i] = v1[i],
436                _ => {}
437            }
438            let (h1, h2) = fix_hues(v1[i], v2[i], hue.unwrap_or(HueMethod::Shorter));
439            (h1 * w1 + h2 * (1.0 - w1)).rem_euclid(360.0)
440        } else if alpha > 0.0 {
441            (v1[i] * a1 * w1 + v2[i] * a2 * (1.0 - w1)) / alpha
442        } else {
443            v1[i] * w1 + v2[i] * (1.0 - w1)
444        };
445    }
446    (out, alpha)
447}
448
449/// `in <space> [<hue-method> hue]?`; a hue method only for polar spaces.
450fn mix_method(s: &str) -> Option<(MixSpace, Option<HueMethod>)> {
451    let lower = s.to_ascii_lowercase();
452    let w: Vec<&str> = lower.split_whitespace().collect();
453    let (space, rest) = match w.as_slice() {
454        ["in", space, rest @ ..] => (*space, rest),
455        _ => return None,
456    };
457    let space = match space {
458        "srgb" => MixSpace::Srgb,
459        "srgb-linear" | "xyz" | "xyz-d65" | "xyz-d50" => MixSpace::SrgbLinear,
460        "oklab" => MixSpace::Oklab,
461        "oklch" => MixSpace::Oklch,
462        "hsl" => MixSpace::Hsl,
463        _ => return None,
464    };
465    let hue = match rest {
466        [] => None,
467        [method, "hue"] if matches!(space, MixSpace::Oklch | MixSpace::Hsl) => {
468            Some(match *method {
469                "shorter" => HueMethod::Shorter,
470                "longer" => HueMethod::Longer,
471                "increasing" => HueMethod::Increasing,
472                "decreasing" => HueMethod::Decreasing,
473                _ => return None,
474            })
475        }
476        _ => return None,
477    };
478    Some((space, hue))
479}
480
481/// `<color> <percentage>?` in either order; the percentage as a fraction,
482/// only within `0%..=100%`.
483fn mix_color(s: &str) -> Option<(Color, Option<f32>)> {
484    let percent = |w: &str| -> Option<f32> {
485        let p = number(w.strip_suffix('%')?)?;
486        (0.0..=100.0).contains(&p).then_some(p / 100.0)
487    };
488    match words(s).as_slice() {
489        [c] => Some((color(c)?, None)),
490        [a, b] if a.ends_with('%') => Some((color(b)?, Some(percent(a)?))),
491        [a, b] => Some((color(a)?, Some(percent(b)?))),
492        _ => None,
493    }
494}
495
496/// A color's coordinates in `space` (the hue in degrees), its alpha, and
497/// whether its hue is powerless (missing, in CSS's terms).
498fn to_mix_space(c: Color, space: MixSpace) -> ([f32; 3], f32, bool) {
499    use crate::color::{Rgba, rgb_to_oklab, srgb_to_linear};
500    let rgba = Rgba::from(c);
501    let v = match space {
502        MixSpace::Srgb => [rgba.r, rgba.g, rgba.b],
503        MixSpace::SrgbLinear => [
504            srgb_to_linear(rgba.r),
505            srgb_to_linear(rgba.g),
506            srgb_to_linear(rgba.b),
507        ],
508        MixSpace::Oklab | MixSpace::Oklch => {
509            let (l, a, b) = rgb_to_oklab(rgba);
510            if space == MixSpace::Oklab {
511                [l, a, b]
512            } else {
513                let chroma = a.hypot(b);
514                let hue = b.atan2(a).to_degrees().rem_euclid(360.0);
515                return ([l, chroma, hue], rgba.a, chroma < ACHROMATIC);
516            }
517        }
518        MixSpace::Hsl => {
519            let hsla = rgba.to_hsla();
520            return (
521                [hsla.h * 360.0, hsla.s, hsla.l],
522                rgba.a,
523                hsla.s < ACHROMATIC,
524            );
525        }
526    };
527    (v, rgba.a, false)
528}
529
530/// The mixed coordinates back to a packed sRGB color, channels clamped.
531fn from_mix_space(v: [f32; 3], alpha: f32, space: MixSpace) -> Color {
532    use crate::color::linear_to_srgb;
533    match space {
534        MixSpace::Srgb => from_unit(v[0], v[1], v[2], alpha),
535        MixSpace::SrgbLinear => from_unit(
536            linear_to_srgb(v[0]),
537            linear_to_srgb(v[1]),
538            linear_to_srgb(v[2]),
539            alpha,
540        ),
541        MixSpace::Oklab => oklab_to_color(v[0], v[1], v[2], alpha),
542        MixSpace::Oklch => {
543            let h = v[2].to_radians();
544            oklab_to_color(v[0], v[1] * h.cos(), v[1] * h.sin(), alpha)
545        }
546        MixSpace::Hsl => {
547            let (r, g, b) = crate::color::hsl_to_rgb(v[0], v[1], v[2]);
548            from_unit(r, g, b, alpha)
549        }
550    }
551}
552
553/// Two hues (degrees in `0..360`) adjusted so a straight interpolation
554/// between them goes the way `method` asks (CSS Color 4 "hue-interpolation").
555fn fix_hues(mut h1: f32, mut h2: f32, method: HueMethod) -> (f32, f32) {
556    let d = h2 - h1;
557    match method {
558        HueMethod::Shorter if d > 180.0 => h1 += 360.0,
559        HueMethod::Shorter if d < -180.0 => h2 += 360.0,
560        HueMethod::Longer if 0.0 < d && d < 180.0 => h1 += 360.0,
561        HueMethod::Longer if -180.0 < d && d <= 0.0 => h2 += 360.0,
562        HueMethod::Increasing if h2 < h1 => h2 += 360.0,
563        HueMethod::Decreasing if h1 < h2 => h1 += 360.0,
564        _ => {}
565    }
566    (h1, h2)
567}
568
569impl Color {
570    /// The color with its alpha multiplied by `factor`.
571    pub fn with_alpha(self, factor: f32) -> Color {
572        let a = ((self.0 & 0xff) as f32 * factor.clamp(0.0, 1.0)).round() as u32;
573        Color(self.0 & 0xffff_ff00 | a)
574    }
575}
576
577// --- Shadows, gradients, filters --------------------------------------------
578
579use crate::{
580    effects::{BoxShadow, ColorStop, Filter, Gradient, GradientKind, GradientSize},
581    geometry::{DefiniteLength, Percentage, deg, percentage, px},
582    style::ObjectPosition,
583};
584
585/// A `box-shadow` list (`none` is empty).
586pub(crate) fn box_shadows(s: &str) -> Option<Vec<BoxShadow>> {
587    Some(shadow_layers(s)?.into_iter().map(|(l, _)| l).collect())
588}
589
590/// A shadow list's layers, each with whether it names its color (else it
591/// is black here, CSS's `currentColor` for a style to fill in).
592pub(crate) fn shadow_layers(s: &str) -> Option<Vec<(BoxShadow, bool)>> {
593    let s = s.trim();
594    if s.is_empty() || s == "none" {
595        return Some(Vec::new());
596    }
597    split_top(s, ',').into_iter().map(shadow_layer).collect()
598}
599
600/// A `text-shadow` list (`none` is empty): offsets, blur and color.
601pub(crate) fn text_shadows(s: &str) -> Option<Vec<(crate::style::TextShadow, bool)>> {
602    shadow_layers(s)?
603        .into_iter()
604        .map(|(l, colored)| {
605            (!l.inset && l.spread.0 == 0.0).then_some((
606                crate::style::TextShadow {
607                    color: l.color,
608                    offset_x: l.offset_x,
609                    offset_y: l.offset_y,
610                    radius: l.blur,
611                },
612                colored,
613            ))
614        })
615        .collect()
616}
617
618/// One shadow, `[inset] <x> <y> [<blur> [<spread>]] [<color>]` (words in
619/// any order around the lengths), and whether it names its color.
620fn shadow_layer(s: &str) -> Option<(BoxShadow, bool)> {
621    let mut shadow = BoxShadow {
622        color: Color(0x0000_00ff),
623        ..BoxShadow::default()
624    };
625    let mut lengths = Vec::with_capacity(4);
626    let mut color_seen = false;
627    for word in words(s) {
628        if word == "inset" {
629            shadow.inset = true;
630        } else if let Some(l) = length(word) {
631            lengths.push(l);
632        } else if !color_seen && let Some(c) = color(word) {
633            shadow.color = c;
634            color_seen = true;
635        } else {
636            return None;
637        }
638    }
639    match lengths.as_slice() {
640        [x, y] => (shadow.offset_x, shadow.offset_y) = (px(*x), px(*y)),
641        [x, y, blur] => {
642            (shadow.offset_x, shadow.offset_y, shadow.blur) = (px(*x), px(*y), px(blur.max(0.0)))
643        }
644        [x, y, blur, spread] => {
645            (shadow.offset_x, shadow.offset_y, shadow.blur, shadow.spread) =
646                (px(*x), px(*y), px(blur.max(0.0)), px(*spread))
647        }
648        _ => return None,
649    }
650    Some((shadow, color_seen))
651}
652
653/// A `background-image` list of gradients (`none` is empty).
654pub(crate) fn gradients(s: &str) -> Option<Vec<Gradient>> {
655    let s = s.trim();
656    if s.is_empty() || s == "none" {
657        return Some(Vec::new());
658    }
659    split_top(s, ',').into_iter().map(gradient).collect()
660}
661
662/// `linear-gradient(...)`, `radial-gradient(...)`, `conic-gradient(...)`
663/// (and their `repeating-` forms).
664pub(crate) fn gradient(s: &str) -> Option<Gradient> {
665    let s = s.trim();
666    let open = s.find('(')?;
667    let name = s[..open].trim();
668    let args = s[open + 1..].strip_suffix(')')?;
669    let (repeating, base) = match name.strip_prefix("repeating-") {
670        Some(b) => (true, b),
671        None => (false, name),
672    };
673    let parts = split_top(args, ',');
674    let mut parts = parts.as_slice();
675    let mut kind = match base {
676        "linear-gradient" => GradientKind::Linear { angle: deg(180.0) },
677        "radial-gradient" => GradientKind::Radial {
678            circle: false,
679            size: GradientSize::FarthestCorner,
680            x: percentage(0.5),
681            y: percentage(0.5),
682        },
683        "conic-gradient" => GradientKind::Conic {
684            from: deg(0.0),
685            x: percentage(0.5),
686            y: percentage(0.5),
687        },
688        _ => return None,
689    };
690    // The first argument configures the gradient when it is not a stop:
691    // its geometry and how its colors mix (`in oklab`).
692    let mut interpolation = Interpolation::SRGB;
693    let mut explicit = false;
694    if let Some(first) = parts.first() {
695        let first = first.trim();
696        // `to right in oklab` or `in oklab to right`: CSS takes both orders.
697        let (geometry, method) = match interpolation_at(first) {
698            Some(i) => {
699                let end = method_end(&first[i..]) + i;
700                let geometry = format!("{} {}", &first[..i], &first[end..]);
701                (geometry, Some(&first[i..end]))
702            }
703            None => (first.to_string(), None),
704        };
705        if let Some(method) = method {
706            let (space, hue) = mix_method(method)?;
707            interpolation = Interpolation { space, hue };
708            explicit = true;
709        }
710        let configured = configure(&mut kind, geometry.trim());
711        if method.is_some() && !configured {
712            return None;
713        }
714        if configured {
715            parts = &parts[1..];
716        }
717    }
718    let conic = matches!(kind, GradientKind::Conic { .. });
719    let mut stops = Vec::with_capacity(parts.len());
720    let mut modern = false;
721    for part in parts {
722        let w = words(part);
723        let (c, positions) = w.split_first()?;
724        let color = color(c)?;
725        modern |= !is_legacy_color(c);
726        // A stop takes up to two positions (`red 0 10px`: a band of one
727        // color).
728        if positions.len() > 2 {
729            return None;
730        }
731        if positions.is_empty() {
732            stops.push(ColorStop {
733                color,
734                position: None,
735            });
736        }
737        for p in positions {
738            stops.push(ColorStop {
739                color,
740                position: Some(stop_position(p, conic)?),
741            });
742        }
743    }
744    if stops.is_empty() {
745        return None;
746    }
747    if stops.len() == 1 {
748        let only = stops[0];
749        stops.push(only);
750    }
751    // Without a method, CSS mixes in Oklab unless every color is a legacy
752    // sRGB one.
753    if !explicit && modern {
754        interpolation = Interpolation::OKLAB;
755    }
756    Some(Gradient {
757        kind,
758        stops: interpolate_stops(stops, interpolation),
759        repeating,
760    })
761}
762
763/// Whether the CSS color `s` is a legacy sRGB color (hex, `rgb()`,
764/// `hsl()`, `hwb()`, a name), which CSS mixes in sRGB where no
765/// interpolation method is given, and in Oklab otherwise.
766pub(crate) fn is_legacy_color(s: &str) -> bool {
767    let s = s.trim().to_ascii_lowercase();
768    !["oklch(", "oklab(", "lab(", "lch(", "color(", "color-mix("]
769        .iter()
770        .any(|p| s.starts_with(p))
771}
772
773/// Where `arg` (a gradient's first argument) says `in <space>`, outside
774/// parentheses (keywords in any case, as CSS's).
775fn interpolation_at(arg: &str) -> Option<usize> {
776    let mut depth = 0i32;
777    for (i, c) in arg.char_indices() {
778        match c {
779            '(' => depth += 1,
780            ')' => depth -= 1,
781            _ if depth == 0
782                && arg[i..].get(..3).is_some_and(|w| {
783                    w[..2].eq_ignore_ascii_case("in") && w.ends_with(char::is_whitespace)
784                })
785                && (i == 0 || arg[..i].ends_with(char::is_whitespace)) =>
786            {
787                return Some(i);
788            }
789            _ => {}
790        }
791    }
792    None
793}
794
795/// The length of the `<color-interpolation-method>` `s` starts with: `in`,
796/// the space, and `<method> hue` when it follows.
797fn method_end(s: &str) -> usize {
798    let mut words = Vec::with_capacity(4);
799    let mut word = None;
800    for (i, c) in s.char_indices().chain([(s.len(), ' ')]) {
801        match (c.is_whitespace(), word) {
802            (false, None) => word = Some(i),
803            (true, Some(start)) => {
804                words.push((start, i));
805                word = None;
806                if words.len() == 4 {
807                    break;
808                }
809            }
810            _ => {}
811        }
812    }
813    let text = |n: usize| words.get(n).map(|&(a, b)| s[a..b].to_ascii_lowercase());
814    let hue = matches!(
815        text(2).as_deref(),
816        Some("shorter" | "longer" | "increasing" | "decreasing")
817    ) && text(3).as_deref() == Some("hue");
818    match (hue, words.get(1)) {
819        (true, _) => words[3].1,
820        (false, Some(&(_, end))) => end,
821        (false, None) => s.len(),
822    }
823}
824
825/// How a gradient's colors mix between its stops (CSS's
826/// `<color-interpolation-method>`).
827#[derive(Clone, Copy, PartialEq)]
828pub(crate) struct Interpolation {
829    space: MixSpace,
830    hue: Option<HueMethod>,
831}
832
833impl Interpolation {
834    /// In sRGB, what the platforms draw: CSS's for legacy colors.
835    pub(crate) const SRGB: Interpolation = Interpolation {
836        space: MixSpace::Srgb,
837        hue: None,
838    };
839    /// In Oklab, Tailwind's for every gradient utility (`in oklab`).
840    pub(crate) const OKLAB: Interpolation = Interpolation {
841        space: MixSpace::Oklab,
842        hue: None,
843    };
844
845    /// `t` of the way from `a` to `b`.
846    fn mix(self, a: Color, b: Color, t: f32) -> Color {
847        let (v, alpha) = mix_coords(a, b, 1.0 - t, self.space, self.hue);
848        from_mix_space(v, alpha, self.space)
849    }
850}
851
852/// `stops` mixed in `method`, as the platforms draw: they interpolate in
853/// sRGB, so between each two stops placed in the same unit (two fractions
854/// of the line, two lengths; unplaced ones are spread as CSS spreads them
855/// first, when every placed one is a fraction) stops sampled in `method`
856/// are inserted where the sRGB segments would leave the curve by more than
857/// about one 8-bit step, at most 32 segments per pair.
858pub(crate) fn interpolate_stops(
859    mut stops: Vec<ColorStop>,
860    method: Interpolation,
861) -> Vec<ColorStop> {
862    if method == Interpolation::SRGB || stops.windows(2).all(|w| w[0].color == w[1].color) {
863        return stops;
864    }
865    spread_positions(&mut stops);
866    let mut out = Vec::with_capacity(stops.len() * 4);
867    for (i, &stop) in stops.iter().enumerate() {
868        out.push(stop);
869        let Some(&next) = stops.get(i + 1) else {
870            break;
871        };
872        let place = match (stop.position, next.position) {
873            (Some(DefiniteLength::Fraction(a)), Some(DefiniteLength::Fraction(b))) if b.0 > a.0 => {
874                Some((a.0, b.0, true))
875            }
876            (Some(DefiniteLength::Absolute(a)), Some(DefiniteLength::Absolute(b))) => {
877                let rem = crate::geometry::REM_SIZE;
878                let (a, b) = (a.to_points(rem).0, b.to_points(rem).0);
879                (b > a).then_some((a, b, false))
880            }
881            _ => None,
882        };
883        let Some((from, to, fraction)) = place.filter(|_| stop.color != next.color) else {
884            continue;
885        };
886        let at = |t: f32| -> DefiniteLength {
887            let p = from + (to - from) * t;
888            if fraction {
889                percentage(p).into()
890            } else {
891                px(p).into()
892            }
893        };
894        // Polar spaces may turn the hue all the way around: never fewer
895        // than four segments there.
896        let min_depth =
897            if method.hue.is_some() || matches!(method.space, MixSpace::Oklch | MixSpace::Hsl) {
898                2
899            } else {
900                0
901            };
902        subdivide(
903            method,
904            stop.color,
905            next.color,
906            (0.0, stop.color),
907            (1.0, next.color),
908            0,
909            min_depth,
910            &mut |t, color| {
911                out.push(ColorStop {
912                    color,
913                    position: Some(at(t)),
914                });
915            },
916        );
917    }
918    out
919}
920
921/// Emits the samples of `a` to `b` in `method` between `lo` and `hi` (each
922/// `(t, color)`), in order.
923#[allow(clippy::too_many_arguments)]
924fn subdivide(
925    method: Interpolation,
926    a: Color,
927    b: Color,
928    lo: (f32, Color),
929    hi: (f32, Color),
930    depth: u8,
931    min_depth: u8,
932    emit: &mut impl FnMut(f32, Color),
933) {
934    const MAX_DEPTH: u8 = 5;
935    if depth >= MAX_DEPTH {
936        return;
937    }
938    let t = (lo.0 + hi.0) / 2.0;
939    let mid = method.mix(a, b, t);
940    // Premultiplied, as a fully transparent end has no color to leave.
941    let premultiplied = |c: Color| {
942        let c = crate::color::Rgba::from(c);
943        [c.r * c.a, c.g * c.a, c.b * c.a, c.a]
944    };
945    let (m, l, h) = (premultiplied(mid), premultiplied(lo.1), premultiplied(hi.1));
946    let off = (0..4)
947        .map(|i| (m[i] - (l[i] + h[i]) / 2.0).abs())
948        .fold(0.0f32, f32::max);
949    if depth >= min_depth && off * 255.0 <= 1.0 {
950        return;
951    }
952    subdivide(method, a, b, lo, (t, mid), depth + 1, min_depth, emit);
953    emit(t, mid);
954    subdivide(method, a, b, (t, mid), hi, depth + 1, min_depth, emit);
955}
956
957/// Places unplaced stops as CSS does, when every placed one is a fraction
958/// of the line: the first at 0, the last at 1, the others spread evenly
959/// between their placed neighbors; then each at least the one before it.
960fn spread_positions(stops: &mut [ColorStop]) {
961    let fraction = |s: &ColorStop| match s.position {
962        Some(DefiniteLength::Fraction(f)) => Some(f.0),
963        _ => None,
964    };
965    if stops
966        .iter()
967        .any(|s| s.position.is_some() && fraction(s).is_none())
968    {
969        return;
970    }
971    let n = stops.len();
972    if stops[0].position.is_none() {
973        stops[0].position = Some(percentage(0.0).into());
974    }
975    if stops[n - 1].position.is_none() {
976        stops[n - 1].position = Some(percentage(1.0).into());
977    }
978    let mut max = 0.0f32;
979    let mut i = 0;
980    while i < n {
981        let Some(p) = fraction(&stops[i]) else {
982            // A run of unplaced stops up to the next placed one.
983            let start = i - 1;
984            let end = (i..n)
985                .find(|&j| stops[j].position.is_some())
986                .unwrap_or(n - 1);
987            let (a, b) = (max, fraction(&stops[end]).unwrap_or(1.0).max(max));
988            for (j, stop) in stops.iter_mut().enumerate().take(end).skip(i) {
989                let t = (j - start) as f32 / (end - start) as f32;
990                stop.position = Some(percentage(a + (b - a) * t).into());
991            }
992            i = end;
993            continue;
994        };
995        max = max.max(p);
996        stops[i].position = Some(percentage(max).into());
997        i += 1;
998    }
999}
1000
1001/// A stop's position: a percentage, or a length along a linear or radial
1002/// gradient's line (`10px`, `1rem`; resolved against the box when it is
1003/// drawn), or an angle around a conic one (`90deg`, `0.25turn`, as a
1004/// fraction of a turn).
1005fn stop_position(s: &str, conic: bool) -> Option<DefiniteLength> {
1006    let s = s.trim();
1007    if let Some(p) = s.strip_suffix('%') {
1008        return number(p).map(|p| percentage(p / 100.0).into());
1009    }
1010    if conic {
1011        angle(s).map(|a| percentage(a / 360.0).into())
1012    } else {
1013        // A zero length is the line's start whatever its length, as
1014        // before lengths were taken.
1015        length(s).map(|l| {
1016            if l == 0.0 {
1017                percentage(0.0).into()
1018            } else {
1019                px(l).into()
1020            }
1021        })
1022    }
1023}
1024
1025/// Reads a gradient's geometry argument (without its interpolation
1026/// method) into `kind`; false when the argument is a color stop.
1027fn configure(kind: &mut GradientKind, arg: &str) -> bool {
1028    let w = words(arg);
1029    if w.is_empty() {
1030        return true;
1031    }
1032    match kind {
1033        GradientKind::Linear { .. } | GradientKind::LinearCorner { .. } => {
1034            if w[0] == "to" {
1035                let mut h = 0.0f32;
1036                let mut v = 0.0f32;
1037                for side in &w[1..] {
1038                    match *side {
1039                        "top" => v = -1.0,
1040                        "bottom" => v = 1.0,
1041                        "left" => h = -1.0,
1042                        "right" => h = 1.0,
1043                        _ => return false,
1044                    }
1045                }
1046                *kind = match (h as i8, v as i8) {
1047                    (0, -1) => GradientKind::Linear { angle: deg(0.0) },
1048                    (1, 0) => GradientKind::Linear { angle: deg(90.0) },
1049                    (0, 1) => GradientKind::Linear { angle: deg(180.0) },
1050                    (-1, 0) => GradientKind::Linear { angle: deg(270.0) },
1051                    (0, 0) => return false,
1052                    // A corner: the angle depends on the box's shape.
1053                    (h, v) => GradientKind::LinearCorner {
1054                        right: h > 0,
1055                        bottom: v > 0,
1056                    },
1057                };
1058                true
1059            } else if let Some(a) = angle(w[0]) {
1060                *kind = GradientKind::Linear { angle: deg(a) };
1061                true
1062            } else {
1063                false
1064            }
1065        }
1066        GradientKind::Radial { circle, size, x, y } => {
1067            let mut i = 0;
1068            let mut any = false;
1069            while i < w.len() {
1070                match w[i] {
1071                    "circle" => *circle = true,
1072                    "ellipse" => *circle = false,
1073                    "closest-side" => *size = GradientSize::ClosestSide,
1074                    "closest-corner" => *size = GradientSize::ClosestCorner,
1075                    "farthest-side" => *size = GradientSize::FarthestSide,
1076                    "farthest-corner" => *size = GradientSize::FarthestCorner,
1077                    "at" => {
1078                        let Some((px, py)) = position(&w[i + 1..]) else {
1079                            return false;
1080                        };
1081                        (*x, *y) = (Percentage(px), Percentage(py));
1082                        return true;
1083                    }
1084                    _ => return any,
1085                }
1086                any = true;
1087                i += 1;
1088            }
1089            any
1090        }
1091        GradientKind::Conic { from, x, y } => {
1092            let mut i = 0;
1093            let mut any = false;
1094            while i < w.len() {
1095                match w[i] {
1096                    "from" => {
1097                        let Some(a) = w.get(i + 1).and_then(|s| angle(s)) else {
1098                            return false;
1099                        };
1100                        *from = deg(a);
1101                        i += 2;
1102                    }
1103                    "at" => {
1104                        let Some((px, py)) = position(&w[i + 1..]) else {
1105                            return false;
1106                        };
1107                        (*x, *y) = (Percentage(px), Percentage(py));
1108                        return true;
1109                    }
1110                    _ => return any,
1111                }
1112                any = true;
1113            }
1114            any
1115        }
1116    }
1117}
1118
1119/// A position (`center`, `top left`, `25% 75%`) as fractions of the box.
1120pub(crate) fn position(w: &[&str]) -> Option<(f32, f32)> {
1121    let (mut x, mut y) = (0.5, 0.5);
1122    let mut xs = Vec::new();
1123    for word in w {
1124        match *word {
1125            "left" => x = 0.0,
1126            "right" => x = 1.0,
1127            "top" => y = 0.0,
1128            "bottom" => y = 1.0,
1129            "center" => {}
1130            p => xs.push(amount(p)?),
1131        }
1132    }
1133    match xs.as_slice() {
1134        [] => {}
1135        [a] => x = *a,
1136        [a, b] => (x, y) = (*a, *b),
1137        _ => return None,
1138    }
1139    Some((x, y))
1140}
1141
1142/// A `clip-path` `inset()` shape (CSS Shapes'): one to four lengths or
1143/// percentages for the edges, as `margin` takes them, then optionally
1144/// `round` and one to four radii, as `border-radius` takes them (in
1145/// points: no percentages, no `/` for elliptical corners).
1146pub(crate) fn clip_inset(s: &str) -> Option<crate::effects::ClipInset> {
1147    let args = s.trim().strip_prefix("inset(")?.strip_suffix(')')?.trim();
1148    let words = words(args);
1149    let round = words.iter().position(|w| *w == "round");
1150    let (edges, radii) = match round {
1151        Some(i) => (&words[..i], Some(&words[i + 1..])),
1152        None => (&words[..], None),
1153    };
1154    let edges = edges
1155        .iter()
1156        .map(|w| length_or_percent(w))
1157        .collect::<Option<Vec<_>>>()?;
1158    let [top, right, bottom, left] = sides(&edges)?;
1159    let mut clip = crate::effects::ClipInset::new()
1160        .top(top)
1161        .right(right)
1162        .bottom(bottom)
1163        .left(left);
1164    if let Some(radii) = radii {
1165        let radii = radii
1166            .iter()
1167            .map(|w| length(w).filter(|r| *r >= 0.0).map(px))
1168            .collect::<Option<Vec<_>>>()?;
1169        // `border-radius` spreads its values over the corners from the top
1170        // left as the box shorthands do over the edges from the top.
1171        let [top_left, top_right, bottom_right, bottom_left] = sides(&radii)?;
1172        clip = clip.corner_radii(crate::geometry::Corners {
1173            top_left,
1174            top_right,
1175            bottom_right,
1176            bottom_left,
1177        });
1178    }
1179    Some(clip)
1180}
1181
1182/// One to four values as CSS's box shorthands spread them: top, right,
1183/// bottom, left.
1184fn sides<T: Copy>(v: &[T]) -> Option<[T; 4]> {
1185    Some(match *v {
1186        [a] => [a, a, a, a],
1187        [a, b] => [a, b, a, b],
1188        [a, b, c] => [a, b, c, b],
1189        [a, b, c, d] => [a, b, c, d],
1190        _ => return None,
1191    })
1192}
1193
1194/// An `object-position` (CSS's `<position>`): one value (`top`, `25%`,
1195/// the other axis centered), two (`left bottom`, `bottom left`, `25% 10px`,
1196/// `right 30%`: horizontal first unless both are keywords) or four, edges
1197/// with offsets (`right 10px bottom 20%`, either axis first). Three values
1198/// are not a `<position>`, as in browsers.
1199pub(crate) fn object_position(s: &str) -> Option<ObjectPosition> {
1200    use crate::style::PositionAxis as A;
1201    #[derive(Clone, Copy, PartialEq)]
1202    enum Word {
1203        Left,
1204        Right,
1205        Top,
1206        Bottom,
1207        Center,
1208        Length(DefiniteLength),
1209    }
1210    let word = |w: &str| -> Option<Word> {
1211        Some(match w {
1212            "left" => Word::Left,
1213            "right" => Word::Right,
1214            "top" => Word::Top,
1215            "bottom" => Word::Bottom,
1216            "center" => Word::Center,
1217            w => Word::Length(length_or_percent(w)?),
1218        })
1219    };
1220    let horizontal = |w: Word| -> Option<A> {
1221        match w {
1222            Word::Left => Some(A::START),
1223            Word::Center => Some(A::CENTER),
1224            Word::Right => Some(A::END),
1225            Word::Length(l) => Some(A::start(l)),
1226            _ => None,
1227        }
1228    };
1229    let vertical = |w: Word| -> Option<A> {
1230        match w {
1231            Word::Top => Some(A::START),
1232            Word::Center => Some(A::CENTER),
1233            Word::Bottom => Some(A::END),
1234            Word::Length(l) => Some(A::start(l)),
1235            _ => None,
1236        }
1237    };
1238    let words: Vec<&str> = s.split_whitespace().collect();
1239    let (x, y) = match words.as_slice() {
1240        [a] => match word(a)? {
1241            w @ (Word::Top | Word::Bottom) => (A::CENTER, vertical(w)?),
1242            w => (horizontal(w)?, A::CENTER),
1243        },
1244        [a, b] => {
1245            let (a, b) = (word(a)?, word(b)?);
1246            // Two keywords go in either order (`top left`).
1247            let keyword = |w: Word| !matches!(w, Word::Length(_));
1248            let swapped = keyword(a)
1249                && keyword(b)
1250                && (matches!(a, Word::Top | Word::Bottom) || matches!(b, Word::Left | Word::Right));
1251            let (a, b) = if swapped { (b, a) } else { (a, b) };
1252            (horizontal(a)?, vertical(b)?)
1253        }
1254        [e1, o1, e2, o2] => {
1255            let mut x = None;
1256            let mut y = None;
1257            for (edge, o) in [(*e1, *o1), (*e2, *o2)] {
1258                let o = length_or_percent(o)?;
1259                let (slot, axis) = match edge {
1260                    "left" => (&mut x, A::start(o)),
1261                    "right" => (&mut x, A::end(o)),
1262                    "top" => (&mut y, A::start(o)),
1263                    "bottom" => (&mut y, A::end(o)),
1264                    _ => return None,
1265                };
1266                if slot.replace(axis).is_some() {
1267                    return None;
1268                }
1269            }
1270            (x?, y?)
1271        }
1272        _ => return None,
1273    };
1274    Some(ObjectPosition::new(x, y))
1275}
1276
1277/// A `filter` list (`none` is empty).
1278pub(crate) fn filters(s: &str) -> Option<Vec<Filter>> {
1279    Some(filter_list(s)?.into_iter().map(|(f, _)| f).collect())
1280}
1281
1282/// A `filter` list, each function with whether it names its color: a
1283/// `drop-shadow()` without one is black here, CSS's `currentColor` for a
1284/// style to fill in.
1285pub(crate) fn filter_list(s: &str) -> Option<Vec<(Filter, bool)>> {
1286    let s = s.trim();
1287    if s.is_empty() || s == "none" {
1288        return Some(Vec::new());
1289    }
1290    words(s).into_iter().map(filter).collect()
1291}
1292
1293fn filter(s: &str) -> Option<(Filter, bool)> {
1294    let open = s.find('(')?;
1295    let name = &s[..open];
1296    let arg = s[open + 1..].strip_suffix(')')?.trim();
1297    let factor = |default: f32| {
1298        if arg.is_empty() {
1299            Some(default)
1300        } else {
1301            amount(arg)
1302        }
1303    };
1304    let mut named = true;
1305    let filter = match name {
1306        "blur" => Filter::Blur(px(if arg.is_empty() { 0.0 } else { length(arg)? })),
1307        "brightness" => Filter::Brightness(factor(1.0)?),
1308        "contrast" => Filter::Contrast(factor(1.0)?),
1309        "grayscale" => Filter::Grayscale(factor(1.0)?.clamp(0.0, 1.0)),
1310        "hue-rotate" => Filter::HueRotate(deg(if arg.is_empty() { 0.0 } else { angle(arg)? })),
1311        "invert" => Filter::Invert(factor(1.0)?.clamp(0.0, 1.0)),
1312        "opacity" => Filter::Opacity(factor(1.0)?.clamp(0.0, 1.0)),
1313        "saturate" => Filter::Saturate(factor(1.0)?),
1314        "sepia" => Filter::Sepia(factor(1.0)?.clamp(0.0, 1.0)),
1315        "drop-shadow" => {
1316            let (s, colored) = shadow_layer(arg)?;
1317            named = colored;
1318            Filter::DropShadow {
1319                offset_x: s.offset_x,
1320                offset_y: s.offset_y,
1321                blur: s.blur,
1322                color: s.color,
1323            }
1324        }
1325        _ => return None,
1326    };
1327    Some((filter, named))
1328}
1329
1330#[cfg(test)]
1331mod tests {
1332    use super::*;
1333
1334    #[test]
1335    fn current_color_in_values() {
1336        assert!(mentions_current_color(
1337            "color-mix(in srgb, CurrentColor 50%, red)"
1338        ));
1339        // Part of a longer name: not the keyword.
1340        assert!(!mentions_current_color("var(--currentcolor) currentcolors"));
1341        assert_eq!(
1342            with_current_color("0 1px currentColor, 0 2px currentcolor", Color(0x1234_56ff)),
1343            "0 1px #123456ff, 0 2px #123456ff"
1344        );
1345    }
1346
1347    #[test]
1348    fn object_positions() {
1349        use crate::style::PositionAxis as A;
1350        let p = |s: &str| object_position(s).unwrap_or_else(|| panic!("{s}"));
1351        let l = |v: f32| DefiniteLength::from(px(v));
1352        let f = |v: f32| DefiniteLength::from(percentage(v));
1353        let at = ObjectPosition::new;
1354        assert_eq!(p("center"), ObjectPosition::CENTER);
1355        assert_eq!(p("top"), at(A::CENTER, A::START));
1356        assert_eq!(p("bottom"), at(A::CENTER, A::END));
1357        assert_eq!(p("left"), at(A::START, A::CENTER));
1358        assert_eq!(p("25%"), at(A::start(f(0.25)), A::CENTER));
1359        assert_eq!(p("left top"), at(A::START, A::START));
1360        assert_eq!(p("top left"), at(A::START, A::START));
1361        assert_eq!(p("bottom right"), at(A::END, A::END));
1362        assert_eq!(p("center top"), at(A::CENTER, A::START));
1363        assert_eq!(p("top center"), at(A::CENTER, A::START));
1364        assert_eq!(p("25% 75%"), at(A::start(f(0.25)), A::start(f(0.75))));
1365        assert_eq!(p("10px 1rem"), at(A::start(l(10.0)), A::start(l(16.0))));
1366        assert_eq!(p("right 30%"), at(A::END, A::start(f(0.3))));
1367        assert_eq!(
1368            p("right 10px bottom 20%"),
1369            at(A::end(l(10.0)), A::end(f(0.2)))
1370        );
1371        assert_eq!(
1372            p("bottom 20% right 10px"),
1373            at(A::end(l(10.0)), A::end(f(0.2)))
1374        );
1375        // Not `<position>`s, as in browsers.
1376        for bad in [
1377            "",
1378            "middle",
1379            "left right",
1380            "top bottom",
1381            "10px left",
1382            "top 10px",
1383            "left 10px top",
1384            "center 10px top 5px",
1385            "left 10px left 5px",
1386            "1 2 3 4 5",
1387        ] {
1388            assert!(object_position(bad).is_none(), "{bad}");
1389        }
1390        // Written back as CSS, it reads the same.
1391        for s in ["top left", "25% 75%", "right 10px bottom 20%", "center"] {
1392            let v = p(s);
1393            assert_eq!(p(&v.to_string()), v, "{s}");
1394        }
1395    }
1396
1397    #[test]
1398    fn object_positions_place_content() {
1399        use crate::geometry::{point, size};
1400        let at = |s: &str| {
1401            // A 100x300 image covering a 100x100 box.
1402            object_position(s)
1403                .unwrap()
1404                .place(size(px(100.0), px(100.0)), size(px(100.0), px(300.0)))
1405        };
1406        assert_eq!(at("center"), point(px(0.0), px(-100.0)));
1407        assert_eq!(at("top"), point(px(0.0), px(0.0)));
1408        assert_eq!(at("bottom"), point(px(0.0), px(-200.0)));
1409        assert_eq!(at("left 10px top 25%"), point(px(10.0), px(-50.0)));
1410        assert_eq!(at("right 10px bottom 10px"), point(px(-10.0), px(-210.0)));
1411    }
1412
1413    /// The packed values CSS colors had before the Rust API took `Hsla`
1414    /// (`crate::color`): TSX apps render as they did.
1415    #[test]
1416    fn css_colors_keep_their_packed_values() {
1417        for (css, packed) in [
1418            ("#fff", 0xffffffff),
1419            ("#0000", 0x00000000),
1420            ("#1a2b3c", 0x1a2b3cff),
1421            ("#1a2b3c80", 0x1a2b3c80),
1422            ("rgb(255, 0, 10)", 0xff000aff),
1423            ("rgb(0 0 0 / 0.1)", 0x0000001a),
1424            ("rgba(0,0,0,0.5)", 0x00000080),
1425            ("rgb(50% 25% 12.5%)", 0x804020ff),
1426            ("rgb(12.7 200.4 99.5)", 0x0dc864ff),
1427            ("hsl(0 100% 50%)", 0xff0000ff),
1428            ("hsl(120, 100%, 25%)", 0x008000ff),
1429            ("hsl(240 100% 50%)", 0x0000ffff),
1430            ("hsl(200 50% 50%)", 0x4095bfff),
1431            ("hsl(30 80% 60% / 0.4)", 0xeb994766),
1432            ("hsl(-30 80% 60%)", 0xeb4799ff),
1433            ("hsl(390 80% 60%)", 0xeb9947ff),
1434            ("hsl(0.5turn 33% 77%)", 0xb1d8d8ff),
1435            ("hsl(1rad 20% 30%)", 0x5c5a3dff),
1436            ("hsla(210, 40%, 96%, 0.85)", 0xf1f5f9d9),
1437            ("hsl(359.9 100% 50%)", 0xff0000ff),
1438            ("hsl(17 3% 97%)", 0xf8f7f7ff),
1439            ("hsl(222.2 84% 4.9%)", 0x020817ff),
1440            ("hsl(217.2 91.2% 59.8%)", 0x3b82f6ff),
1441            ("hsl(0 0% 50%)", 0x808080ff),
1442            ("hsl(60 100% 100%)", 0xffffffff),
1443            ("hsl(300 76% 72%)", 0xee81eeff),
1444            ("hsl(45deg 93% 47%)", 0xe7b008ff),
1445            ("hsl(160 84% 39% / 50%)", 0x10b77f80),
1446            ("oklch(62.3% 0.214 259.815)", 0x2b7fffff),
1447            ("oklab(1 0 0)", 0xffffffff),
1448            ("oklch(0.7 0.1 30 / 0.5)", 0xd5867980),
1449            ("RebeccaPurple", 0x663399ff),
1450            ("transparent", 0x00000000),
1451            ("teal", 0x008080ff),
1452        ] {
1453            assert_eq!(color(css), Some(Color(packed)), "{css}");
1454            // And through the Rust API's colors.
1455            let hsla: crate::Hsla = css.parse().unwrap();
1456            assert_eq!(Color::from(hsla), Color(packed), "{css}");
1457        }
1458    }
1459
1460    #[test]
1461    fn colors() {
1462        assert_eq!(color("#fff"), Some(Color(0xffff_ffff)));
1463        assert_eq!(color("rgb(255, 0, 10)"), Some(Color(0xff00_0aff)));
1464        assert_eq!(color("rgb(0 0 0 / 0.1)"), Some(Color(0x0000_001a)));
1465        assert_eq!(color("rgba(0,0,0,0.5)"), Some(Color(0x0000_0080)));
1466        assert_eq!(color("hsl(0 100% 50%)"), Some(Color(0xff00_00ff)));
1467        assert_eq!(color("hsl(120, 100%, 25%)"), Some(Color(0x0080_00ff)));
1468        assert_eq!(color("RebeccaPurple"), Some(Color(0x6633_99ff)));
1469        assert_eq!(color("transparent"), Some(Color::TRANSPARENT));
1470        // Tailwind's blue-500.
1471        assert_eq!(
1472            color("oklch(62.3% 0.214 259.815)"),
1473            Some(Color(0x2b7f_ffff))
1474        );
1475        assert_eq!(color("oklab(1 0 0)"), Some(Color(0xffff_ffff)));
1476        assert_eq!(color("nope"), None);
1477    }
1478
1479    /// Whether two packed colors differ by at most one step per channel:
1480    /// mixes of polar colors go through 8-bit inputs and `f32` math.
1481    fn near(a: Option<Color>, b: Option<Color>) -> bool {
1482        let (Some(Color(a)), Some(Color(b))) = (a, b) else {
1483            return false;
1484        };
1485        (0..4).all(|i| ((a >> (i * 8)) & 0xff).abs_diff((b >> (i * 8)) & 0xff) <= 1)
1486    }
1487
1488    /// `color-mix()`, against what CSS Color 5 and browsers compute.
1489    #[test]
1490    fn color_mix() {
1491        for (css, packed) in [
1492            // Both percentages omitted: 50 / 50.
1493            ("color-mix(in srgb, red, blue)", 0x800080ff),
1494            ("COLOR-MIX(IN SRGB, red, blue)", 0x800080ff),
1495            // One omitted: the rest of 100%, before or after the color.
1496            ("color-mix(in srgb, red 25%, blue)", 0x4000bfff),
1497            ("color-mix(in srgb, 25% red, blue)", 0x4000bfff),
1498            ("color-mix(in srgb, red, blue 75%)", 0x4000bfff),
1499            ("color-mix(in srgb, red 100%, blue)", 0xff0000ff),
1500            // A sum below 100%: scaled, and the result's alpha times the sum.
1501            ("color-mix(in srgb, red 20%, blue 30%)", 0x66009980),
1502            // A sum above 100%: scaled, alpha kept.
1503            ("color-mix(in srgb, red 75%, blue 75%)", 0x800080ff),
1504            // Premultiplied alpha: transparent only lowers the alpha.
1505            ("color-mix(in srgb, #ff0000 30%, transparent)", 0xff00004d),
1506            ("color-mix(in oklab, transparent, #3b82f6)", 0x3b82f680),
1507            ("color-mix(in oklch, transparent, #3b82f6 40%)", 0x3b82f666),
1508            (
1509                "color-mix(in srgb, rgb(255 0 0 / 0.5), rgb(0 0 255))",
1510                0x5500aabf,
1511            ),
1512            ("color-mix(in srgb-linear, red, blue)", 0xbc00bcff),
1513            ("color-mix(in xyz, red, blue)", 0xbc00bcff),
1514            ("color-mix(in oklab, white, black)", 0x636363ff),
1515            // HSL hues: shorter and longer ways around.
1516            (
1517                "color-mix(in hsl, hsl(350 100% 50%), hsl(30 100% 50%))",
1518                0xff2b00ff,
1519            ),
1520            (
1521                "color-mix(in hsl longer hue, hsl(350 100% 50%), hsl(30 100% 50%))",
1522                0x00d5ffff,
1523            ),
1524            // Nested.
1525            (
1526                "color-mix(in srgb, color-mix(in srgb, red, blue), black)",
1527                0x400040ff,
1528            ),
1529        ] {
1530            assert!(
1531                near(color(css), Some(Color(packed))),
1532                "{css}: {:x?}",
1533                color(css)
1534            );
1535        }
1536        // OKLCh hue interpolation, against the colors it should land on.
1537        let a = "oklch(0.7 0.1 350)";
1538        let b = "oklch(0.7 0.1 30)";
1539        for (method, expected) in [
1540            ("", "oklch(0.7 0.1 10)"),
1541            (" shorter hue", "oklch(0.7 0.1 10)"),
1542            (" longer hue", "oklch(0.7 0.1 190)"),
1543            (" increasing hue", "oklch(0.7 0.1 10)"),
1544            (" decreasing hue", "oklch(0.7 0.1 190)"),
1545        ] {
1546            let css = format!("color-mix(in oklch{method}, {a}, {b})");
1547            assert!(
1548                near(color(&css), color(expected)),
1549                "{css}: {:x?}",
1550                color(&css)
1551            );
1552        }
1553        // A grey's hue is powerless: the mix keeps the other color's.
1554        assert!(near(
1555            color("color-mix(in oklch, white, oklch(0.7 0.1 30))"),
1556            color("oklch(0.85 0.05 30)")
1557        ));
1558        assert!(near(
1559            color("color-mix(in hsl, white, hsl(120 100% 50%))"),
1560            color("hsl(120 50% 75%)")
1561        ));
1562        for css in [
1563            "color-mix(in srgb, red 0%, blue 0%)",
1564            "color-mix(in srgb, red -10%, blue)",
1565            "color-mix(in srgb, red 120%, blue)",
1566            "color-mix(in srgb, red 10% 20%, blue)",
1567            "color-mix(in srgb, red 10, blue)",
1568            "color-mix(srgb, red, blue)",
1569            "color-mix(in nope, red, blue)",
1570            "color-mix(in srgb shorter hue, red, blue)",
1571            "color-mix(in oklch sideways hue, red, blue)",
1572            "color-mix(in oklch shorter, red, blue)",
1573            "color-mix(in srgb, red)",
1574            "color-mix(in srgb, red, blue, green)",
1575            "color-mix(in srgb, red, nope)",
1576        ] {
1577            assert_eq!(color(css), None, "{css}");
1578        }
1579    }
1580
1581    #[test]
1582    fn shadows() {
1583        let s = box_shadows("0 1px 3px 0 rgb(0 0 0 / 0.1), inset 0 1px 2px -1px #f00").unwrap();
1584        assert_eq!(s.len(), 2);
1585        assert_eq!(
1586            (s[0].offset_y, s[0].blur, s[0].spread),
1587            (px(1.0), px(3.0), px(0.0))
1588        );
1589        assert_eq!(s[0].color, Color(0x0000_001a));
1590        assert!(s[1].inset);
1591        assert_eq!(s[1].spread, px(-1.0));
1592        assert_eq!(s[1].color, Color(0xff00_00ff));
1593        assert!(box_shadows("none").unwrap().is_empty());
1594        assert!(box_shadows("1px").is_none());
1595    }
1596
1597    /// `cargo test --release -p nsh-core bench_gradient_oklab -- --ignored
1598    /// --nocapture`: the stops a Tailwind gradient gets, sampled in Oklab,
1599    /// which its node's styling pays each time its classes apply.
1600    #[test]
1601    #[ignore]
1602    fn bench_gradient_oklab() {
1603        use crate::geometry::percentage;
1604        let stops = |c: [u32; 3]| {
1605            [0.0, 0.4, 1.0]
1606                .iter()
1607                .zip(c)
1608                .map(|(&p, c)| ColorStop {
1609                    color: Color(c),
1610                    position: Some(percentage(p).into()),
1611                })
1612                .collect::<Vec<_>>()
1613        };
1614        for c in [
1615            [0x2b7f_ffff, 0xad46_ffff, 0xf633_9aff],
1616            [0xff00_00ff, 0x00ff_00ff, 0x0000_ffff],
1617            [0x1818_1bff, 0x2727_2aff, 0],
1618        ] {
1619            let n = interpolate_stops(stops(c), Interpolation::OKLAB).len();
1620            let t = std::time::Instant::now();
1621            for _ in 0..1000 {
1622                std::hint::black_box(interpolate_stops(stops(c), Interpolation::OKLAB));
1623            }
1624            println!("{c:08x?}: {n} stops, {:?} per gradient", t.elapsed() / 1000);
1625        }
1626    }
1627
1628    #[test]
1629    fn gradient_syntax() {
1630        let g = gradient("linear-gradient(to right, #f00, rgb(0 0 255) 80%)").unwrap();
1631        assert_eq!(g.kind, GradientKind::Linear { angle: deg(90.0) });
1632        assert_eq!(g.stops[1].position, Some(percentage(0.8).into()));
1633        let g = gradient("linear-gradient(45deg in oklab, red, blue)").unwrap();
1634        assert_eq!(g.kind, GradientKind::Linear { angle: deg(45.0) });
1635        // `in oklab` mixes in Oklab: stops sampled there are placed between
1636        // the two, the halfway one CSS's `color-mix(in oklab, red, blue)`.
1637        assert!(g.stops.len() > 2);
1638        let half = g
1639            .stops
1640            .iter()
1641            .find(|s| s.position == Some(percentage(0.5).into()))
1642            .unwrap();
1643        assert_eq!(half.color, color("color-mix(in oklab, red, blue)").unwrap());
1644        // In sRGB (or saying nothing, legacy colors), the platforms' own.
1645        for g in [
1646            "linear-gradient(in srgb, red, blue)",
1647            "linear-gradient(red, blue)",
1648            "linear-gradient(#f00, rgb(0 0 255), hsl(120 100% 50%))",
1649            "linear-gradient(in srgb, oklch(60% 0.2 30), blue)",
1650        ] {
1651            assert!(gradient(g).unwrap().stops.len() <= 3, "{g}");
1652        }
1653        // Saying nothing with a modern color, Oklab (CSS Color 4).
1654        assert!(
1655            gradient("linear-gradient(oklch(60% 0.2 30), blue)")
1656                .unwrap()
1657                .stops
1658                .len()
1659                > 2
1660        );
1661        let g = gradient("linear-gradient(to right in oklch longer hue, red, blue)").unwrap();
1662        assert_eq!(g.kind, GradientKind::Linear { angle: deg(90.0) });
1663        assert!(g.stops.len() >= 5);
1664        // The method before the direction, and in any case.
1665        for g in [
1666            "linear-gradient(in oklch longer hue to right, red, blue)",
1667            "linear-gradient(IN OKLCH LONGER HUE to right, red, blue)",
1668        ] {
1669            let g = gradient(g).unwrap();
1670            assert_eq!(g.kind, GradientKind::Linear { angle: deg(90.0) }, "{g:?}");
1671            assert!(g.stops.len() >= 5);
1672        }
1673        let g = gradient("radial-gradient(in oklab circle at 25% 75%, red, blue)").unwrap();
1674        assert!(matches!(g.kind, GradientKind::Radial { circle: true, .. }));
1675        assert!(g.stops.len() > 2);
1676        let g = gradient("linear-gradient(in hsl, red 0 10px, blue 30px)").unwrap();
1677        assert_eq!(g.stops[1].position, Some(px(10.0).into()));
1678        assert!(g.stops.len() > 3);
1679        assert_eq!(g.stops.last().unwrap().position, Some(px(30.0).into()));
1680        // A space NSH does not mix in is no gradient (a browser's is).
1681        assert!(gradient("linear-gradient(in display-p3, red, blue)").is_none());
1682        // A stop holding `in` inside a function is a stop.
1683        assert!(gradient("linear-gradient(color-mix( in srgb, red, blue), blue)").is_some());
1684        let g = gradient("radial-gradient(circle at 25% 75%, red, blue)").unwrap();
1685        assert_eq!(
1686            g.kind,
1687            GradientKind::Radial {
1688                circle: true,
1689                size: GradientSize::FarthestCorner,
1690                x: percentage(0.25),
1691                y: percentage(0.75)
1692            }
1693        );
1694        let g = gradient("conic-gradient(from 90deg, red, blue, red)").unwrap();
1695        assert_eq!(g.stops.len(), 3);
1696        assert!(gradient("linear-gradient(red)").unwrap().stops.len() == 2);
1697    }
1698
1699    #[test]
1700    fn gradient_stop_positions() {
1701        let at = |g: &Gradient| g.stops.iter().map(|s| s.position).collect::<Vec<_>>();
1702        let fraction = |f: f32| DefiniteLength::from(percentage(f));
1703        let points = |p: f32| DefiniteLength::from(px(p));
1704        let g = gradient("repeating-linear-gradient(90deg, red 0px, blue 10px)").unwrap();
1705        assert!(g.repeating);
1706        assert_eq!(at(&g), [Some(fraction(0.0)), Some(points(10.0))]);
1707        // Lengths in every unit, mixed with percentages; two positions
1708        // make a band.
1709        let g = gradient("linear-gradient(red 0 1rem, blue 50%, green 2pt)").unwrap();
1710        assert_eq!(
1711            at(&g),
1712            [
1713                Some(fraction(0.0)),
1714                Some(points(16.0)),
1715                Some(fraction(0.5)),
1716                Some(points(8.0 / 3.0))
1717            ]
1718        );
1719        let g = gradient("radial-gradient(circle, red 4px, blue 20px)").unwrap();
1720        assert_eq!(at(&g), [Some(points(4.0)), Some(points(20.0))]);
1721        // Conic stops are angles (as fractions of a turn) or percentages.
1722        let g = gradient("conic-gradient(red 0deg 90deg, blue 0.5turn, green 75%)").unwrap();
1723        assert_eq!(
1724            at(&g),
1725            [
1726                Some(fraction(0.0)),
1727                Some(fraction(0.25)),
1728                Some(fraction(0.5)),
1729                Some(fraction(0.75))
1730            ]
1731        );
1732        assert!(gradient("conic-gradient(red 10px, blue)").is_none());
1733        assert!(gradient("linear-gradient(red 90deg, blue)").is_none());
1734        assert!(gradient("linear-gradient(red 0 10px 20px, blue)").is_none());
1735    }
1736
1737    #[test]
1738    fn filter_lists() {
1739        let f = filters("blur(4px) brightness(120%) hue-rotate(90deg) drop-shadow(0 1px 2px #000)")
1740            .unwrap();
1741        assert_eq!(f[0], Filter::Blur(px(4.0)));
1742        assert_eq!(f[1], Filter::Brightness(1.2));
1743        assert_eq!(f[2], Filter::HueRotate(deg(90.0)));
1744        assert!(matches!(
1745            f[3],
1746            Filter::DropShadow {
1747                blur: crate::geometry::Points(2.0),
1748                ..
1749            }
1750        ));
1751    }
1752
1753    #[test]
1754    fn units() {
1755        assert_eq!(length("0.5rem"), Some(8.0));
1756        // CSS's absolute units: 1pt is 1/72 of an inch, 4/3 of a pixel.
1757        assert_eq!(length("12pt"), Some(16.0));
1758        assert_eq!(angle("0.25turn"), Some(90.0));
1759        assert_eq!(words("a rgb(0 0 0) b"), ["a", "rgb(0 0 0)", "b"]);
1760        assert_eq!(split_top("a(1,2), b", ','), ["a(1,2)", "b"]);
1761    }
1762}