1
//! CSS properties for backgrounds, including colors, images, and gradients.
2

            
3
use alloc::{
4
    string::{String, ToString},
5
    vec::Vec,
6
};
7
use core::fmt;
8

            
9
#[cfg(feature = "parser")]
10
use crate::props::basic::{
11
    color::parse_color_or_system,
12
    error::{InvalidValueErr, InvalidValueErrOwned},
13
    parse::{
14
        parse_image, parse_parentheses, split_string_respect_comma, CssImageParseError,
15
        CssImageParseErrorOwned, ParenthesisParseError, ParenthesisParseErrorOwned,
16
    },
17
};
18
use crate::{
19
    codegen::format::GetHash,
20
    corety::AzString,
21
    props::{
22
        basic::{
23
            angle::{
24
                parse_angle_value, AngleValue, CssAngleValueParseError,
25
                CssAngleValueParseErrorOwned, OptionAngleValue,
26
            },
27
            color::{
28
                ColorOrSystem, ColorU, CssColorParseError, CssColorParseErrorOwned, SystemColorRef,
29
            },
30
            direction::{
31
                parse_direction, CssDirectionParseError, CssDirectionParseErrorOwned, Direction,
32
            },
33
            length::{
34
                parse_percentage_value, OptionPercentageValue, PercentageParseError,
35
                PercentageParseErrorOwned, PercentageValue,
36
            },
37
            pixel::{
38
                parse_pixel_value, CssPixelValueParseError, CssPixelValueParseErrorOwned,
39
                PixelValue,
40
            },
41
        },
42
        formatter::PrintAsCssValue,
43
    },
44
};
45

            
46
// --- TYPE DEFINITIONS ---
47

            
48
/// Whether a `gradient` should be repeated or clamped to the edges.
49
#[derive(Debug, Copy, Clone, PartialEq, Ord, PartialOrd, Eq, Hash)]
50
#[repr(C)]
51
#[derive(Default)]
52
pub enum ExtendMode {
53
    #[default]
54
    Clamp,
55
    Repeat,
56
}
57

            
58
// -- Main Background Content Type --
59

            
60
/// A single CSS background layer: a solid color, image URL, or gradient.
61
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
62
#[repr(C, u8)]
63
pub enum StyleBackgroundContent {
64
    LinearGradient(LinearGradient),
65
    RadialGradient(RadialGradient),
66
    ConicGradient(ConicGradient),
67
    Image(AzString),
68
    Color(ColorU),
69
    /// A theme-aware system color (e.g. `background: system:accent`), kept unresolved
70
    /// and resolved at render time. Mirrors the `ColorOrSystem::System` value that
71
    /// gradient color stops already accept.
72
    SystemColor(SystemColorRef),
73
}
74

            
75
impl_option!(
76
    StyleBackgroundContent,
77
    OptionStyleBackgroundContent,
78
    copy = false,
79
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
80
);
81

            
82
impl_vec!(
83
    StyleBackgroundContent,
84
    StyleBackgroundContentVec,
85
    StyleBackgroundContentVecDestructor,
86
    StyleBackgroundContentVecDestructorType,
87
    StyleBackgroundContentVecSlice,
88
    OptionStyleBackgroundContent
89
);
90
impl_vec_debug!(StyleBackgroundContent, StyleBackgroundContentVec);
91
impl_vec_partialord!(StyleBackgroundContent, StyleBackgroundContentVec);
92
impl_vec_ord!(StyleBackgroundContent, StyleBackgroundContentVec);
93
impl_vec_clone!(
94
    StyleBackgroundContent,
95
    StyleBackgroundContentVec,
96
    StyleBackgroundContentVecDestructor
97
);
98
impl_vec_partialeq!(StyleBackgroundContent, StyleBackgroundContentVec);
99
impl_vec_eq!(StyleBackgroundContent, StyleBackgroundContentVec);
100
impl_vec_hash!(StyleBackgroundContent, StyleBackgroundContentVec);
101

            
102
impl Default for StyleBackgroundContent {
103
1
    fn default() -> Self {
104
1
        Self::Color(ColorU::TRANSPARENT)
105
1
    }
106
}
107

            
108
impl PrintAsCssValue for StyleBackgroundContent {
109
238
    fn print_as_css_value(&self) -> String {
110
238
        match self {
111
8
            Self::LinearGradient(lg) => {
112
8
                let prefix = if lg.extend_mode == ExtendMode::Repeat {
113
3
                    "repeating-linear-gradient"
114
                } else {
115
5
                    "linear-gradient"
116
                };
117
8
                format!("{}({})", prefix, lg.print_as_css_value())
118
            }
119
3
            Self::RadialGradient(rg) => {
120
3
                let prefix = if rg.extend_mode == ExtendMode::Repeat {
121
                    "repeating-radial-gradient"
122
                } else {
123
3
                    "radial-gradient"
124
                };
125
3
                format!("{}({})", prefix, rg.print_as_css_value())
126
            }
127
5
            Self::ConicGradient(cg) => {
128
5
                let prefix = if cg.extend_mode == ExtendMode::Repeat {
129
2
                    "repeating-conic-gradient"
130
                } else {
131
3
                    "conic-gradient"
132
                };
133
5
                format!("{}({})", prefix, cg.print_as_css_value())
134
            }
135
2
            Self::Image(id) => format!("url(\"{}\")", id.as_str()),
136
218
            Self::Color(c) => c.to_hash(),
137
2
            Self::SystemColor(s) => s.as_css_str().to_string(),
138
        }
139
238
    }
140
}
141

            
142
// Formatting to Rust code for background-related vecs
143

            
144
impl crate::codegen::format::FormatAsRustCode for StyleBackgroundContent {
145
    fn format_as_rust_code(&self, _tabs: usize) -> String {
146
        // Delegate to the CSS value representation for single backgrounds
147
        format!(
148
            "StyleBackgroundContent::from_css(\"{}\")",
149
            self.print_as_css_value()
150
        )
151
    }
152
}
153

            
154
impl crate::codegen::format::FormatAsRustCode for StyleBackgroundSizeVec {
155
    fn format_as_rust_code(&self, _tabs: usize) -> String {
156
        format!(
157
            "StyleBackgroundSizeVec::from_const_slice(STYLE_BACKGROUND_SIZE_{}_ITEMS)",
158
            self.get_hash()
159
        )
160
    }
161
}
162

            
163
impl crate::codegen::format::FormatAsRustCode for StyleBackgroundRepeatVec {
164
    fn format_as_rust_code(&self, _tabs: usize) -> String {
165
        format!(
166
            "StyleBackgroundRepeatVec::from_const_slice(STYLE_BACKGROUND_REPEAT_{}_ITEMS)",
167
            self.get_hash()
168
        )
169
    }
170
}
171

            
172
impl crate::codegen::format::FormatAsRustCode for StyleBackgroundContentVec {
173
    fn format_as_rust_code(&self, _tabs: usize) -> String {
174
        format!(
175
            "StyleBackgroundContentVec::from_const_slice(STYLE_BACKGROUND_CONTENT_{}_ITEMS)",
176
            self.get_hash()
177
        )
178
    }
179
}
180

            
181
impl PrintAsCssValue for StyleBackgroundContentVec {
182
197
    fn print_as_css_value(&self) -> String {
183
197
        self.as_ref()
184
197
            .iter()
185
197
            .map(PrintAsCssValue::print_as_css_value)
186
197
            .collect::<Vec<_>>()
187
197
            .join(", ")
188
197
    }
189
}
190

            
191
// -- Gradient Types --
192

            
193
/// A CSS `linear-gradient()` or `repeating-linear-gradient()` value.
194
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
195
#[repr(C)]
196
pub struct LinearGradient {
197
    pub direction: Direction,
198
    pub extend_mode: ExtendMode,
199
    pub stops: NormalizedLinearColorStopVec,
200
}
201
impl Default for LinearGradient {
202
6253
    fn default() -> Self {
203
6253
        Self {
204
6253
            direction: Direction::default(),
205
6253
            extend_mode: ExtendMode::default(),
206
6253
            stops: Vec::new().into(),
207
6253
        }
208
6253
    }
209
}
210
impl PrintAsCssValue for LinearGradient {
211
8
    fn print_as_css_value(&self) -> String {
212
8
        let dir_str = self.direction.print_as_css_value();
213
8
        let stops_str = self
214
8
            .stops
215
8
            .iter()
216
8
            .map(PrintAsCssValue::print_as_css_value)
217
8
            .collect::<Vec<_>>()
218
8
            .join(", ");
219
8
        if stops_str.is_empty() {
220
2
            dir_str
221
        } else {
222
6
            format!("{dir_str}, {stops_str}")
223
        }
224
8
    }
225
}
226

            
227
/// A CSS `radial-gradient()` or `repeating-radial-gradient()` value.
228
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
229
#[repr(C)]
230
pub struct RadialGradient {
231
    pub shape: Shape,
232
    pub size: RadialGradientSize,
233
    pub position: StyleBackgroundPosition,
234
    pub extend_mode: ExtendMode,
235
    pub stops: NormalizedLinearColorStopVec,
236
}
237
impl Default for RadialGradient {
238
263
    fn default() -> Self {
239
263
        Self {
240
263
            shape: Shape::default(),
241
263
            size: RadialGradientSize::default(),
242
263
            position: StyleBackgroundPosition::default(),
243
263
            extend_mode: ExtendMode::default(),
244
263
            stops: Vec::new().into(),
245
263
        }
246
263
    }
247
}
248
impl PrintAsCssValue for RadialGradient {
249
3
    fn print_as_css_value(&self) -> String {
250
3
        let stops_str = self
251
3
            .stops
252
3
            .iter()
253
3
            .map(PrintAsCssValue::print_as_css_value)
254
3
            .collect::<Vec<_>>()
255
3
            .join(", ");
256
3
        format!(
257
3
            "{} {} at {}, {}",
258
            self.shape,
259
            self.size,
260
3
            self.position.print_as_css_value(),
261
            stops_str
262
        )
263
3
    }
264
}
265

            
266
/// A CSS `conic-gradient()` or `repeating-conic-gradient()` value.
267
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
268
#[repr(C)]
269
pub struct ConicGradient {
270
    pub extend_mode: ExtendMode,
271
    pub center: StyleBackgroundPosition,
272
    pub angle: AngleValue,
273
    pub stops: NormalizedRadialColorStopVec,
274
}
275
impl Default for ConicGradient {
276
256
    fn default() -> Self {
277
256
        Self {
278
256
            extend_mode: ExtendMode::default(),
279
256
            // CSS default for conic-gradient is `at center` (50% 50%), NOT the generic
280
256
            // Left/Top of StyleBackgroundPosition::default() — a corner-anchored cone maps
281
256
            // the whole element into one angular slice and renders a flat color.
282
256
            center: StyleBackgroundPosition {
283
256
                horizontal: BackgroundPositionHorizontal::Center,
284
256
                vertical: BackgroundPositionVertical::Center,
285
256
            },
286
256
            angle: AngleValue::default(),
287
256
            stops: Vec::new().into(),
288
256
        }
289
256
    }
290
}
291
impl PrintAsCssValue for ConicGradient {
292
5
    fn print_as_css_value(&self) -> String {
293
5
        let stops_str = self
294
5
            .stops
295
5
            .iter()
296
5
            .map(PrintAsCssValue::print_as_css_value)
297
5
            .collect::<Vec<_>>()
298
5
            .join(", ");
299
5
        format!(
300
5
            "from {} at {}, {}",
301
            self.angle,
302
5
            self.center.print_as_css_value(),
303
            stops_str
304
        )
305
5
    }
306
}
307

            
308
// -- Gradient Sub-types --
309

            
310
/// The shape of a radial gradient: `circle` or `ellipse`.
311
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
312
#[repr(C)]
313
#[derive(Default)]
314
pub enum Shape {
315
    #[default]
316
    Ellipse,
317
    Circle,
318
}
319
impl fmt::Display for Shape {
320
10
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321
10
        write!(
322
10
            f,
323
10
            "{}",
324
10
            match self {
325
5
                Self::Ellipse => "ellipse",
326
5
                Self::Circle => "circle",
327
            }
328
        )
329
10
    }
330
}
331

            
332
/// The sizing keyword for a radial gradient (e.g. `closest-side`, `farthest-corner`).
333
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
334
#[repr(C)]
335
#[derive(Default)]
336
pub enum RadialGradientSize {
337
    ClosestSide,
338
    ClosestCorner,
339
    FarthestSide,
340
    #[default]
341
    FarthestCorner,
342
}
343
impl fmt::Display for RadialGradientSize {
344
15
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345
15
        write!(
346
15
            f,
347
15
            "{}",
348
15
            match self {
349
3
                Self::ClosestSide => "closest-side",
350
3
                Self::ClosestCorner => "closest-corner",
351
3
                Self::FarthestSide => "farthest-side",
352
6
                Self::FarthestCorner => "farthest-corner",
353
            }
354
        )
355
15
    }
356
}
357

            
358
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
359
#[repr(C)]
360
pub struct NormalizedLinearColorStop {
361
    pub offset: PercentageValue,
362
    /// Color for this gradient stop. Can be a concrete color or a system color reference.
363
    pub color: ColorOrSystem,
364
}
365

            
366
impl NormalizedLinearColorStop {
367
    /// Create a new normalized linear color stop with a concrete color.
368
    #[must_use]
369
14
    pub const fn new(offset: PercentageValue, color: ColorU) -> Self {
370
14
        Self {
371
14
            offset,
372
14
            color: ColorOrSystem::color(color),
373
14
        }
374
14
    }
375

            
376
    /// Resolve the color against system colors.
377
    #[must_use]
378
15
    pub fn resolve(&self, system_colors: &crate::system::SystemColors, fallback: ColorU) -> ColorU {
379
15
        self.color.resolve(system_colors, fallback)
380
15
    }
381
}
382

            
383
impl_option!(
384
    NormalizedLinearColorStop,
385
    OptionNormalizedLinearColorStop,
386
    copy = false,
387
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
388
);
389
impl_vec!(
390
    NormalizedLinearColorStop,
391
    NormalizedLinearColorStopVec,
392
    NormalizedLinearColorStopVecDestructor,
393
    NormalizedLinearColorStopVecDestructorType,
394
    NormalizedLinearColorStopVecSlice,
395
    OptionNormalizedLinearColorStop
396
);
397
impl_vec_debug!(NormalizedLinearColorStop, NormalizedLinearColorStopVec);
398
impl_vec_partialord!(NormalizedLinearColorStop, NormalizedLinearColorStopVec);
399
impl_vec_ord!(NormalizedLinearColorStop, NormalizedLinearColorStopVec);
400
impl_vec_clone!(
401
    NormalizedLinearColorStop,
402
    NormalizedLinearColorStopVec,
403
    NormalizedLinearColorStopVecDestructor
404
);
405
impl_vec_partialeq!(NormalizedLinearColorStop, NormalizedLinearColorStopVec);
406
impl_vec_eq!(NormalizedLinearColorStop, NormalizedLinearColorStopVec);
407
impl_vec_hash!(NormalizedLinearColorStop, NormalizedLinearColorStopVec);
408
impl PrintAsCssValue for NormalizedLinearColorStop {
409
20
    fn print_as_css_value(&self) -> String {
410
20
        match &self.color {
411
18
            ColorOrSystem::Color(c) => format!("{} {}", c.to_hash(), self.offset),
412
2
            ColorOrSystem::System(s) => format!("{} {}", s.as_css_str(), self.offset),
413
        }
414
20
    }
415
}
416

            
417
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
418
#[repr(C)]
419
pub struct NormalizedRadialColorStop {
420
    pub angle: AngleValue,
421
    /// Color for this gradient stop. Can be a concrete color or a system color reference.
422
    pub color: ColorOrSystem,
423
}
424

            
425
impl NormalizedRadialColorStop {
426
    /// Create a new normalized radial color stop with a concrete color.
427
    #[must_use]
428
13
    pub const fn new(angle: AngleValue, color: ColorU) -> Self {
429
13
        Self {
430
13
            angle,
431
13
            color: ColorOrSystem::color(color),
432
13
        }
433
13
    }
434

            
435
    /// Resolve the color against system colors.
436
    #[must_use]
437
10
    pub fn resolve(&self, system_colors: &crate::system::SystemColors, fallback: ColorU) -> ColorU {
438
10
        self.color.resolve(system_colors, fallback)
439
10
    }
440
}
441

            
442
impl_option!(
443
    NormalizedRadialColorStop,
444
    OptionNormalizedRadialColorStop,
445
    copy = false,
446
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
447
);
448
impl_vec!(
449
    NormalizedRadialColorStop,
450
    NormalizedRadialColorStopVec,
451
    NormalizedRadialColorStopVecDestructor,
452
    NormalizedRadialColorStopVecDestructorType,
453
    NormalizedRadialColorStopVecSlice,
454
    OptionNormalizedRadialColorStop
455
);
456
impl_vec_debug!(NormalizedRadialColorStop, NormalizedRadialColorStopVec);
457
impl_vec_partialord!(NormalizedRadialColorStop, NormalizedRadialColorStopVec);
458
impl_vec_ord!(NormalizedRadialColorStop, NormalizedRadialColorStopVec);
459
impl_vec_clone!(
460
    NormalizedRadialColorStop,
461
    NormalizedRadialColorStopVec,
462
    NormalizedRadialColorStopVecDestructor
463
);
464
impl_vec_partialeq!(NormalizedRadialColorStop, NormalizedRadialColorStopVec);
465
impl_vec_eq!(NormalizedRadialColorStop, NormalizedRadialColorStopVec);
466
impl_vec_hash!(NormalizedRadialColorStop, NormalizedRadialColorStopVec);
467
impl PrintAsCssValue for NormalizedRadialColorStop {
468
10
    fn print_as_css_value(&self) -> String {
469
10
        match &self.color {
470
10
            ColorOrSystem::Color(c) => format!("{} {}", c.to_hash(), self.angle),
471
            ColorOrSystem::System(s) => format!("{} {}", s.as_css_str(), self.angle),
472
        }
473
10
    }
474
}
475

            
476
/// Transient struct for parsing linear color stops before normalization.
477
///
478
/// Per W3C CSS Images Level 3, a color stop can have 0, 1, or 2 positions:
479
/// - `red` (no position)
480
/// - `red 50%` (one position)
481
/// - `red 10% 30%` (two positions - creates two stops at same color)
482
///
483
/// Supports system colors like `system:accent` for theme-aware gradients.
484
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
485
pub struct LinearColorStop {
486
    pub color: ColorOrSystem,
487
    /// First position (optional)
488
    pub offset1: OptionPercentageValue,
489
    /// Second position (optional, only valid if offset1 is Some)
490
    /// When present, creates two color stops at the same color.
491
    pub offset2: OptionPercentageValue,
492
}
493

            
494
/// Transient struct for parsing radial/conic color stops before normalization.
495
///
496
/// Per W3C CSS Images Level 3, a color stop can have 0, 1, or 2 positions:
497
/// - `red` (no position)
498
/// - `red 90deg` (one position)
499
/// - `red 45deg 90deg` (two positions - creates two stops at same color)
500
///
501
/// Supports system colors like `system:accent` for theme-aware gradients.
502
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
503
pub struct RadialColorStop {
504
    pub color: ColorOrSystem,
505
    /// First position (optional)
506
    pub offset1: OptionAngleValue,
507
    /// Second position (optional, only valid if offset1 is Some)
508
    /// When present, creates two color stops at the same color.
509
    pub offset2: OptionAngleValue,
510
}
511

            
512
// -- Other Background Properties --
513

            
514
/// The `background-position` property (horizontal + vertical components).
515
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
516
#[repr(C)]
517
pub struct StyleBackgroundPosition {
518
    pub horizontal: BackgroundPositionHorizontal,
519
    pub vertical: BackgroundPositionVertical,
520
}
521

            
522
impl_option!(
523
    StyleBackgroundPosition,
524
    OptionStyleBackgroundPosition,
525
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
526
);
527
impl_vec!(
528
    StyleBackgroundPosition,
529
    StyleBackgroundPositionVec,
530
    StyleBackgroundPositionVecDestructor,
531
    StyleBackgroundPositionVecDestructorType,
532
    StyleBackgroundPositionVecSlice,
533
    OptionStyleBackgroundPosition
534
);
535
impl_vec_debug!(StyleBackgroundPosition, StyleBackgroundPositionVec);
536
impl_vec_partialord!(StyleBackgroundPosition, StyleBackgroundPositionVec);
537
impl_vec_ord!(StyleBackgroundPosition, StyleBackgroundPositionVec);
538
impl_vec_clone!(
539
    StyleBackgroundPosition,
540
    StyleBackgroundPositionVec,
541
    StyleBackgroundPositionVecDestructor
542
);
543
impl_vec_partialeq!(StyleBackgroundPosition, StyleBackgroundPositionVec);
544
impl_vec_eq!(StyleBackgroundPosition, StyleBackgroundPositionVec);
545
impl_vec_hash!(StyleBackgroundPosition, StyleBackgroundPositionVec);
546
impl Default for StyleBackgroundPosition {
547
282
    fn default() -> Self {
548
282
        Self {
549
282
            horizontal: BackgroundPositionHorizontal::Left,
550
282
            vertical: BackgroundPositionVertical::Top,
551
282
        }
552
282
    }
553
}
554

            
555
impl StyleBackgroundPosition {
556
8
    pub fn scale_for_dpi(&mut self, scale_factor: f32) {
557
8
        self.horizontal.scale_for_dpi(scale_factor);
558
8
        self.vertical.scale_for_dpi(scale_factor);
559
8
    }
560
}
561

            
562
impl PrintAsCssValue for StyleBackgroundPosition {
563
35
    fn print_as_css_value(&self) -> String {
564
35
        format!(
565
35
            "{} {}",
566
35
            self.horizontal.print_as_css_value(),
567
35
            self.vertical.print_as_css_value()
568
        )
569
35
    }
570
}
571
impl PrintAsCssValue for StyleBackgroundPositionVec {
572
1
    fn print_as_css_value(&self) -> String {
573
1
        self.iter()
574
1
            .map(PrintAsCssValue::print_as_css_value)
575
1
            .collect::<Vec<_>>()
576
1
            .join(", ")
577
1
    }
578
}
579

            
580
// Formatting to Rust code for StyleBackgroundPositionVec
581
impl crate::codegen::format::FormatAsRustCode for StyleBackgroundPositionVec {
582
    fn format_as_rust_code(&self, _tabs: usize) -> String {
583
        format!(
584
            "StyleBackgroundPositionVec::from_const_slice(STYLE_BACKGROUND_POSITION_{}_ITEMS)",
585
            self.get_hash()
586
        )
587
    }
588
}
589
#[allow(variant_size_differences)]
590
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
591
// disparity accepted
592
/// Horizontal component of `background-position`: a keyword or exact pixel value.
593
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
594
#[repr(C, u8)]
595
pub enum BackgroundPositionHorizontal {
596
    Left,
597
    Center,
598
    Right,
599
    Exact(PixelValue),
600
}
601

            
602
impl BackgroundPositionHorizontal {
603
37
    pub fn scale_for_dpi(&mut self, scale_factor: f32) {
604
37
        if let Self::Exact(s) = self {
605
10
            s.scale_for_dpi(scale_factor);
606
27
        }
607
37
    }
608
}
609

            
610
impl PrintAsCssValue for BackgroundPositionHorizontal {
611
53
    fn print_as_css_value(&self) -> String {
612
53
        match self {
613
17
            Self::Left => "left".to_string(),
614
11
            Self::Center => "center".to_string(),
615
9
            Self::Right => "right".to_string(),
616
16
            Self::Exact(px) => px.print_as_css_value(),
617
        }
618
53
    }
619
}
620
#[allow(variant_size_differences)]
621
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
622
// disparity accepted
623
/// Vertical component of `background-position`: a keyword or exact pixel value.
624
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
625
#[repr(C, u8)]
626
pub enum BackgroundPositionVertical {
627
    Top,
628
    Center,
629
    Bottom,
630
    Exact(PixelValue),
631
}
632

            
633
impl BackgroundPositionVertical {
634
33
    pub fn scale_for_dpi(&mut self, scale_factor: f32) {
635
33
        if let Self::Exact(s) = self {
636
6
            s.scale_for_dpi(scale_factor);
637
27
        }
638
33
    }
639
}
640

            
641
impl PrintAsCssValue for BackgroundPositionVertical {
642
53
    fn print_as_css_value(&self) -> String {
643
53
        match self {
644
17
            Self::Top => "top".to_string(),
645
11
            Self::Center => "center".to_string(),
646
9
            Self::Bottom => "bottom".to_string(),
647
16
            Self::Exact(px) => px.print_as_css_value(),
648
        }
649
53
    }
650
}
651
#[allow(variant_size_differences)]
652
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
653
// disparity accepted
654
/// The `background-size` property: `contain`, `cover`, or an exact size.
655
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
656
#[repr(C, u8)]
657
#[derive(Default)]
658
pub enum StyleBackgroundSize {
659
    ExactSize(PixelValueSize),
660
    #[default]
661
    Contain,
662
    Cover,
663
}
664

            
665
impl_option!(
666
    StyleBackgroundSize,
667
    OptionStyleBackgroundSize,
668
    copy = false,
669
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
670
);
671

            
672
/// Two-dimensional size in `PixelValue` units (width, height)
673
/// Used for background-size and similar properties
674
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
675
#[repr(C)]
676
pub struct PixelValueSize {
677
    pub width: PixelValue,
678
    pub height: PixelValue,
679
}
680

            
681
impl_vec!(
682
    StyleBackgroundSize,
683
    StyleBackgroundSizeVec,
684
    StyleBackgroundSizeVecDestructor,
685
    StyleBackgroundSizeVecDestructorType,
686
    StyleBackgroundSizeVecSlice,
687
    OptionStyleBackgroundSize
688
);
689
impl_vec_debug!(StyleBackgroundSize, StyleBackgroundSizeVec);
690
impl_vec_partialord!(StyleBackgroundSize, StyleBackgroundSizeVec);
691
impl_vec_ord!(StyleBackgroundSize, StyleBackgroundSizeVec);
692
impl_vec_clone!(
693
    StyleBackgroundSize,
694
    StyleBackgroundSizeVec,
695
    StyleBackgroundSizeVecDestructor
696
);
697
impl_vec_partialeq!(StyleBackgroundSize, StyleBackgroundSizeVec);
698
impl_vec_eq!(StyleBackgroundSize, StyleBackgroundSizeVec);
699
impl_vec_hash!(StyleBackgroundSize, StyleBackgroundSizeVec);
700

            
701
impl StyleBackgroundSize {
702
15
    pub fn scale_for_dpi(&mut self, scale_factor: f32) {
703
15
        if let Self::ExactSize(size) = self {
704
3
            size.width.scale_for_dpi(scale_factor);
705
3
            size.height.scale_for_dpi(scale_factor);
706
12
        }
707
15
    }
708
}
709

            
710
impl PrintAsCssValue for StyleBackgroundSize {
711
7
    fn print_as_css_value(&self) -> String {
712
7
        match self {
713
2
            Self::Contain => "contain".to_string(),
714
1
            Self::Cover => "cover".to_string(),
715
4
            Self::ExactSize(size) => {
716
4
                format!(
717
4
                    "{} {}",
718
4
                    size.width.print_as_css_value(),
719
4
                    size.height.print_as_css_value()
720
                )
721
            }
722
        }
723
7
    }
724
}
725
impl PrintAsCssValue for StyleBackgroundSizeVec {
726
1
    fn print_as_css_value(&self) -> String {
727
1
        self.iter()
728
1
            .map(PrintAsCssValue::print_as_css_value)
729
1
            .collect::<Vec<_>>()
730
1
            .join(", ")
731
1
    }
732
}
733

            
734
/// The `background-repeat` property.
735
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
736
#[repr(C)]
737
#[derive(Default)]
738
pub enum StyleBackgroundRepeat {
739
    NoRepeat,
740
    #[default]
741
    PatternRepeat,
742
    RepeatX,
743
    RepeatY,
744
}
745

            
746
impl_option!(
747
    StyleBackgroundRepeat,
748
    OptionStyleBackgroundRepeat,
749
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
750
);
751
impl_vec!(
752
    StyleBackgroundRepeat,
753
    StyleBackgroundRepeatVec,
754
    StyleBackgroundRepeatVecDestructor,
755
    StyleBackgroundRepeatVecDestructorType,
756
    StyleBackgroundRepeatVecSlice,
757
    OptionStyleBackgroundRepeat
758
);
759
impl_vec_debug!(StyleBackgroundRepeat, StyleBackgroundRepeatVec);
760
impl_vec_partialord!(StyleBackgroundRepeat, StyleBackgroundRepeatVec);
761
impl_vec_ord!(StyleBackgroundRepeat, StyleBackgroundRepeatVec);
762
impl_vec_clone!(
763
    StyleBackgroundRepeat,
764
    StyleBackgroundRepeatVec,
765
    StyleBackgroundRepeatVecDestructor
766
);
767
impl_vec_partialeq!(StyleBackgroundRepeat, StyleBackgroundRepeatVec);
768
impl_vec_eq!(StyleBackgroundRepeat, StyleBackgroundRepeatVec);
769
impl_vec_hash!(StyleBackgroundRepeat, StyleBackgroundRepeatVec);
770
impl PrintAsCssValue for StyleBackgroundRepeat {
771
6
    fn print_as_css_value(&self) -> String {
772
6
        match self {
773
2
            Self::NoRepeat => "no-repeat".to_string(),
774
2
            Self::PatternRepeat => "repeat".to_string(),
775
1
            Self::RepeatX => "repeat-x".to_string(),
776
1
            Self::RepeatY => "repeat-y".to_string(),
777
        }
778
6
    }
779
}
780
impl PrintAsCssValue for StyleBackgroundRepeatVec {
781
1
    fn print_as_css_value(&self) -> String {
782
1
        self.iter()
783
1
            .map(PrintAsCssValue::print_as_css_value)
784
1
            .collect::<Vec<_>>()
785
1
            .join(", ")
786
1
    }
787
}
788

            
789
// --- ERROR DEFINITIONS ---
790

            
791
#[derive(Clone, PartialEq)]
792
pub enum CssBackgroundParseError<'a> {
793
    Error(&'a str),
794
    InvalidBackground(ParenthesisParseError<'a>),
795
    UnclosedGradient(&'a str),
796
    NoDirection(&'a str),
797
    TooFewGradientStops(&'a str),
798
    DirectionParseError(CssDirectionParseError<'a>),
799
    GradientParseError(CssGradientStopParseError<'a>),
800
    ConicGradient(CssConicGradientParseError<'a>),
801
    ShapeParseError(CssShapeParseError<'a>),
802
    ImageParseError(CssImageParseError<'a>),
803
    ColorParseError(CssColorParseError<'a>),
804
}
805

            
806
impl_debug_as_display!(CssBackgroundParseError<'a>);
807
impl_display! { CssBackgroundParseError<'a>, {
808
    Error(e) => e,
809
    InvalidBackground(val) => format!("Invalid background value: \"{}\"", val),
810
    UnclosedGradient(val) => format!("Unclosed gradient: \"{}\"", val),
811
    NoDirection(val) => format!("Gradient has no direction: \"{}\"", val),
812
    TooFewGradientStops(val) => format!("Failed to parse gradient due to too few gradient steps: \"{}\"", val),
813
    DirectionParseError(e) => format!("Failed to parse gradient direction: \"{}\"", e),
814
    GradientParseError(e) => format!("Failed to parse gradient: {}", e),
815
    ConicGradient(e) => format!("Failed to parse conic gradient: {}", e),
816
    ShapeParseError(e) => format!("Failed to parse shape of radial gradient: {}", e),
817
    ImageParseError(e) => format!("Failed to parse image() value: {}", e),
818
    ColorParseError(e) => format!("Failed to parse color value: {}", e),
819
}}
820

            
821
#[cfg(feature = "parser")]
822
impl_from!(
823
    ParenthesisParseError<'a>,
824
    CssBackgroundParseError::InvalidBackground
825
);
826
#[cfg(feature = "parser")]
827
impl_from!(
828
    CssDirectionParseError<'a>,
829
    CssBackgroundParseError::DirectionParseError
830
);
831
#[cfg(feature = "parser")]
832
impl_from!(
833
    CssGradientStopParseError<'a>,
834
    CssBackgroundParseError::GradientParseError
835
);
836
#[cfg(feature = "parser")]
837
impl_from!(
838
    CssShapeParseError<'a>,
839
    CssBackgroundParseError::ShapeParseError
840
);
841
#[cfg(feature = "parser")]
842
impl_from!(
843
    CssImageParseError<'a>,
844
    CssBackgroundParseError::ImageParseError
845
);
846
#[cfg(feature = "parser")]
847
impl_from!(
848
    CssColorParseError<'a>,
849
    CssBackgroundParseError::ColorParseError
850
);
851
#[cfg(feature = "parser")]
852
impl_from!(
853
    CssConicGradientParseError<'a>,
854
    CssBackgroundParseError::ConicGradient
855
);
856

            
857
#[derive(Debug, Clone, PartialEq)]
858
#[repr(C, u8)]
859
pub enum CssBackgroundParseErrorOwned {
860
    Error(AzString),
861
    InvalidBackground(ParenthesisParseErrorOwned),
862
    UnclosedGradient(AzString),
863
    NoDirection(AzString),
864
    TooFewGradientStops(AzString),
865
    DirectionParseError(CssDirectionParseErrorOwned),
866
    GradientParseError(CssGradientStopParseErrorOwned),
867
    ConicGradient(CssConicGradientParseErrorOwned),
868
    ShapeParseError(CssShapeParseErrorOwned),
869
    ImageParseError(CssImageParseErrorOwned),
870
    ColorParseError(CssColorParseErrorOwned),
871
}
872

            
873
impl CssBackgroundParseError<'_> {
874
    #[must_use]
875
62
    pub fn to_contained(&self) -> CssBackgroundParseErrorOwned {
876
62
        match self {
877
2
            Self::Error(s) => CssBackgroundParseErrorOwned::Error((*s).to_string().into()),
878
2
            Self::InvalidBackground(e) => {
879
2
                CssBackgroundParseErrorOwned::InvalidBackground(e.to_contained())
880
            }
881
5
            Self::UnclosedGradient(s) => {
882
5
                CssBackgroundParseErrorOwned::UnclosedGradient((*s).to_string().into())
883
            }
884
2
            Self::NoDirection(s) => {
885
2
                CssBackgroundParseErrorOwned::NoDirection((*s).to_string().into())
886
            }
887
1
            Self::TooFewGradientStops(s) => {
888
1
                CssBackgroundParseErrorOwned::TooFewGradientStops((*s).to_string().into())
889
            }
890
2
            Self::DirectionParseError(e) => {
891
2
                CssBackgroundParseErrorOwned::DirectionParseError(e.to_contained())
892
            }
893
1
            Self::GradientParseError(e) => {
894
1
                CssBackgroundParseErrorOwned::GradientParseError(e.to_contained())
895
            }
896
1
            Self::ConicGradient(e) => CssBackgroundParseErrorOwned::ConicGradient(e.to_contained()),
897
1
            Self::ShapeParseError(e) => {
898
1
                CssBackgroundParseErrorOwned::ShapeParseError(e.to_contained())
899
            }
900
1
            Self::ImageParseError(e) => {
901
1
                CssBackgroundParseErrorOwned::ImageParseError(e.to_contained())
902
            }
903
44
            Self::ColorParseError(e) => {
904
44
                CssBackgroundParseErrorOwned::ColorParseError(e.to_contained())
905
            }
906
        }
907
62
    }
908
}
909

            
910
impl CssBackgroundParseErrorOwned {
911
    #[must_use]
912
77
    pub fn to_shared(&self) -> CssBackgroundParseError<'_> {
913
77
        match self {
914
4
            Self::Error(s) => CssBackgroundParseError::Error(s),
915
4
            Self::InvalidBackground(e) => CssBackgroundParseError::InvalidBackground(e.to_shared()),
916
6
            Self::UnclosedGradient(s) => CssBackgroundParseError::UnclosedGradient(s),
917
3
            Self::NoDirection(s) => CssBackgroundParseError::NoDirection(s),
918
2
            Self::TooFewGradientStops(s) => CssBackgroundParseError::TooFewGradientStops(s),
919
4
            Self::DirectionParseError(e) => {
920
4
                CssBackgroundParseError::DirectionParseError(e.to_shared())
921
            }
922
2
            Self::GradientParseError(e) => {
923
2
                CssBackgroundParseError::GradientParseError(e.to_shared())
924
            }
925
2
            Self::ConicGradient(e) => CssBackgroundParseError::ConicGradient(e.to_shared()),
926
2
            Self::ShapeParseError(e) => CssBackgroundParseError::ShapeParseError(e.to_shared()),
927
2
            Self::ImageParseError(e) => CssBackgroundParseError::ImageParseError(e.to_shared()),
928
46
            Self::ColorParseError(e) => CssBackgroundParseError::ColorParseError(e.to_shared()),
929
        }
930
77
    }
931
}
932

            
933
#[derive(Clone, PartialEq)]
934
pub enum CssGradientStopParseError<'a> {
935
    Error(&'a str),
936
    Percentage(PercentageParseError),
937
    Angle(CssAngleValueParseError<'a>),
938
    ColorParseError(CssColorParseError<'a>),
939
}
940

            
941
impl_debug_as_display!(CssGradientStopParseError<'a>);
942
impl_display! { CssGradientStopParseError<'a>, {
943
    Error(e) => e,
944
    Percentage(e) => format!("Failed to parse offset percentage: {}", e),
945
    Angle(e) => format!("Failed to parse angle: {}", e),
946
    ColorParseError(e) => format!("{}", e),
947
}}
948
#[cfg(feature = "parser")]
949
impl_from!(
950
    CssColorParseError<'a>,
951
    CssGradientStopParseError::ColorParseError
952
);
953

            
954
#[derive(Debug, Clone, PartialEq)]
955
#[repr(C, u8)]
956
pub enum CssGradientStopParseErrorOwned {
957
    Error(AzString),
958
    Percentage(PercentageParseErrorOwned),
959
    Angle(CssAngleValueParseErrorOwned),
960
    ColorParseError(CssColorParseErrorOwned),
961
}
962

            
963
impl CssGradientStopParseError<'_> {
964
    #[must_use]
965
11
    pub fn to_contained(&self) -> CssGradientStopParseErrorOwned {
966
11
        match self {
967
6
            Self::Error(s) => CssGradientStopParseErrorOwned::Error((*s).to_string().into()),
968
2
            Self::Percentage(e) => CssGradientStopParseErrorOwned::Percentage(e.to_contained()),
969
2
            Self::Angle(e) => CssGradientStopParseErrorOwned::Angle(e.to_contained()),
970
1
            Self::ColorParseError(e) => {
971
1
                CssGradientStopParseErrorOwned::ColorParseError(e.to_contained())
972
            }
973
        }
974
11
    }
975
}
976

            
977
impl CssGradientStopParseErrorOwned {
978
    #[must_use]
979
12
    pub fn to_shared(&self) -> CssGradientStopParseError<'_> {
980
12
        match self {
981
7
            Self::Error(s) => CssGradientStopParseError::Error(s),
982
2
            Self::Percentage(e) => CssGradientStopParseError::Percentage(e.to_shared()),
983
2
            Self::Angle(e) => CssGradientStopParseError::Angle(e.to_shared()),
984
1
            Self::ColorParseError(e) => CssGradientStopParseError::ColorParseError(e.to_shared()),
985
        }
986
12
    }
987
}
988

            
989
#[derive(Clone, PartialEq, Eq)]
990
pub enum CssConicGradientParseError<'a> {
991
    Position(CssBackgroundPositionParseError<'a>),
992
    Angle(CssAngleValueParseError<'a>),
993
    NoAngle(&'a str),
994
}
995
impl_debug_as_display!(CssConicGradientParseError<'a>);
996
impl_display! { CssConicGradientParseError<'a>, {
997
    Position(val) => format!("Invalid position attribute: \"{}\"", val),
998
    Angle(val) => format!("Invalid angle value: \"{}\"", val),
999
    NoAngle(val) => format!("Expected angle: \"{}\"", val),
}}
#[cfg(feature = "parser")]
impl_from!(
    CssAngleValueParseError<'a>,
    CssConicGradientParseError::Angle
);
#[cfg(feature = "parser")]
impl_from!(
    CssBackgroundPositionParseError<'a>,
    CssConicGradientParseError::Position
);
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C, u8)]
pub enum CssConicGradientParseErrorOwned {
    Position(CssBackgroundPositionParseErrorOwned),
    Angle(CssAngleValueParseErrorOwned),
    NoAngle(AzString),
}
impl CssConicGradientParseError<'_> {
    #[must_use]
8
    pub fn to_contained(&self) -> CssConicGradientParseErrorOwned {
8
        match self {
1
            Self::Position(e) => CssConicGradientParseErrorOwned::Position(e.to_contained()),
1
            Self::Angle(e) => CssConicGradientParseErrorOwned::Angle(e.to_contained()),
6
            Self::NoAngle(s) => CssConicGradientParseErrorOwned::NoAngle((*s).to_string().into()),
        }
8
    }
}
impl CssConicGradientParseErrorOwned {
    #[must_use]
9
    pub fn to_shared(&self) -> CssConicGradientParseError<'_> {
9
        match self {
1
            Self::Position(e) => CssConicGradientParseError::Position(e.to_shared()),
1
            Self::Angle(e) => CssConicGradientParseError::Angle(e.to_shared()),
7
            Self::NoAngle(s) => CssConicGradientParseError::NoAngle(s),
        }
9
    }
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum CssShapeParseError<'a> {
    ShapeErr(InvalidValueErr<'a>),
}
impl_display! {CssShapeParseError<'a>, {
    ShapeErr(e) => format!("\"{}\"", e.0),
}}
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C, u8)]
pub enum CssShapeParseErrorOwned {
    ShapeErr(InvalidValueErrOwned),
}
impl CssShapeParseError<'_> {
    #[must_use]
6
    pub fn to_contained(&self) -> CssShapeParseErrorOwned {
6
        match self {
6
            Self::ShapeErr(err) => CssShapeParseErrorOwned::ShapeErr(err.to_contained()),
        }
6
    }
}
impl CssShapeParseErrorOwned {
    #[must_use]
7
    pub fn to_shared(&self) -> CssShapeParseError<'_> {
7
        match self {
7
            Self::ShapeErr(err) => CssShapeParseError::ShapeErr(err.to_shared()),
        }
7
    }
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CssBackgroundPositionParseError<'a> {
    NoPosition(&'a str),
    TooManyComponents(&'a str),
    FirstComponentWrong(CssPixelValueParseError<'a>),
    SecondComponentWrong(CssPixelValueParseError<'a>),
}
impl_display! {CssBackgroundPositionParseError<'a>, {
    NoPosition(e) => format!("First background position missing: \"{}\"", e),
    TooManyComponents(e) => format!("background-position can only have one or two components, not more: \"{}\"", e),
    FirstComponentWrong(e) => format!("Failed to parse first component: \"{}\"", e),
    SecondComponentWrong(e) => format!("Failed to parse second component: \"{}\"", e),
}}
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C, u8)]
pub enum CssBackgroundPositionParseErrorOwned {
    NoPosition(AzString),
    TooManyComponents(AzString),
    FirstComponentWrong(CssPixelValueParseErrorOwned),
    SecondComponentWrong(CssPixelValueParseErrorOwned),
}
impl CssBackgroundPositionParseError<'_> {
    #[must_use]
40
    pub fn to_contained(&self) -> CssBackgroundPositionParseErrorOwned {
40
        match self {
11
            Self::NoPosition(s) => {
11
                CssBackgroundPositionParseErrorOwned::NoPosition((*s).to_string().into())
            }
1
            Self::TooManyComponents(s) => {
1
                CssBackgroundPositionParseErrorOwned::TooManyComponents((*s).to_string().into())
            }
27
            Self::FirstComponentWrong(e) => {
27
                CssBackgroundPositionParseErrorOwned::FirstComponentWrong(e.to_contained())
            }
1
            Self::SecondComponentWrong(e) => {
1
                CssBackgroundPositionParseErrorOwned::SecondComponentWrong(e.to_contained())
            }
        }
40
    }
}
impl CssBackgroundPositionParseErrorOwned {
    #[must_use]
40
    pub fn to_shared(&self) -> CssBackgroundPositionParseError<'_> {
40
        match self {
11
            Self::NoPosition(s) => CssBackgroundPositionParseError::NoPosition(s),
1
            Self::TooManyComponents(s) => CssBackgroundPositionParseError::TooManyComponents(s),
27
            Self::FirstComponentWrong(e) => {
27
                CssBackgroundPositionParseError::FirstComponentWrong(e.to_shared())
            }
1
            Self::SecondComponentWrong(e) => {
1
                CssBackgroundPositionParseError::SecondComponentWrong(e.to_shared())
            }
        }
40
    }
}
// --- PARSERS ---
#[cfg(feature = "parser")]
pub mod parser {
    #[allow(clippy::wildcard_imports)]
    // parser submodule reuses the parent module's value types
    use super::*;
    // the `*Gradient` suffix mirrors the CSS gradient function names this enum
    // parses (linear-gradient, radial-gradient, conic-gradient, …).
    #[allow(clippy::enum_variant_names)]
    #[derive(Debug, Copy, Clone, PartialEq, Eq)]
    enum GradientType {
        LinearGradient,
        RepeatingLinearGradient,
        RadialGradient,
        RepeatingRadialGradient,
        ConicGradient,
        RepeatingConicGradient,
    }
    impl GradientType {
6408
        pub(crate) const fn get_extend_mode(self) -> ExtendMode {
6408
            match self {
                Self::LinearGradient | Self::RadialGradient | Self::ConicGradient => {
6132
                    ExtendMode::Clamp
                }
                Self::RepeatingLinearGradient
                | Self::RepeatingRadialGradient
276
                | Self::RepeatingConicGradient => ExtendMode::Repeat,
            }
6408
        }
    }
    // -- Top-level Parsers for background-* properties --
    /// Parses multiple backgrounds, such as "linear-gradient(red, green), url(image.png)".
    /// # Errors
    ///
    /// Returns an error if `input` is not a valid CSS `background-content-multiple` value.
46580
    pub fn parse_style_background_content_multiple(
46580
        input: &str,
46580
    ) -> Result<StyleBackgroundContentVec, CssBackgroundParseError<'_>> {
46580
        Ok(split_string_respect_comma(input)
46580
            .iter()
48583
            .map(|i| parse_style_background_content(i))
46580
            .collect::<Result<Vec<_>, _>>()?
46482
            .into())
46580
    }
    /// Parses a single background value, which can be a color, image, or gradient.
    /// # Errors
    ///
    /// Returns an error if `input` is not a valid CSS `background-content` value.
48852
    pub fn parse_style_background_content(
48852
        input: &str,
48852
    ) -> Result<StyleBackgroundContent, CssBackgroundParseError<'_>> {
48852
        match parse_parentheses(
48852
            input,
48852
            &[
48852
                "linear-gradient",
48852
                "repeating-linear-gradient",
48852
                "radial-gradient",
48852
                "repeating-radial-gradient",
48852
                "conic-gradient",
48852
                "repeating-conic-gradient",
48852
                "image",
48852
                "url",
48852
            ],
48852
        ) {
5921
            Ok((background_type, brace_contents)) => {
5921
                let gradient_type = match background_type {
5921
                    "linear-gradient" => GradientType::LinearGradient,
92
                    "repeating-linear-gradient" => GradientType::RepeatingLinearGradient,
87
                    "radial-gradient" => GradientType::RadialGradient,
59
                    "repeating-radial-gradient" => GradientType::RepeatingRadialGradient,
58
                    "conic-gradient" => GradientType::ConicGradient,
44
                    "repeating-conic-gradient" => GradientType::RepeatingConicGradient,
40
                    "image" | "url" => {
40
                        return Ok(StyleBackgroundContent::Image(parse_image(brace_contents)?))
                    }
                    _ => unreachable!(),
                };
5881
                parse_gradient(brace_contents, gradient_type)
            }
            // A bare `background:` value is a color. Accept system colors here too
            // (`system:accent`, `system:text`, ...), matching the gradient color stops
            // (which use `parse_color_or_system`). System colors stay unresolved and are
            // theme-resolved at render time. `parse_color_or_system` is a superset of
            // `parse_css_color`, so ordinary colors keep parsing exactly as before.
42931
            Err(_) => Ok(match parse_color_or_system(input)? {
24417
                ColorOrSystem::Color(c) => StyleBackgroundContent::Color(c),
18281
                ColorOrSystem::System(s) => StyleBackgroundContent::SystemColor(s),
            }),
        }
48852
    }
    /// Parses multiple `background-position` values.
    /// # Errors
    ///
    /// Returns an error if `input` is not a valid CSS `background-position-multiple` value.
7
    pub fn parse_style_background_position_multiple(
7
        input: &str,
7
    ) -> Result<StyleBackgroundPositionVec, CssBackgroundPositionParseError<'_>> {
7
        Ok(split_string_respect_comma(input)
7
            .iter()
2010
            .map(|i| parse_style_background_position(i))
7
            .collect::<Result<Vec<_>, _>>()?
5
            .into())
7
    }
    /// Parses a single `background-position` value.
    /// # Errors
    ///
    /// Returns an error if `input` is not a valid CSS `background-position` value.
2398
    pub fn parse_style_background_position(
2398
        input: &str,
2398
    ) -> Result<StyleBackgroundPosition, CssBackgroundPositionParseError<'_>> {
2398
        let input = input.trim();
2398
        let mut whitespace_iter = input.split_whitespace();
2398
        let first = whitespace_iter
2398
            .next()
2398
            .ok_or(CssBackgroundPositionParseError::NoPosition(input))?;
2379
        let second = whitespace_iter.next();
2379
        if whitespace_iter.next().is_some() {
13
            return Err(CssBackgroundPositionParseError::TooManyComponents(input));
2366
        }
        // Try to parse as horizontal first, if that fails, maybe it's a vertical keyword
2366
        if let Ok(horizontal) = parse_background_position_horizontal(first) {
2144
            let vertical = match second {
2040
                Some(s) => parse_background_position_vertical(s)
2040
                    .map_err(CssBackgroundPositionParseError::SecondComponentWrong)?,
104
                None => BackgroundPositionVertical::Center,
            };
2143
            return Ok(StyleBackgroundPosition {
2143
                horizontal,
2143
                vertical,
2143
            });
222
        }
        // If the first part wasn't a horizontal keyword, maybe it's a vertical one
222
        if let Ok(vertical) = parse_background_position_vertical(first) {
2
            let horizontal = match second {
1
                Some(s) => parse_background_position_horizontal(s)
1
                    .map_err(CssBackgroundPositionParseError::FirstComponentWrong)?,
1
                None => BackgroundPositionHorizontal::Center,
            };
2
            return Ok(StyleBackgroundPosition {
2
                horizontal,
2
                vertical,
2
            });
220
        }
220
        Err(CssBackgroundPositionParseError::FirstComponentWrong(
220
            CssPixelValueParseError::InvalidPixelValue(first),
220
        ))
2398
    }
    /// Parses multiple `background-size` values.
    /// # Errors
    ///
    /// Returns an error if `input` is not a valid CSS `background-size-multiple` value.
7
    pub fn parse_style_background_size_multiple(
7
        input: &str,
7
    ) -> Result<StyleBackgroundSizeVec, InvalidValueErr<'_>> {
7
        Ok(split_string_respect_comma(input)
7
            .iter()
2011
            .map(|i| parse_style_background_size(i))
7
            .collect::<Result<Vec<_>, _>>()?
5
            .into())
7
    }
    /// Parses a single `background-size` value.
    /// # Errors
    ///
    /// Returns an error if `input` is not a valid CSS `background-size` value.
2127
    pub fn parse_style_background_size(
2127
        input: &str,
2127
    ) -> Result<StyleBackgroundSize, InvalidValueErr<'_>> {
2127
        let input = input.trim();
2127
        match input {
2127
            "contain" => Ok(StyleBackgroundSize::Contain),
2120
            "cover" => Ok(StyleBackgroundSize::Cover),
115
            other => {
115
                let mut iter = other.split_whitespace();
115
                let x_val = iter.next().ok_or(InvalidValueErr(input))?;
101
                let x_pos = parse_pixel_value(x_val).map_err(|_| InvalidValueErr(input))?;
43
                let y_pos = match iter.next() {
8
                    Some(y_val) => parse_pixel_value(y_val).map_err(|_| InvalidValueErr(input))?,
35
                    None => x_pos, // If only one value, it applies to both width and height
                };
43
                Ok(StyleBackgroundSize::ExactSize(PixelValueSize {
43
                    width: x_pos,
43
                    height: y_pos,
43
                }))
            }
        }
2127
    }
    /// Parses multiple `background-repeat` values.
    /// # Errors
    ///
    /// Returns an error if `input` is not a valid CSS `background-repeat-multiple` value.
7
    pub fn parse_style_background_repeat_multiple(
7
        input: &str,
7
    ) -> Result<StyleBackgroundRepeatVec, InvalidValueErr<'_>> {
7
        Ok(split_string_respect_comma(input)
7
            .iter()
2010
            .map(|i| parse_style_background_repeat(i))
7
            .collect::<Result<Vec<_>, _>>()?
5
            .into())
7
    }
    /// Parses a single `background-repeat` value.
    /// # Errors
    ///
    /// Returns an error if `input` is not a valid CSS `background-repeat` value.
2121
    pub fn parse_style_background_repeat(
2121
        input: &str,
2121
    ) -> Result<StyleBackgroundRepeat, InvalidValueErr<'_>> {
2121
        match input.trim() {
2121
            "no-repeat" => Ok(StyleBackgroundRepeat::NoRepeat),
2114
            "repeat" => Ok(StyleBackgroundRepeat::PatternRepeat),
107
            "repeat-x" => Ok(StyleBackgroundRepeat::RepeatX),
104
            "repeat-y" => Ok(StyleBackgroundRepeat::RepeatY),
101
            _ => Err(InvalidValueErr(input)),
        }
2121
    }
    // -- Gradient Parsing Logic --
    /// Parses the contents of a gradient function.
6471
    fn parse_gradient(
6471
        input: &str,
6471
        gradient_type: GradientType,
6471
    ) -> Result<StyleBackgroundContent, CssBackgroundParseError<'_>> {
6471
        let input = input.trim();
6471
        let comma_separated_items = split_string_respect_comma(input);
6471
        let mut brace_iterator = comma_separated_items.iter();
6471
        let first_brace_item = brace_iterator
6471
            .next()
6471
            .ok_or(CssBackgroundParseError::NoDirection(input))?;
6390
        match gradient_type {
            GradientType::LinearGradient | GradientType::RepeatingLinearGradient => {
6003
                let mut linear_gradient = LinearGradient {
6003
                    extend_mode: gradient_type.get_extend_mode(),
6003
                    ..Default::default()
6003
                };
6003
                let mut linear_stops = Vec::new();
6003
                if let Ok(dir) = parse_direction(first_brace_item) {
5854
                    linear_gradient.direction = dir;
5854
                } else {
149
                    linear_stops.push(parse_linear_color_stop(first_brace_item)?);
                }
26335
                for item in brace_iterator {
20450
                    linear_stops.push(parse_linear_color_stop(item)?);
                }
5885
                linear_gradient.stops = get_normalized_linear_stops(&linear_stops).into();
5885
                Ok(StyleBackgroundContent::LinearGradient(linear_gradient))
            }
            GradientType::RadialGradient | GradientType::RepeatingRadialGradient => {
                // Simplified parsing: assumes shape/size/position come first, then stops.
                // A more robust parser would handle them in any order.
197
                let mut radial_gradient = RadialGradient {
197
                    extend_mode: gradient_type.get_extend_mode(),
197
                    ..Default::default()
197
                };
197
                let mut radial_stops = Vec::new();
197
                let mut current_item = *first_brace_item;
197
                let mut items_consumed = false;
                // Greedily consume shape, size, position keywords
                loop {
222
                    let mut consumed_in_iteration = false;
222
                    let mut temp_iter = current_item.split_whitespace();
402
                    for word in temp_iter {
233
                        if let Ok(shape) = parse_shape(word) {
29
                            radial_gradient.shape = shape;
29
                            consumed_in_iteration = true;
204
                        } else if let Ok(size) = parse_radial_gradient_size(word) {
5
                            radial_gradient.size = size;
5
                            consumed_in_iteration = true;
199
                        } else if let Ok(pos) = parse_style_background_position(current_item) {
53
                            radial_gradient.position = pos;
53
                            consumed_in_iteration = true;
53
                            break; // position can have multiple words, so consume the rest of the
                                   // item
146
                        }
                    }
222
                    if consumed_in_iteration {
82
                        if let Some(next_item) = brace_iterator.next() {
25
                            current_item = next_item;
25
                            items_consumed = true;
25
                        } else {
57
                            break;
                        }
                    } else {
140
                        break;
                    }
                }
197
                if items_consumed || parse_linear_color_stop(current_item).is_ok() {
32
                    radial_stops.push(parse_linear_color_stop(current_item)?);
165
                }
226
                for item in brace_iterator {
39
                    radial_stops.push(parse_linear_color_stop(item)?);
                }
187
                radial_gradient.stops = get_normalized_linear_stops(&radial_stops).into();
187
                Ok(StyleBackgroundContent::RadialGradient(radial_gradient))
            }
            GradientType::ConicGradient | GradientType::RepeatingConicGradient => {
190
                let mut conic_gradient = ConicGradient {
190
                    extend_mode: gradient_type.get_extend_mode(),
190
                    ..Default::default()
190
                };
190
                let mut conic_stops = Vec::new();
190
                if let Some((angle, center)) = parse_conic_first_item(first_brace_item)? {
7
                    conic_gradient.angle = angle;
7
                    conic_gradient.center = center;
7
                } else {
178
                    conic_stops.push(parse_radial_color_stop(first_brace_item)?);
                }
47
                for item in brace_iterator {
26
                    conic_stops.push(parse_radial_color_stop(item)?);
                }
21
                conic_gradient.stops = get_normalized_radial_stops(&conic_stops).into();
21
                Ok(StyleBackgroundContent::ConicGradient(conic_gradient))
            }
        }
6471
    }
    // -- Gradient Parsing Helpers --
    /// Parses color stops per W3C CSS Images Level 3:
    /// - "red" (no position)
    /// - "red 5%" (one position)
    /// - "red 10% 30%" (two positions - creates a hard color band)
    ///
    /// Also supports system colors like `system:accent 50%` for theme-aware gradients.
20859
    fn parse_linear_color_stop(
20859
        input: &str,
20859
    ) -> Result<LinearColorStop, CssGradientStopParseError<'_>> {
20859
        let input = input.trim();
20859
        let (color_str, offset1_str, offset2_str) = split_color_and_offsets(input);
20859
        let color = parse_color_or_system(color_str)?;
20558
        let offset1 = match offset1_str {
10941
            None => OptionPercentageValue::None,
9617
            Some(s) => OptionPercentageValue::Some(
9617
                parse_percentage_value(s).map_err(CssGradientStopParseError::Percentage)?,
            ),
        };
20556
        let offset2 = match offset2_str {
20553
            None => OptionPercentageValue::None,
3
            Some(s) => OptionPercentageValue::Some(
3
                parse_percentage_value(s).map_err(CssGradientStopParseError::Percentage)?,
            ),
        };
20556
        Ok(LinearColorStop {
20556
            color,
20556
            offset1,
20556
            offset2,
20556
        })
20859
    }
    /// Parses color stops per W3C CSS Images Level 3:
    /// - "red" (no position)
    /// - "red 90deg" (one position)
    /// - "red 45deg 90deg" (two positions - creates a hard color band)
    ///
    /// Also supports system colors like `system:accent 90deg` for theme-aware gradients.
216
    fn parse_radial_color_stop(
216
        input: &str,
216
    ) -> Result<RadialColorStop, CssGradientStopParseError<'_>> {
216
        let input = input.trim();
216
        let (color_str, offset1_str, offset2_str) = split_color_and_offsets(input);
216
        let color = parse_color_or_system(color_str)?;
45
        let offset1 = match offset1_str {
17
            None => OptionAngleValue::None,
28
            Some(s) => OptionAngleValue::Some(
28
                parse_angle_value(s).map_err(CssGradientStopParseError::Angle)?,
            ),
        };
45
        let offset2 = match offset2_str {
44
            None => OptionAngleValue::None,
1
            Some(s) => OptionAngleValue::Some(
1
                parse_angle_value(s).map_err(CssGradientStopParseError::Angle)?,
            ),
        };
45
        Ok(RadialColorStop {
45
            color,
45
            offset1,
45
            offset2,
45
        })
216
    }
    /// Helper to robustly split a string like "rgba(0,0,0,0.5) 10% 30%" into color and offset
    /// parts. Returns (`color_str`, offset1, offset2) where offsets are optional.
    ///
    /// Per W3C CSS Images Level 3, a color stop can have 0, 1, or 2 positions:
    /// - "red" -> ("red", None, None)
    /// - "red 50%" -> ("red", Some("50%"), None)
    /// - "red 10% 30%" -> ("red", Some("10%"), Some("30%"))
21171
    fn split_color_and_offsets(input: &str) -> (&str, Option<&str>, Option<&str>) {
        // Strategy: scan from the end to find position values (contain digits + % or unit).
        // We need to handle complex colors like "rgba(0, 0, 0, 0.5)" that contain spaces and
        // digits.
21171
        let input = input.trim();
        // Try to find the last position value (might be second of two)
21171
        if let Some((remaining, last_offset)) = try_split_last_offset(input) {
            // Try to find another position value before it
9654
            if let Some((color_part, first_offset)) = try_split_last_offset(remaining) {
8
                return (color_part.trim(), Some(first_offset), Some(last_offset));
9646
            }
9646
            return (remaining.trim(), Some(last_offset), None);
11517
        }
11517
        (input, None, None)
21171
    }
    /// Try to split off the last whitespace-separated token if it looks like a position value.
    /// Returns (remaining, `offset_str`) if successful.
30920
    fn try_split_last_offset(input: &str) -> Option<(&str, &str)> {
30920
        let input = input.trim();
30920
        if let Some(last_ws_idx) = input.rfind(char::is_whitespace) {
15512
            let (potential_color, potential_offset) = input.split_at(last_ws_idx);
15512
            let potential_offset = potential_offset.trim();
            // A valid offset must contain a digit and typically ends with % or a unit
            // This avoids misinterpreting "to right bottom" as containing offsets
15512
            if is_likely_offset(potential_offset) {
9666
                return Some((potential_color, potential_offset));
5846
            }
15408
        }
21254
        None
30920
    }
    /// Check if a string looks like a position value (percentage or length).
    /// Must contain a digit and typically ends with %, px, em, etc.
15627
    fn is_likely_offset(s: &str) -> bool {
15984
        if !s.contains(|c: char| c.is_ascii_digit()) {
92
            return false;
15535
        }
        // Check if it ends with a known unit or %
15535
        let units = [
15535
            "%", "px", "em", "rem", "ex", "ch", "vw", "vh", "vmin", "vmax", "cm", "mm", "in", "pt",
15535
            "pc", "deg", "rad", "grad", "turn",
15535
        ];
121333
        units.iter().any(|u| s.ends_with(u))
15627
    }
    /// Parses the `from <angle> at <position>` part of a conic gradient.
286
    fn parse_conic_first_item(
286
        input: &str,
286
    ) -> Result<Option<(AngleValue, StyleBackgroundPosition)>, CssConicGradientParseError<'_>> {
286
        let input = input.trim();
286
        if !input.starts_with("from") {
265
            return Ok(None);
21
        }
21
        let mut parts = input["from".len()..].trim().split("at");
21
        let angle_part = parts
21
            .next()
21
            .ok_or(CssConicGradientParseError::NoAngle(input))?
21
            .trim();
21
        let angle = parse_angle_value(angle_part)?;
11
        let position = match parts.next() {
6
            Some(pos_part) => parse_style_background_position(pos_part.trim())?,
5
            None => StyleBackgroundPosition::default(),
        };
10
        Ok(Some((angle, position)))
286
    }
    // -- Normalization Functions --
    macro_rules! impl_get_normalized_stops {
        (
            fn
            $fn_name:ident($input_stop:ty) -> Vec <
            $output_stop:ident > ,pos_type =
            $pos_ty:ty,default_start =
            $default_start:expr,default_end =
            $default_end:expr,pos_ctor =
            $pos_ctor:expr,pos_to_f32 =
            $pos_to_f32:expr,output_field =
            $out_field:ident,
        ) => {
            #[allow(clippy::suboptimal_flops)] // explicit FP; mul_add slower without +fma
6093
            fn $fn_name(stops: &[$input_stop]) -> Vec<$output_stop> {
6093
                if stops.is_empty() {
211
                    return Vec::new();
5882
                }
5882
                let mut expanded: Vec<(ColorOrSystem, Option<$pos_ty>)> = Vec::new();
26464
                for stop in stops {
20582
                    match (stop.offset1.into_option(), stop.offset2.into_option()) {
10954
                        (None, _) => {
10954
                            expanded.push((stop.color, None));
10954
                        }
9626
                        (Some(pos1), None) => {
9626
                            expanded.push((stop.color, Some(pos1)));
9626
                        }
2
                        (Some(pos1), Some(pos2)) => {
2
                            expanded.push((stop.color, Some(pos1)));
2
                            expanded.push((stop.color, Some(pos2)));
2
                        }
                    }
                }
5882
                if expanded.is_empty() {
                    return Vec::new();
5882
                }
5882
                let pos_ctor: fn(f32) -> $pos_ty = $pos_ctor;
5882
                let pos_to_f32: fn(&$pos_ty) -> f32 = $pos_to_f32;
5882
                if expanded[0].1.is_none() {
4474
                    expanded[0].1 = Some(pos_ctor($default_start));
4474
                }
5882
                let last_idx = expanded.len() - 1;
5882
                if expanded[last_idx].1.is_none() {
4475
                    expanded[last_idx].1 = Some(pos_ctor($default_end));
4475
                }
5882
                let mut max_so_far: f32 = 0.0;
20584
                for (_, pos) in expanded.iter_mut() {
20584
                    if let Some(p) = pos {
18579
                        let val = pos_to_f32(p);
18579
                        if val < max_so_far {
10
                            *p = pos_ctor(max_so_far);
18569
                        } else {
18569
                            max_so_far = val;
18569
                        }
2005
                    }
                }
5882
                let mut i = 0;
24466
                while i < expanded.len() {
18584
                    if expanded[i].1.is_none() {
5
                        let run_start = i;
5
                        let mut run_end = i;
2010
                        while run_end < expanded.len() && expanded[run_end].1.is_none() {
2005
                            run_end += 1;
2005
                        }
5
                        let prev_pos = if run_start > 0 {
5
                            pos_to_f32(&expanded[run_start - 1].1.unwrap())
                        } else {
                            $default_start
                        };
5
                        let next_pos = if run_end < expanded.len() {
5
                            pos_to_f32(&expanded[run_end].1.unwrap())
                        } else {
                            $default_end
                        };
5
                        let run_len = run_end - run_start;
5
                        let step = (next_pos - prev_pos) / crate::cast::usize_to_f32(run_len + 1);
2005
                        for j in 0..run_len {
2005
                            expanded[run_start + j].1 =
2005
                                Some(pos_ctor(prev_pos + step * crate::cast::usize_to_f32(j + 1)));
2005
                        }
5
                        i = run_end;
18579
                    } else {
18579
                        i += 1;
18579
                    }
                }
5882
                expanded
5882
                    .into_iter()
5882
                    .map(|(color, pos)| $output_stop {
20584
                        $out_field: pos.unwrap_or(pos_ctor($default_start)),
20584
                        color,
20584
                    })
5882
                    .collect()
6093
            }
        };
    }
    impl_get_normalized_stops! {
        fn get_normalized_linear_stops(LinearColorStop) -> Vec<NormalizedLinearColorStop>,
        pos_type = PercentageValue,
        default_start = 0.0,
        default_end = 100.0,
31489
        pos_ctor = (|v| PercentageValue::new(v)),
18549
        pos_to_f32 = (|p: &PercentageValue| p.normalized() * 100.0),
        output_field = offset,
    }
    impl_get_normalized_stops! {
        fn get_normalized_radial_stops(RadialColorStop) -> Vec<NormalizedRadialColorStop>,
        pos_type = AngleValue,
        default_start = 0.0,
        default_end = 360.0,
59
        pos_ctor = (|v| AngleValue::deg(v)),
40
        pos_to_f32 = (|p: &AngleValue| p.to_degrees_raw()),
        output_field = angle,
    }
    // -- Other Background Helpers --
2376
    fn parse_background_position_horizontal(
2376
        input: &str,
2376
    ) -> Result<BackgroundPositionHorizontal, CssPixelValueParseError<'_>> {
2376
        Ok(match input {
2376
            "left" => BackgroundPositionHorizontal::Left,
358
            "center" => BackgroundPositionHorizontal::Center,
349
            "right" => BackgroundPositionHorizontal::Right,
342
            other => BackgroundPositionHorizontal::Exact(parse_pixel_value(other)?),
        })
2376
    }
2270
    fn parse_background_position_vertical(
2270
        input: &str,
2270
    ) -> Result<BackgroundPositionVertical, CssPixelValueParseError<'_>> {
2270
        Ok(match input {
2270
            "top" => BackgroundPositionVertical::Top,
253
            "center" => BackgroundPositionVertical::Center,
247
            "bottom" => BackgroundPositionVertical::Bottom,
241
            other => BackgroundPositionVertical::Exact(parse_pixel_value(other)?),
        })
2270
    }
332
    fn parse_shape(input: &str) -> Result<Shape, CssShapeParseError<'_>> {
332
        match input.trim() {
332
            "circle" => Ok(Shape::Circle),
301
            "ellipse" => Ok(Shape::Ellipse),
297
            _ => Err(CssShapeParseError::ShapeErr(InvalidValueErr(input))),
        }
332
    }
220
    fn parse_radial_gradient_size(input: &str) -> Result<RadialGradientSize, InvalidValueErr<'_>> {
220
        match input.trim() {
220
            "closest-side" => Ok(RadialGradientSize::ClosestSide),
216
            "closest-corner" => Ok(RadialGradientSize::ClosestCorner),
214
            "farthest-side" => Ok(RadialGradientSize::FarthestSide),
211
            "farthest-corner" => Ok(RadialGradientSize::FarthestCorner),
207
            _ => Err(InvalidValueErr(input)),
        }
220
    }
    /// Adversarial tests. Lives inside `mod parser` (not at file scope) because
    /// the interesting helpers -- `parse_gradient`, `split_color_and_offsets`,
    /// `try_split_last_offset`, `is_likely_offset`, `parse_conic_first_item`,
    /// `parse_shape`, ... -- are private to this module.
    #[cfg(test)]
    #[allow(
        clippy::float_cmp,
        clippy::too_many_lines,
        clippy::unreadable_literal,
        clippy::cognitive_complexity,
        clippy::wildcard_imports
    )]
    mod autotest_generated {
        // `super::*` = the private parser helpers under test; the second glob pulls in
        // the value/error types from the enclosing `background` module.
        use alloc::{string::ToString, vec::Vec};
        use super::*;
        use crate::{
            props::{
                basic::{
                    angle::CssAngleValueParseError,
                    color::{CssColorParseError, OptionColorU, SystemColorRef},
                    direction::CssDirectionParseError,
                    error::InvalidValueErr,
                    length::PercentageParseError,
                    parse::{CssImageParseError, ParenthesisParseError},
                    pixel::CssPixelValueParseError,
                },
                style::background::*,
            },
            system::SystemColors,
        };
        // ---------------------------------------------------------------
        // fixtures
        // ---------------------------------------------------------------
        /// Inputs that every `&str` parser in this file is swept over: empty,
        /// whitespace, garbage, boundary numbers, unbalanced braces, unicode.
        const ADVERSARIAL: &[&str] = &[
            "",
            " ",
            "   ",
            "\t\n\r",
            "\u{0}",
            "!!!",
            ";",
            ",",
            ",,",
            "(",
            ")",
            "()",
            "((((",
            "0",
            "-0",
            "+0",
            "NaN",
            "nan",
            "inf",
            "-inf",
            "1e40",
            "-1e40",
            "1e-45",
            "3.4028235e38",
            "9223372036854775807",
            "-9223372036854775808",
            "\u{1F600}",
            "e\u{0301}\u{0301}\u{0301}",
            "\u{00a0}",
            "red\u{00a0}50%",
            "  valid  ",
            "valid;garbage",
            "red;blue",
            "linear-gradient",
            "linear-gradient(",
            "linear-gradient()",
            "url(",
            "url()",
            "rgba(",
            "rgb(0,0,0",
            "to right",
            "circle",
            "from",
        ];
        const ALL_SYSTEM_REFS: [SystemColorRef; 9] = [
            SystemColorRef::Text,
            SystemColorRef::Background,
            SystemColorRef::Accent,
            SystemColorRef::AccentText,
            SystemColorRef::ButtonFace,
            SystemColorRef::ButtonText,
            SystemColorRef::WindowBackground,
            SystemColorRef::SelectionBackground,
            SystemColorRef::SelectionText,
        ];
        const ALL_GRADIENT_TYPES: [GradientType; 6] = [
            GradientType::LinearGradient,
            GradientType::RepeatingLinearGradient,
            GradientType::RadialGradient,
            GradientType::RepeatingRadialGradient,
            GradientType::ConicGradient,
            GradientType::RepeatingConicGradient,
        ];
        fn blue() -> ColorU {
            ColorU::new_rgb(0, 0, 255)
        }
        fn linear(input: &str) -> LinearGradient {
            match parse_style_background_content(input) {
                Ok(StyleBackgroundContent::LinearGradient(g)) => g,
                other => panic!("expected a linear gradient for {input:?}, got {other:?}"),
            }
        }
        fn radial(input: &str) -> RadialGradient {
            match parse_style_background_content(input) {
                Ok(StyleBackgroundContent::RadialGradient(g)) => g,
                other => panic!("expected a radial gradient for {input:?}, got {other:?}"),
            }
        }
        fn conic(input: &str) -> ConicGradient {
            match parse_style_background_content(input) {
                Ok(StyleBackgroundContent::ConicGradient(g)) => g,
                other => panic!("expected a conic gradient for {input:?}, got {other:?}"),
            }
        }
        /// Offsets of a linear/radial gradient, in percent.
        fn offsets(stops: &NormalizedLinearColorStopVec) -> Vec<f32> {
            stops
                .iter()
                .map(|s| s.offset.normalized() * 100.0)
                .collect()
        }
        // ---------------------------------------------------------------
        // serializers: Shape::fmt / RadialGradientSize::fmt
        // ---------------------------------------------------------------
        #[test]
        fn autotest_shape_display_is_exact_and_never_empty() {
            assert_eq!(Shape::Ellipse.to_string(), "ellipse");
            assert_eq!(Shape::Circle.to_string(), "circle");
            assert_eq!(Shape::default(), Shape::Ellipse);
            assert_eq!(Shape::default().to_string(), "ellipse");
            for s in [Shape::Ellipse, Shape::Circle] {
                assert!(!s.to_string().is_empty());
                // The serialized form is a valid input for the parser.
                assert_eq!(parse_shape(&s.to_string()).unwrap(), s);
            }
        }
        #[test]
        fn autotest_radial_gradient_size_display_is_exact_and_never_empty() {
            assert_eq!(RadialGradientSize::ClosestSide.to_string(), "closest-side");
            assert_eq!(
                RadialGradientSize::ClosestCorner.to_string(),
                "closest-corner"
            );
            assert_eq!(
                RadialGradientSize::FarthestSide.to_string(),
                "farthest-side"
            );
            assert_eq!(
                RadialGradientSize::FarthestCorner.to_string(),
                "farthest-corner"
            );
            assert_eq!(
                RadialGradientSize::default(),
                RadialGradientSize::FarthestCorner
            );
            for s in [
                RadialGradientSize::ClosestSide,
                RadialGradientSize::ClosestCorner,
                RadialGradientSize::FarthestSide,
                RadialGradientSize::FarthestCorner,
            ] {
                assert!(!s.to_string().is_empty());
                assert_eq!(parse_radial_gradient_size(&s.to_string()).unwrap(), s);
            }
        }
        // ---------------------------------------------------------------
        // constructors: Normalized{Linear,Radial}ColorStop::new
        // ---------------------------------------------------------------
        #[test]
        fn autotest_normalized_linear_stop_new_keeps_its_arguments() {
            let stop = NormalizedLinearColorStop::new(PercentageValue::new(42.5), ColorU::RED);
            assert_eq!(stop.offset.normalized() * 100.0, 42.5);
            assert_eq!(stop.color, ColorOrSystem::Color(ColorU::RED));
            // Extreme offsets must not panic, and must stay finite: FloatValue
            // encodes f32*1000 into an isize, and `as` saturates (NaN -> 0).
            for f in [
                0.0_f32,
                -0.0,
                f32::NAN,
                f32::INFINITY,
                f32::NEG_INFINITY,
                f32::MAX,
                f32::MIN,
                f32::MIN_POSITIVE,
                -100.0,
                1e30,
            ] {
                let stop =
                    NormalizedLinearColorStop::new(PercentageValue::new(f), ColorU::TRANSPARENT);
                assert!(
                    stop.offset.normalized().is_finite(),
                    "offset went non-finite for {f}"
                );
                assert_eq!(stop.color, ColorOrSystem::Color(ColorU::TRANSPARENT));
            }
            // NaN is flushed to 0, not propagated.
            assert_eq!(
                NormalizedLinearColorStop::new(PercentageValue::new(f32::NAN), ColorU::RED).offset,
                PercentageValue::new(0.0)
            );
        }
        #[test]
        fn autotest_normalized_radial_stop_new_keeps_its_arguments() {
            let stop = NormalizedRadialColorStop::new(AngleValue::deg(90.0), ColorU::RED);
            assert_eq!(stop.angle, AngleValue::deg(90.0));
            assert_eq!(stop.angle.to_degrees_raw(), 90.0);
            assert_eq!(stop.color, ColorOrSystem::Color(ColorU::RED));
            for f in [
                0.0_f32,
                -0.0,
                f32::NAN,
                f32::INFINITY,
                f32::NEG_INFINITY,
                f32::MAX,
                f32::MIN,
                720.0,
                -360.0,
            ] {
                let stop = NormalizedRadialColorStop::new(AngleValue::deg(f), ColorU::WHITE);
                assert!(
                    stop.angle.to_degrees_raw().is_finite(),
                    "angle went non-finite for {f}"
                );
                assert_eq!(stop.color, ColorOrSystem::Color(ColorU::WHITE));
            }
            assert_eq!(
                NormalizedRadialColorStop::new(AngleValue::deg(f32::NAN), ColorU::RED).angle,
                AngleValue::deg(0.0)
            );
        }
        // ---------------------------------------------------------------
        // Normalized{Linear,Radial}ColorStop::resolve
        // ---------------------------------------------------------------
        #[test]
        fn autotest_resolve_concrete_color_ignores_system_colors() {
            let stop = NormalizedLinearColorStop::new(PercentageValue::new(0.0), ColorU::RED);
            assert_eq!(
                stop.resolve(&SystemColors::default(), ColorU::WHITE),
                ColorU::RED
            );
            let populated = SystemColors {
                accent: OptionColorU::Some(ColorU::new_rgb(1, 2, 3)),
                ..SystemColors::default()
            };
            assert_eq!(stop.resolve(&populated, ColorU::WHITE), ColorU::RED);
            let rstop = NormalizedRadialColorStop::new(AngleValue::deg(0.0), ColorU::RED);
            assert_eq!(rstop.resolve(&populated, ColorU::WHITE), ColorU::RED);
        }
        #[test]
        fn autotest_resolve_system_stop_falls_back_for_every_variant() {
            let fallback = ColorU::rgba(9, 8, 7, 6);
            for r in ALL_SYSTEM_REFS {
                let lin = NormalizedLinearColorStop {
                    offset: PercentageValue::new(50.0),
                    color: ColorOrSystem::System(r),
                };
                let rad = NormalizedRadialColorStop {
                    angle: AngleValue::deg(180.0),
                    color: ColorOrSystem::System(r),
                };
                // Nothing is populated -> every variant resolves to the fallback.
                assert_eq!(lin.resolve(&SystemColors::default(), fallback), fallback);
                assert_eq!(rad.resolve(&SystemColors::default(), fallback), fallback);
            }
            // A populated key resolves; the others still fall back.
            let accent = ColorU::new_rgb(0, 122, 255);
            let populated = SystemColors {
                accent: OptionColorU::Some(accent),
                ..SystemColors::default()
            };
            let stop = NormalizedLinearColorStop {
                offset: PercentageValue::new(0.0),
                color: ColorOrSystem::System(SystemColorRef::Accent),
            };
            assert_eq!(stop.resolve(&populated, fallback), accent);
            let other = NormalizedLinearColorStop {
                offset: PercentageValue::new(0.0),
                color: ColorOrSystem::System(SystemColorRef::ButtonText),
            };
            assert_eq!(other.resolve(&populated, fallback), fallback);
        }
        // ---------------------------------------------------------------
        // numeric: scale_for_dpi
        // ---------------------------------------------------------------
        #[test]
        fn autotest_background_position_horizontal_scale_for_dpi() {
            // Keywords are immune to scaling, for *any* factor.
            for f in [
                0.0_f32,
                1.0,
                -1.0,
                f32::NAN,
                f32::INFINITY,
                f32::MIN,
                f32::MAX,
            ] {
                for keyword in [
                    BackgroundPositionHorizontal::Left,
                    BackgroundPositionHorizontal::Center,
                    BackgroundPositionHorizontal::Right,
                ] {
                    let mut k = keyword;
                    k.scale_for_dpi(f);
                    assert_eq!(k, keyword, "keyword mutated by scale factor {f}");
                }
            }
            let mut exact = BackgroundPositionHorizontal::Exact(PixelValue::px(10.0));
            exact.scale_for_dpi(2.0);
            assert_eq!(
                exact,
                BackgroundPositionHorizontal::Exact(PixelValue::px(20.0))
            );
            // zero, negative
            let mut zeroed = BackgroundPositionHorizontal::Exact(PixelValue::px(10.0));
            zeroed.scale_for_dpi(0.0);
            assert_eq!(
                zeroed,
                BackgroundPositionHorizontal::Exact(PixelValue::px(0.0))
            );
            let mut negated = BackgroundPositionHorizontal::Exact(PixelValue::px(10.0));
            negated.scale_for_dpi(-1.0);
            assert_eq!(
                negated,
                BackgroundPositionHorizontal::Exact(PixelValue::px(-10.0))
            );
            // NaN is flushed to 0 by the isize cast, never propagated.
            let mut nan = BackgroundPositionHorizontal::Exact(PixelValue::px(10.0));
            nan.scale_for_dpi(f32::NAN);
            assert_eq!(
                nan,
                BackgroundPositionHorizontal::Exact(PixelValue::px(0.0))
            );
            // +-inf and MIN/MAX saturate to the isize bounds -- finite, no panic.
            for f in [f32::INFINITY, f32::NEG_INFINITY, f32::MAX, f32::MIN] {
                let mut v = BackgroundPositionHorizontal::Exact(PixelValue::px(10.0));
                v.scale_for_dpi(f);
                let BackgroundPositionHorizontal::Exact(px) = v else {
                    panic!("variant changed under scaling");
                };
                assert!(px.number.get().is_finite(), "non-finite result for {f}");
                assert_eq!(px.number.get().is_sign_negative(), f.is_sign_negative());
            }
        }
        #[test]
        fn autotest_background_position_vertical_scale_for_dpi() {
            for f in [
                0.0_f32,
                1.0,
                -1.0,
                f32::NAN,
                f32::INFINITY,
                f32::MIN,
                f32::MAX,
            ] {
                for keyword in [
                    BackgroundPositionVertical::Top,
                    BackgroundPositionVertical::Center,
                    BackgroundPositionVertical::Bottom,
                ] {
                    let mut k = keyword;
                    k.scale_for_dpi(f);
                    assert_eq!(k, keyword, "keyword mutated by scale factor {f}");
                }
            }
            let mut exact = BackgroundPositionVertical::Exact(PixelValue::em(4.0));
            exact.scale_for_dpi(0.5);
            assert_eq!(
                exact,
                BackgroundPositionVertical::Exact(PixelValue::em(2.0))
            );
            let mut nan = BackgroundPositionVertical::Exact(PixelValue::px(10.0));
            nan.scale_for_dpi(f32::NAN);
            assert_eq!(nan, BackgroundPositionVertical::Exact(PixelValue::px(0.0)));
            // Saturation is a fixed point: scaling an already-saturated value again
            // must not wrap around into a negative number.
            let mut saturated = BackgroundPositionVertical::Exact(PixelValue::px(f32::MAX));
            saturated.scale_for_dpi(f32::MAX);
            let once = saturated;
            saturated.scale_for_dpi(f32::MAX);
            assert_eq!(saturated, once);
            let BackgroundPositionVertical::Exact(px) = saturated else {
                panic!("variant changed under scaling");
            };
            assert!(px.number.get() > 0.0);
            assert!(px.number.get().is_finite());
        }
        #[test]
        fn autotest_style_background_position_scale_for_dpi_scales_both_axes() {
            let mut pos = StyleBackgroundPosition {
                horizontal: BackgroundPositionHorizontal::Exact(PixelValue::px(10.0)),
                vertical: BackgroundPositionVertical::Exact(PixelValue::px(20.0)),
            };
            pos.scale_for_dpi(3.0);
            assert_eq!(
                pos.horizontal,
                BackgroundPositionHorizontal::Exact(PixelValue::px(30.0))
            );
            assert_eq!(
                pos.vertical,
                BackgroundPositionVertical::Exact(PixelValue::px(60.0))
            );
            // Scaling compounds -- pinned, because a double-applied DPI scale is a
            // classic layout bug.
            pos.scale_for_dpi(2.0);
            assert_eq!(
                pos.horizontal,
                BackgroundPositionHorizontal::Exact(PixelValue::px(60.0))
            );
            // The all-keyword default is a fixed point for every factor.
            for f in [
                0.0_f32,
                1.0,
                -2.5,
                f32::NAN,
                f32::INFINITY,
                f32::NEG_INFINITY,
            ] {
                let mut default = StyleBackgroundPosition::default();
                default.scale_for_dpi(f);
                assert_eq!(default, StyleBackgroundPosition::default());
            }
        }
        #[test]
        fn autotest_style_background_size_scale_for_dpi() {
            // Contain / Cover carry no number and must survive any factor.
            for f in [
                0.0_f32,
                2.0,
                -1.0,
                f32::NAN,
                f32::INFINITY,
                f32::NEG_INFINITY,
            ] {
                for keyword in [StyleBackgroundSize::Contain, StyleBackgroundSize::Cover] {
                    let mut k = keyword;
                    k.scale_for_dpi(f);
                    assert_eq!(k, keyword, "keyword mutated by scale factor {f}");
                }
            }
            let mut size = StyleBackgroundSize::ExactSize(PixelValueSize {
                width: PixelValue::px(10.0),
                height: PixelValue::percent(50.0),
            });
            size.scale_for_dpi(2.0);
            assert_eq!(
                size,
                StyleBackgroundSize::ExactSize(PixelValueSize {
                    width: PixelValue::px(20.0),
                    // NOTE: percentages are scaled too, which is arguably wrong for a
                    // DPI change -- pinned as current behaviour.
                    height: PixelValue::percent(100.0),
                })
            );
            let mut nan = StyleBackgroundSize::ExactSize(PixelValueSize {
                width: PixelValue::px(10.0),
                height: PixelValue::px(20.0),
            });
            nan.scale_for_dpi(f32::NAN);
            assert_eq!(
                nan,
                StyleBackgroundSize::ExactSize(PixelValueSize {
                    width: PixelValue::px(0.0),
                    height: PixelValue::px(0.0),
                })
            );
            let mut inf = StyleBackgroundSize::ExactSize(PixelValueSize {
                width: PixelValue::px(1.0),
                height: PixelValue::px(-1.0),
            });
            inf.scale_for_dpi(f32::INFINITY);
            let StyleBackgroundSize::ExactSize(s) = inf else {
                panic!("variant changed under scaling");
            };
            assert!(s.width.number.get().is_finite() && s.width.number.get() > 0.0);
            assert!(s.height.number.get().is_finite() && s.height.number.get() < 0.0);
        }
        // ---------------------------------------------------------------
        // getters: to_contained / to_shared round-trips
        // ---------------------------------------------------------------
        #[test]
        fn autotest_css_background_parse_error_round_trips() {
            let errors = [
                CssBackgroundParseError::Error(""),
                CssBackgroundParseError::Error("boom \u{1F600}"),
                CssBackgroundParseError::InvalidBackground(ParenthesisParseError::EmptyInput),
                CssBackgroundParseError::InvalidBackground(
                    ParenthesisParseError::StopWordNotFound("nope"),
                ),
                CssBackgroundParseError::UnclosedGradient(""),
                CssBackgroundParseError::NoDirection("nodir"),
                CssBackgroundParseError::TooFewGradientStops("few"),
                CssBackgroundParseError::DirectionParseError(CssDirectionParseError::Error("d")),
                CssBackgroundParseError::DirectionParseError(
                    CssDirectionParseError::InvalidArguments("args"),
                ),
                CssBackgroundParseError::GradientParseError(CssGradientStopParseError::Error("g")),
                CssBackgroundParseError::ConicGradient(CssConicGradientParseError::NoAngle("a")),
                CssBackgroundParseError::ShapeParseError(CssShapeParseError::ShapeErr(
                    InvalidValueErr("s"),
                )),
                CssBackgroundParseError::ImageParseError(CssImageParseError::UnclosedQuotes("q")),
                CssBackgroundParseError::ColorParseError(CssColorParseError::InvalidColor("c")),
                CssBackgroundParseError::ColorParseError(CssColorParseError::EmptyInput),
            ];
            for e in &errors {
                let owned = e.to_contained();
                assert_eq!(&owned.to_shared(), e, "round-trip changed {e:?}");
                // Display must survive the round-trip as well.
                assert_eq!(
                    alloc::format!("{}", owned.to_shared()),
                    alloc::format!("{e}")
                );
            }
        }
        #[test]
        fn autotest_error_round_trip_survives_huge_and_unicode_payloads() {
            let huge = "x".repeat(100_000);
            let weird = "\u{1F600}\u{0}\u{00a0}e\u{0301}";
            for s in [huge.as_str(), weird, "", " "] {
                let e = CssBackgroundParseError::UnclosedGradient(s);
                assert_eq!(e.to_contained().to_shared(), e);
                let e = CssGradientStopParseError::Error(s);
                assert_eq!(e.to_contained().to_shared(), e);
                let e = CssConicGradientParseError::NoAngle(s);
                assert_eq!(e.to_contained().to_shared(), e);
                let e = CssShapeParseError::ShapeErr(InvalidValueErr(s));
                assert_eq!(e.to_contained().to_shared(), e);
                let e = CssBackgroundPositionParseError::NoPosition(s);
                assert_eq!(e.to_contained().to_shared(), e);
            }
        }
        #[test]
        fn autotest_css_gradient_stop_parse_error_round_trips() {
            let errors = [
                CssGradientStopParseError::Error("boom"),
                CssGradientStopParseError::Percentage(PercentageParseError::NoPercentSign),
                CssGradientStopParseError::Percentage(PercentageParseError::InvalidUnit(
                    "px".to_string().into(),
                )),
                CssGradientStopParseError::Angle(CssAngleValueParseError::EmptyString),
                CssGradientStopParseError::Angle(CssAngleValueParseError::InvalidAngle("q")),
                CssGradientStopParseError::ColorParseError(CssColorParseError::InvalidColor("c")),
            ];
            for e in &errors {
                assert_eq!(&e.to_contained().to_shared(), e, "round-trip changed {e:?}");
            }
        }
        #[test]
        fn autotest_css_conic_and_shape_parse_error_round_trip() {
            let errors = [
                CssConicGradientParseError::NoAngle("n"),
                CssConicGradientParseError::Angle(CssAngleValueParseError::EmptyString),
                CssConicGradientParseError::Position(CssBackgroundPositionParseError::NoPosition(
                    "p",
                )),
            ];
            for e in &errors {
                assert_eq!(&e.to_contained().to_shared(), e);
            }
            let shape = CssShapeParseError::ShapeErr(InvalidValueErr("blob"));
            assert_eq!(shape.to_contained().to_shared(), shape);
        }
        #[test]
        fn autotest_css_background_position_parse_error_round_trips() {
            let errors = [
                CssBackgroundPositionParseError::NoPosition(""),
                CssBackgroundPositionParseError::TooManyComponents("a b c"),
                CssBackgroundPositionParseError::FirstComponentWrong(
                    CssPixelValueParseError::EmptyString,
                ),
                CssBackgroundPositionParseError::FirstComponentWrong(
                    CssPixelValueParseError::InvalidPixelValue("q"),
                ),
                CssBackgroundPositionParseError::SecondComponentWrong(
                    CssPixelValueParseError::InvalidPixelValue("\u{1F600}"),
                ),
            ];
            for e in &errors {
                assert_eq!(&e.to_contained().to_shared(), e, "round-trip changed {e:?}");
            }
        }
        #[test]
        fn autotest_real_parse_errors_round_trip_through_the_owned_form() {
            // Errors as actually produced by the parsers, not hand-built ones.
            for input in ADVERSARIAL {
                if let Err(e) = parse_style_background_content(input) {
                    assert_eq!(e.to_contained().to_shared(), e, "for input {input:?}");
                }
                if let Err(e) = parse_style_background_position(input) {
                    assert_eq!(e.to_contained().to_shared(), e, "for input {input:?}");
                }
            }
        }
        // ---------------------------------------------------------------
        // GradientType::get_extend_mode (private)
        // ---------------------------------------------------------------
        #[test]
        fn autotest_get_extend_mode_is_repeat_exactly_for_the_repeating_variants() {
            assert_eq!(
                GradientType::LinearGradient.get_extend_mode(),
                ExtendMode::Clamp
            );
            assert_eq!(
                GradientType::RadialGradient.get_extend_mode(),
                ExtendMode::Clamp
            );
            assert_eq!(
                GradientType::ConicGradient.get_extend_mode(),
                ExtendMode::Clamp
            );
            assert_eq!(
                GradientType::RepeatingLinearGradient.get_extend_mode(),
                ExtendMode::Repeat
            );
            assert_eq!(
                GradientType::RepeatingRadialGradient.get_extend_mode(),
                ExtendMode::Repeat
            );
            assert_eq!(
                GradientType::RepeatingConicGradient.get_extend_mode(),
                ExtendMode::Repeat
            );
            // Total + pure: same input, same answer.
            for t in ALL_GRADIENT_TYPES {
                assert_eq!(t.get_extend_mode(), t.get_extend_mode());
            }
            assert_eq!(ExtendMode::default(), ExtendMode::Clamp);
        }
        // ---------------------------------------------------------------
        // parser: parse_style_background_content
        // ---------------------------------------------------------------
        #[test]
        fn autotest_background_content_never_panics_and_is_deterministic() {
            for input in ADVERSARIAL {
                let a = parse_style_background_content(input);
                let b = parse_style_background_content(input);
                assert_eq!(a, b, "non-deterministic for {input:?}");
            }
        }
        #[test]
        fn autotest_background_content_rejects_empty_whitespace_and_garbage() {
            for input in [
                "",
                " ",
                "   ",
                "\t\n\r",
                "\u{0}",
                "!!!",
                ";",
                "valid;garbage",
            ] {
                assert!(
                    parse_style_background_content(input).is_err(),
                    "{input:?} should not parse as a background"
                );
            }
        }
        #[test]
        fn autotest_background_content_valid_minimal_positive_controls() {
            assert_eq!(
                parse_style_background_content("red").unwrap(),
                StyleBackgroundContent::Color(ColorU::RED)
            );
            // Leading/trailing whitespace is trimmed, not rejected.
            assert_eq!(
                parse_style_background_content("  red  ").unwrap(),
                StyleBackgroundContent::Color(ColorU::RED)
            );
            assert_eq!(
                parse_style_background_content("system:accent").unwrap(),
                StyleBackgroundContent::SystemColor(SystemColorRef::Accent)
            );
            assert_eq!(
                parse_style_background_content("url(a.png)").unwrap(),
                StyleBackgroundContent::Image("a.png".into())
            );
        }
        #[test]
        fn autotest_background_content_unicode_is_rejected_without_panicking() {
            for input in [
                "\u{1F600}",
                "url(\u{1F600}.png)",
                "linear-gradient(\u{1F600}, red)",
                "e\u{0301}\u{0301}\u{0301}",
                "\u{00a0}",
            ] {
                let parsed = parse_style_background_content(input);
                // url() accepts any payload; everything else must be an error.
                if input.starts_with("url(") {
                    assert!(parsed.is_ok());
                } else {
                    assert!(parsed.is_err(), "{input:?} unexpectedly parsed");
                }
            }
        }
        #[test]
        fn autotest_background_content_extremely_long_input_terminates() {
            let huge = "a".repeat(100_000);
            assert!(parse_style_background_content(&huge).is_err());
            let huge_gradient =
                alloc::format!("linear-gradient({})", "red, ".repeat(2_000) + "blue");
            let g = linear(&huge_gradient);
            assert_eq!(g.stops.len(), 2_001);
            let huge_url = alloc::format!("url({})", "a".repeat(100_000));
            assert!(matches!(
                parse_style_background_content(&huge_url),
                Ok(StyleBackgroundContent::Image(_))
            ));
        }
        #[test]
        fn autotest_background_content_deep_nesting_does_not_stack_overflow() {
            let nested = alloc::format!(
                "linear-gradient({}red{})",
                "(".repeat(10_000),
                ")".repeat(10_000)
            );
            assert!(parse_style_background_content(&nested).is_err());
            let unbalanced = alloc::format!("linear-gradient({}", "(".repeat(10_000));
            assert!(parse_style_background_content(&unbalanced).is_err());
        }
        #[test]
        fn autotest_unclosed_gradient_reports_a_color_error_not_unclosed_gradient() {
            // parse_parentheses fails (no ')'), so the input falls through to the
            // color branch -- the `UnclosedGradient` variant is never produced here.
            let err = parse_style_background_content("linear-gradient(red, blue").unwrap_err();
            assert!(
                matches!(err, CssBackgroundParseError::ColorParseError(_)),
                "got {err:?}"
            );
        }
        #[test]
        fn autotest_empty_gradient_body_is_a_no_direction_error() {
            let err = parse_style_background_content("linear-gradient()").unwrap_err();
            assert!(
                matches!(err, CssBackgroundParseError::NoDirection(_)),
                "got {err:?}"
            );
            for f in [
                "radial-gradient()",
                "conic-gradient()",
                "repeating-linear-gradient()",
            ] {
                assert!(parse_style_background_content(f).is_err(), "{f:?}");
            }
        }
        #[test]
        fn autotest_url_with_empty_payload_is_accepted_as_an_empty_image() {
            // Pinned: `url()` yields an empty image id rather than an error.
            assert_eq!(
                parse_style_background_content("url()").unwrap(),
                StyleBackgroundContent::Image("".into())
            );
        }
        #[test]
        fn autotest_gradient_boundary_number_directions_stay_finite() {
            // "NaN" parses as a bare number -> a NaN angle, which the isize cast
            // flushes to 0deg. Pinned: it is silently accepted, not rejected.
            let g = linear("linear-gradient(NaN, red, blue)");
            assert_eq!(g.direction, Direction::Angle(AngleValue::deg(0.0)));
            // Overflowing / tiny literals must not panic and must stay finite.
            for input in [
                "linear-gradient(0deg, red, blue)",
                "linear-gradient(-0deg, red, blue)",
                "linear-gradient(1e40deg, red, blue)",
                "linear-gradient(-1e40deg, red, blue)",
                "linear-gradient(1e-45deg, red, blue)",
                "linear-gradient(inf, red, blue)",
                "linear-gradient(-inf, red, blue)",
                "linear-gradient(9223372036854775807deg, red, blue)",
            ] {
                let g = linear(input);
                let Direction::Angle(a) = g.direction else {
                    panic!("expected an angle direction for {input:?}");
                };
                assert!(
                    a.to_degrees_raw().is_finite(),
                    "non-finite angle for {input:?}"
                );
                assert_eq!(g.stops.len(), 2, "{input:?}");
            }
        }
        #[test]
        fn autotest_gradient_stop_offsets_are_monotonic_and_finite() {
            for input in [
                "linear-gradient(red, blue)",
                "linear-gradient(red, green, blue)",
                "linear-gradient(red 50%, blue 20%)",
                "linear-gradient(red -50%, blue)",
                "linear-gradient(red 0%, yellow, green, blue 100%)",
                "linear-gradient(red 10% 30%, blue)",
                "linear-gradient(red 200%, blue 10%)",
                "repeating-linear-gradient(red, blue 20%)",
                "radial-gradient(circle, red, blue)",
            ] {
                let content = parse_style_background_content(input).unwrap();
                let stops = match &content {
                    StyleBackgroundContent::LinearGradient(g) => &g.stops,
                    StyleBackgroundContent::RadialGradient(g) => &g.stops,
                    other => panic!("unexpected content {other:?}"),
                };
                let mut prev = f32::NEG_INFINITY;
                for o in offsets(stops) {
                    assert!(o.is_finite(), "non-finite offset in {input:?}");
                    assert!(
                        o >= prev,
                        "offsets not monotonic in {input:?}: {o} < {prev}"
                    );
                    prev = o;
                }
            }
        }
        #[test]
        fn autotest_negative_and_overflowing_stop_offsets_are_clamped() {
            // A negative first offset is clamped to the running maximum (0%).
            let g = linear("linear-gradient(red -50%, blue)");
            assert_eq!(offsets(&g.stops), alloc::vec![0.0, 100.0]);
            // An out-of-range offset is *not* clamped down to 100% -- the later
            // stop is dragged up to it instead.
            let g = linear("linear-gradient(red 200%, blue 10%)");
            assert_eq!(offsets(&g.stops), alloc::vec![200.0, 200.0]);
        }
        #[test]
        fn autotest_offsets_that_are_not_percentages_are_rejected() {
            // "50px" looks like an offset (is_likely_offset), but a linear stop
            // offset must be a percentage -> hard error, no silent fallback.
            let err =
                parse_style_background_content("linear-gradient(red 50px, blue)").unwrap_err();
            assert!(
                matches!(
                    err,
                    CssBackgroundParseError::GradientParseError(
                        CssGradientStopParseError::Percentage(_)
                    )
                ),
                "got {err:?}"
            );
            // A bare number is *not* recognised as an offset at all, so the whole
            // token is treated as part of the color and fails to parse.
            assert!(parse_style_background_content("linear-gradient(red 0.5, blue)").is_err());
            // Neither is "NaN%" (no ASCII digit).
            assert!(parse_style_background_content("linear-gradient(red NaN%, blue)").is_err());
        }
        #[test]
        fn autotest_huge_stop_offsets_do_not_produce_nan_or_inf() {
            let g = linear("linear-gradient(red 1e40%, blue)");
            assert_eq!(g.stops.len(), 2);
            for o in offsets(&g.stops) {
                assert!(o.is_finite(), "offset leaked a non-finite value: {o}");
            }
        }
        // ---------------------------------------------------------------
        // parser: parse_style_background_content_multiple
        // ---------------------------------------------------------------
        #[test]
        fn autotest_background_content_multiple_empty_input_yields_an_empty_vec() {
            // Pinned: empty input is *not* an error -- split_string_respect_comma
            // returns no items, so the result is an empty layer list.
            let parsed = parse_style_background_content_multiple("").unwrap();
            assert_eq!(parsed.len(), 0);
            // Whitespace-only *is* an error (one empty item that fails to parse).
            assert!(parse_style_background_content_multiple("   ").is_err());
            assert!(parse_style_background_content_multiple(",").is_err());
            assert!(parse_style_background_content_multiple("red,,blue").is_err());
        }
        #[test]
        fn autotest_background_content_multiple_valid_and_adversarial() {
            let parsed =
                parse_style_background_content_multiple("linear-gradient(red, blue), url(a.png)")
                    .unwrap();
            assert_eq!(parsed.len(), 2);
            assert!(matches!(
                parsed.as_slice()[0],
                StyleBackgroundContent::LinearGradient(_)
            ));
            assert!(matches!(
                parsed.as_slice()[1],
                StyleBackgroundContent::Image(_)
            ));
            // One bad layer poisons the whole list.
            assert!(parse_style_background_content_multiple("red, !!!").is_err());
            // Long repeated input terminates.
            let many = "red,".repeat(2_000) + "blue";
            assert_eq!(
                parse_style_background_content_multiple(&many)
                    .unwrap()
                    .len(),
                2_001
            );
            for input in ADVERSARIAL {
                let a = parse_style_background_content_multiple(input);
                let b = parse_style_background_content_multiple(input);
                assert_eq!(a, b, "non-deterministic for {input:?}");
            }
        }
        // ---------------------------------------------------------------
        // parser: parse_style_background_position(_multiple)
        // ---------------------------------------------------------------
        #[test]
        fn autotest_background_position_empty_and_whitespace() {
            assert_eq!(
                parse_style_background_position(""),
                Err(CssBackgroundPositionParseError::NoPosition(""))
            );
            assert_eq!(
                parse_style_background_position("   "),
                Err(CssBackgroundPositionParseError::NoPosition(""))
            );
            assert_eq!(
                parse_style_background_position("\t\n\r"),
                Err(CssBackgroundPositionParseError::NoPosition(""))
            );
        }
        #[test]
        fn autotest_background_position_valid_minimal_and_keyword_order() {
            let p = parse_style_background_position("left").unwrap();
            assert_eq!(p.horizontal, BackgroundPositionHorizontal::Left);
            assert_eq!(p.vertical, BackgroundPositionVertical::Center);
            // A lone vertical keyword also works: the horizontal falls back to center.
            let p = parse_style_background_position("top").unwrap();
            assert_eq!(p.horizontal, BackgroundPositionHorizontal::Center);
            assert_eq!(p.vertical, BackgroundPositionVertical::Top);
            // Either order is accepted for keyword pairs.
            assert_eq!(
                parse_style_background_position("left top").unwrap(),
                parse_style_background_position("top left").unwrap()
            );
            // ... but "left right" is a vertical-slot error, not silently accepted.
            assert!(matches!(
                parse_style_background_position("left right"),
                Err(CssBackgroundPositionParseError::SecondComponentWrong(_))
            ));
        }
        #[test]
        fn autotest_background_position_too_many_components() {
            assert!(matches!(
                parse_style_background_position("left 10px top 20px"),
                Err(CssBackgroundPositionParseError::TooManyComponents(_))
            ));
            assert!(matches!(
                parse_style_background_position("a b c"),
                Err(CssBackgroundPositionParseError::TooManyComponents(_))
            ));
        }
        #[test]
        fn autotest_background_position_boundary_numbers_are_accepted_and_saturate() {
            // Pinned: parse_pixel_value accepts a bare number as px -- so "NaN" and
            // "inf" are *valid* background positions, flushed to 0 / saturated.
            assert_eq!(
                parse_style_background_position("NaN").unwrap().horizontal,
                BackgroundPositionHorizontal::Exact(PixelValue::px(0.0))
            );
            assert_eq!(
                parse_style_background_position("-0").unwrap().horizontal,
                BackgroundPositionHorizontal::Exact(PixelValue::px(0.0))
            );
            assert_eq!(
                parse_style_background_position("inf").unwrap().horizontal,
                BackgroundPositionHorizontal::Exact(PixelValue::px(f32::INFINITY))
            );
            for input in ["0", "1e40px", "-1e40px", "1e-45px", "3.4028235e38px"] {
                let p = parse_style_background_position(input).unwrap();
                let BackgroundPositionHorizontal::Exact(px) = p.horizontal else {
                    panic!("expected an exact value for {input:?}");
                };
                assert!(px.number.get().is_finite(), "non-finite for {input:?}");
            }
        }
        #[test]
        fn autotest_background_position_garbage_unicode_and_long_input() {
            for input in ["garbage", "!!!", "\u{1F600}", "e\u{0301}", "left;top"] {
                assert!(
                    parse_style_background_position(input).is_err(),
                    "{input:?} unexpectedly parsed"
                );
            }
            let huge = "a".repeat(100_000);
            assert!(parse_style_background_position(&huge).is_err());
            let nested = "(".repeat(10_000);
            assert!(parse_style_background_position(&nested).is_err());
            for input in ADVERSARIAL {
                let a = parse_style_background_position(input);
                let b = parse_style_background_position(input);
                assert_eq!(a, b, "non-deterministic for {input:?}");
            }
        }
        #[test]
        fn autotest_background_position_multiple() {
            // Empty input -> empty vec (no error), same as the other *_multiple fns.
            assert_eq!(
                parse_style_background_position_multiple("").unwrap().len(),
                0
            );
            let parsed = parse_style_background_position_multiple("left top, 10px 20px").unwrap();
            assert_eq!(parsed.len(), 2);
            assert_eq!(
                parsed.as_slice()[1].horizontal,
                BackgroundPositionHorizontal::Exact(PixelValue::px(10.0))
            );
            assert!(parse_style_background_position_multiple("left top, !!!").is_err());
            assert!(parse_style_background_position_multiple("   ").is_err());
            let many = "left top,".repeat(2_000) + "center";
            assert_eq!(
                parse_style_background_position_multiple(&many)
                    .unwrap()
                    .len(),
                2_001
            );
        }
        // ---------------------------------------------------------------
        // parser: parse_style_background_size(_multiple)
        // ---------------------------------------------------------------
        #[test]
        fn autotest_background_size_empty_whitespace_and_garbage() {
            for input in [
                "",
                "   ",
                "\t\n",
                "auto",
                "!!!",
                "\u{1F600}",
                "CONTAIN",
                "Cover",
            ] {
                assert!(
                    parse_style_background_size(input).is_err(),
                    "{input:?} unexpectedly parsed"
                );
            }
            let huge = "a".repeat(100_000);
            assert!(parse_style_background_size(&huge).is_err());
        }
        #[test]
        fn autotest_background_size_valid_minimal_and_trimming() {
            assert_eq!(
                parse_style_background_size("  contain  ").unwrap(),
                StyleBackgroundSize::Contain
            );
            assert_eq!(
                parse_style_background_size("cover").unwrap(),
                StyleBackgroundSize::Cover
            );
            // A single value applies to both axes.
            assert_eq!(
                parse_style_background_size("50%").unwrap(),
                StyleBackgroundSize::ExactSize(PixelValueSize {
                    width: PixelValue::percent(50.0),
                    height: PixelValue::percent(50.0),
                })
            );
        }
        #[test]
        fn autotest_background_size_silently_ignores_extra_components() {
            // BUG-ish, pinned: unlike background-position (TooManyComponents), a third
            // component is dropped on the floor instead of being rejected.
            assert_eq!(
                parse_style_background_size("10px 20px 30px").unwrap(),
                StyleBackgroundSize::ExactSize(PixelValueSize {
                    width: PixelValue::px(10.0),
                    height: PixelValue::px(20.0),
                })
            );
        }
        #[test]
        fn autotest_background_size_boundary_numbers_saturate_without_panicking() {
            // Bare numbers parse as px, so "NaN" is accepted and flushed to 0px.
            assert_eq!(
                parse_style_background_size("NaN").unwrap(),
                StyleBackgroundSize::ExactSize(PixelValueSize {
                    width: PixelValue::px(0.0),
                    height: PixelValue::px(0.0),
                })
            );
            assert_eq!(
                parse_style_background_size("inf").unwrap(),
                StyleBackgroundSize::ExactSize(PixelValueSize {
                    width: PixelValue::px(f32::INFINITY),
                    height: PixelValue::px(f32::INFINITY),
                })
            );
            for input in ["0", "-0", "1e40px", "-1e40px", "1e-45px"] {
                let StyleBackgroundSize::ExactSize(s) = parse_style_background_size(input).unwrap()
                else {
                    panic!("expected an exact size for {input:?}");
                };
                assert!(s.width.number.get().is_finite(), "non-finite for {input:?}");
                assert!(
                    s.height.number.get().is_finite(),
                    "non-finite for {input:?}"
                );
            }
            for input in ADVERSARIAL {
                let a = parse_style_background_size(input);
                let b = parse_style_background_size(input);
                assert_eq!(a, b, "non-deterministic for {input:?}");
            }
        }
        #[test]
        fn autotest_background_size_multiple() {
            assert_eq!(parse_style_background_size_multiple("").unwrap().len(), 0);
            let parsed = parse_style_background_size_multiple("contain, 10px 20px, cover").unwrap();
            assert_eq!(parsed.len(), 3);
            assert_eq!(parsed.as_slice()[0], StyleBackgroundSize::Contain);
            assert_eq!(parsed.as_slice()[2], StyleBackgroundSize::Cover);
            assert!(parse_style_background_size_multiple("cover, auto").is_err());
            assert!(parse_style_background_size_multiple("   ").is_err());
            let many = "cover,".repeat(2_000) + "contain";
            assert_eq!(
                parse_style_background_size_multiple(&many).unwrap().len(),
                2_001
            );
        }
        // ---------------------------------------------------------------
        // parser: parse_style_background_repeat(_multiple)
        // ---------------------------------------------------------------
        #[test]
        fn autotest_background_repeat_valid_and_invalid() {
            assert_eq!(
                parse_style_background_repeat("  repeat  ").unwrap(),
                StyleBackgroundRepeat::PatternRepeat
            );
            assert_eq!(
                parse_style_background_repeat("no-repeat").unwrap(),
                StyleBackgroundRepeat::NoRepeat
            );
            assert_eq!(
                parse_style_background_repeat("repeat-x").unwrap(),
                StyleBackgroundRepeat::RepeatX
            );
            assert_eq!(
                parse_style_background_repeat("repeat-y").unwrap(),
                StyleBackgroundRepeat::RepeatY
            );
            assert_eq!(
                StyleBackgroundRepeat::default(),
                StyleBackgroundRepeat::PatternRepeat
            );
            for input in [
                "",
                "   ",
                "\t\n",
                "REPEAT",
                "Repeat",
                "repeat-xy",
                "repeat repeat",
                "!!!",
                "\u{1F600}",
                "0",
                "NaN",
            ] {
                assert!(
                    parse_style_background_repeat(input).is_err(),
                    "{input:?} unexpectedly parsed"
                );
            }
            let huge = "repeat".repeat(20_000);
            assert!(parse_style_background_repeat(&huge).is_err());
            for input in ADVERSARIAL {
                let a = parse_style_background_repeat(input);
                let b = parse_style_background_repeat(input);
                assert_eq!(a, b, "non-deterministic for {input:?}");
            }
        }
        #[test]
        fn autotest_background_repeat_multiple() {
            assert_eq!(parse_style_background_repeat_multiple("").unwrap().len(), 0);
            let parsed = parse_style_background_repeat_multiple("repeat, no-repeat").unwrap();
            assert_eq!(parsed.len(), 2);
            assert_eq!(parsed.as_slice()[0], StyleBackgroundRepeat::PatternRepeat);
            assert_eq!(parsed.as_slice()[1], StyleBackgroundRepeat::NoRepeat);
            assert!(parse_style_background_repeat_multiple("repeat,,repeat").is_err());
            assert!(parse_style_background_repeat_multiple("   ").is_err());
            let many = "repeat,".repeat(2_000) + "no-repeat";
            assert_eq!(
                parse_style_background_repeat_multiple(&many).unwrap().len(),
                2_001
            );
        }
        // ---------------------------------------------------------------
        // parser: parse_gradient (private)
        // ---------------------------------------------------------------
        #[test]
        fn autotest_parse_gradient_empty_input_is_no_direction_for_every_type() {
            for t in ALL_GRADIENT_TYPES {
                assert!(
                    matches!(
                        parse_gradient("", t),
                        Err(CssBackgroundParseError::NoDirection(_))
                    ),
                    "empty body accepted for {t:?}"
                );
            }
        }
        #[test]
        fn autotest_parse_gradient_extend_mode_follows_the_gradient_type() {
            let StyleBackgroundContent::LinearGradient(g) =
                parse_gradient("red, blue", GradientType::LinearGradient).unwrap()
            else {
                panic!("expected a linear gradient");
            };
            assert_eq!(g.extend_mode, ExtendMode::Clamp);
            let StyleBackgroundContent::LinearGradient(g) =
                parse_gradient("red, blue", GradientType::RepeatingLinearGradient).unwrap()
            else {
                panic!("expected a linear gradient");
            };
            assert_eq!(g.extend_mode, ExtendMode::Repeat);
            let StyleBackgroundContent::RadialGradient(g) =
                parse_gradient("red, blue", GradientType::RepeatingRadialGradient).unwrap()
            else {
                panic!("expected a radial gradient");
            };
            assert_eq!(g.extend_mode, ExtendMode::Repeat);
            let StyleBackgroundContent::ConicGradient(g) =
                parse_gradient("red, blue", GradientType::RepeatingConicGradient).unwrap()
            else {
                panic!("expected a conic gradient");
            };
            assert_eq!(g.extend_mode, ExtendMode::Repeat);
        }
        #[test]
        fn autotest_parse_gradient_accepts_gradients_with_too_few_stops() {
            // W3C requires >= 2 color stops. Pinned: this parser happily returns
            // gradients with one or zero stops -- `TooFewGradientStops` is dead code.
            let StyleBackgroundContent::LinearGradient(g) =
                parse_gradient("red", GradientType::LinearGradient).unwrap()
            else {
                panic!("expected a linear gradient");
            };
            assert_eq!(g.stops.len(), 1);
            assert_eq!(offsets(&g.stops), alloc::vec![0.0]);
            // A direction with no stops at all -> zero stops, still Ok.
            let StyleBackgroundContent::LinearGradient(g) =
                parse_gradient("to right", GradientType::LinearGradient).unwrap()
            else {
                panic!("expected a linear gradient");
            };
            assert_eq!(g.stops.len(), 0);
            // Same for a radial gradient that only names a shape.
            let StyleBackgroundContent::RadialGradient(g) =
                parse_gradient("circle", GradientType::RadialGradient).unwrap()
            else {
                panic!("expected a radial gradient");
            };
            assert_eq!(g.shape, Shape::Circle);
            assert_eq!(g.stops.len(), 0);
        }
        #[test]
        fn autotest_parse_gradient_never_panics_on_adversarial_input() {
            let huge = "a".repeat(100_000);
            let nested = "(".repeat(10_000) + &")".repeat(10_000);
            let many_commas = ",".repeat(10_000);
            for t in ALL_GRADIENT_TYPES {
                for input in ADVERSARIAL {
                    let a = parse_gradient(input, t);
                    let b = parse_gradient(input, t);
                    assert_eq!(a, b, "non-deterministic for {input:?} / {t:?}");
                }
                for input in [huge.as_str(), nested.as_str(), many_commas.as_str()] {
                    let a = parse_gradient(input, t);
                    let b = parse_gradient(input, t);
                    assert_eq!(a, b, "non-deterministic for a long input / {t:?}");
                }
                // An empty body is rejected for every gradient type.
                assert!(
                    parse_gradient("", t).is_err(),
                    "empty body accepted for {t:?}"
                );
                // A comma-only body has nothing but empty stops -> always an error.
                assert!(
                    parse_gradient(&many_commas, t).is_err(),
                    "comma soup accepted for {t:?}"
                );
            }
            // Linear and conic reject junk outright. (Radial does not -- see
            // `autotest_radial_gradient_silently_drops_unparseable_items`.)
            for t in [
                GradientType::LinearGradient,
                GradientType::RepeatingLinearGradient,
                GradientType::ConicGradient,
                GradientType::RepeatingConicGradient,
            ] {
                assert!(parse_gradient(&huge, t).is_err(), "junk accepted for {t:?}");
                assert!(
                    parse_gradient(&nested, t).is_err(),
                    "junk accepted for {t:?}"
                );
                assert!(parse_gradient("!!!", t).is_err(), "junk accepted for {t:?}");
            }
        }
        #[test]
        fn autotest_radial_gradient_silently_drops_unparseable_items() {
            // BUG (pinned): in the radial branch, a comma-item that is neither a
            // shape/size/position *nor* a valid color stop is skipped rather than
            // rejected -- so pure garbage parses as a gradient with no stops, and a
            // junk leading item simply disappears.
            let StyleBackgroundContent::RadialGradient(g) =
                parse_gradient("!!!", GradientType::RadialGradient).unwrap()
            else {
                panic!("expected a radial gradient");
            };
            assert_eq!(g.stops.len(), 0);
            let g = radial("radial-gradient(!!!, red)");
            assert_eq!(g.stops.len(), 1, "the junk item should have been dropped");
            assert_eq!(g.stops.as_ref()[0].color, ColorOrSystem::Color(ColorU::RED));
            // The same input is a hard error for a linear gradient.
            assert!(parse_style_background_content("linear-gradient(!!!, red)").is_err());
        }
        #[test]
        fn autotest_radial_gradient_position_is_ignored_when_combined_with_a_shape() {
            // BUG (pinned): `parse_style_background_position` is handed the *whole*
            // comma-item ("circle at 50% 50%"), which has 4 whitespace components and
            // therefore fails -- so the `at <position>` part is silently dropped and
            // the position stays at its Left/Top default.
            let g = radial("radial-gradient(circle at 50% 50%, red, blue)");
            assert_eq!(g.shape, Shape::Circle);
            assert_eq!(g.position, StyleBackgroundPosition::default());
            assert_eq!(g.stops.len(), 2);
            // A position on its own (no shape/size in the same item) *is* honoured.
            let g = radial("radial-gradient(50% 50%, red, blue)");
            assert_eq!(
                g.position,
                StyleBackgroundPosition {
                    horizontal: BackgroundPositionHorizontal::Exact(PixelValue::percent(50.0)),
                    vertical: BackgroundPositionVertical::Exact(PixelValue::percent(50.0)),
                }
            );
            assert_eq!(g.stops.len(), 2);
        }
        #[test]
        fn autotest_radial_gradient_shape_and_size_keywords() {
            let g = radial("radial-gradient(circle closest-side, red, blue)");
            assert_eq!(g.shape, Shape::Circle);
            assert_eq!(g.size, RadialGradientSize::ClosestSide);
            let g = radial("radial-gradient(ellipse farthest-side, red, blue)");
            assert_eq!(g.shape, Shape::Ellipse);
            assert_eq!(g.size, RadialGradientSize::FarthestSide);
            // Defaults when nothing is named.
            let g = radial("radial-gradient(red, blue)");
            assert_eq!(g.shape, Shape::default());
            assert_eq!(g.size, RadialGradientSize::default());
        }
        // ---------------------------------------------------------------
        // parser: parse_linear_color_stop / parse_radial_color_stop (private)
        // ---------------------------------------------------------------
        #[test]
        fn autotest_parse_linear_color_stop_valid_minimal() {
            let s = parse_linear_color_stop("red").unwrap();
            assert_eq!(s.color, ColorOrSystem::Color(ColorU::RED));
            assert_eq!(s.offset1, OptionPercentageValue::None);
            assert_eq!(s.offset2, OptionPercentageValue::None);
            let s = parse_linear_color_stop("  red 50%  ").unwrap();
            assert_eq!(
                s.offset1,
                OptionPercentageValue::Some(PercentageValue::new(50.0))
            );
            assert_eq!(s.offset2, OptionPercentageValue::None);
            let s = parse_linear_color_stop("red 10% 30%").unwrap();
            assert_eq!(
                s.offset1,
                OptionPercentageValue::Some(PercentageValue::new(10.0))
            );
            assert_eq!(
                s.offset2,
                OptionPercentageValue::Some(PercentageValue::new(30.0))
            );
            // Colors that themselves contain spaces and digits still split correctly.
            let s = parse_linear_color_stop("rgba(0, 0, 0, 0.5) 50%").unwrap();
            assert_eq!(
                s.offset1,
                OptionPercentageValue::Some(PercentageValue::new(50.0))
            );
            // System colors are accepted as stop colors.
            let s = parse_linear_color_stop("system:accent 50%").unwrap();
            assert_eq!(s.color, ColorOrSystem::System(SystemColorRef::Accent));
        }
        #[test]
        fn autotest_parse_linear_color_stop_rejects_junk() {
            for input in [
                "",
                "   ",
                "\t\n",
                "!!!",
                "\u{1F600}",
                "red 50px",        // offset must be a percentage
                "red 0.5",         // bare number is not recognised as an offset
                "red 10% 20% 30%", // three offsets -> the color part is junk
                "red blue",
            ] {
                assert!(
                    parse_linear_color_stop(input).is_err(),
                    "{input:?} unexpectedly parsed"
                );
            }
            let huge = "a".repeat(100_000);
            assert!(parse_linear_color_stop(&huge).is_err());
        }
        #[test]
        fn autotest_parse_radial_color_stop_valid_and_junk() {
            let s = parse_radial_color_stop("red").unwrap();
            assert_eq!(s.color, ColorOrSystem::Color(ColorU::RED));
            assert_eq!(s.offset1, OptionAngleValue::None);
            let s = parse_radial_color_stop("red 90deg").unwrap();
            assert_eq!(s.offset1, OptionAngleValue::Some(AngleValue::deg(90.0)));
            assert_eq!(s.offset2, OptionAngleValue::None);
            let s = parse_radial_color_stop("red 45deg 90deg").unwrap();
            assert_eq!(s.offset1, OptionAngleValue::Some(AngleValue::deg(45.0)));
            assert_eq!(s.offset2, OptionAngleValue::Some(AngleValue::deg(90.0)));
            // Pinned: a *percentage* is a valid angle for a conic stop.
            assert!(parse_radial_color_stop("red 50%").is_ok());
            for input in [
                "",
                "   ",
                "!!!",
                "\u{1F600}",
                "red 5",
                "red 90deg 45deg 10deg",
            ] {
                assert!(
                    parse_radial_color_stop(input).is_err(),
                    "{input:?} unexpectedly parsed"
                );
            }
            let huge = "a".repeat(100_000);
            assert!(parse_radial_color_stop(&huge).is_err());
        }
        // ---------------------------------------------------------------
        // other: split_color_and_offsets / try_split_last_offset (private)
        // ---------------------------------------------------------------
        #[test]
        fn autotest_split_color_and_offsets_w3c_shapes() {
            assert_eq!(split_color_and_offsets("red"), ("red", None, None));
            assert_eq!(
                split_color_and_offsets("red 50%"),
                ("red", Some("50%"), None)
            );
            assert_eq!(
                split_color_and_offsets("red 10% 30%"),
                ("red", Some("10%"), Some("30%"))
            );
            assert_eq!(
                split_color_and_offsets("rgba(0, 0, 0, 0.5) 10% 30%"),
                ("rgba(0, 0, 0, 0.5)", Some("10%"), Some("30%"))
            );
            // A direction is never mistaken for offsets (no digits).
            assert_eq!(
                split_color_and_offsets("to right bottom"),
                ("to right bottom", None, None)
            );
        }
        #[test]
        fn autotest_split_color_and_offsets_never_panics_on_edges() {
            assert_eq!(split_color_and_offsets(""), ("", None, None));
            assert_eq!(split_color_and_offsets("   "), ("", None, None));
            // Multibyte input: splitting must land on a char boundary.
            assert_eq!(
                split_color_and_offsets("\u{1F600} 50%"),
                ("\u{1F600}", Some("50%"), None)
            );
            // A non-breaking space counts as whitespace for rfind *and* for trim.
            assert_eq!(
                split_color_and_offsets("red\u{00a0}50%"),
                ("red", Some("50%"), None)
            );
            let huge = "a".repeat(100_000);
            assert_eq!(split_color_and_offsets(&huge), (huge.as_str(), None, None));
            for input in ADVERSARIAL {
                assert_eq!(
                    split_color_and_offsets(input),
                    split_color_and_offsets(input)
                );
            }
        }
        #[test]
        fn autotest_try_split_last_offset() {
            assert_eq!(try_split_last_offset("red 50%"), Some(("red", "50%")));
            assert_eq!(try_split_last_offset("red 10px"), Some(("red", "10px")));
            // No whitespace -> nothing to split off.
            assert_eq!(try_split_last_offset("50%"), None);
            // Not offset-shaped.
            assert_eq!(try_split_last_offset("red blue"), None);
            assert_eq!(try_split_last_offset("red 5"), None);
            assert_eq!(try_split_last_offset("to right"), None);
            // Empty / whitespace-only.
            assert_eq!(try_split_last_offset(""), None);
            assert_eq!(try_split_last_offset("   "), None);
            assert_eq!(try_split_last_offset("\t\n"), None);
            for input in ADVERSARIAL {
                assert_eq!(try_split_last_offset(input), try_split_last_offset(input));
            }
        }
        // ---------------------------------------------------------------
        // predicate: is_likely_offset (private)
        // ---------------------------------------------------------------
        #[test]
        fn autotest_is_likely_offset_basic_true_false() {
            for s in [
                "50%", "10px", "0.5turn", "90deg", "1rem", "2vmin", "3vmax", "4grad", "5rad",
                "-50%", "1e40%",
            ] {
                assert!(is_likely_offset(s), "{s:?} should look like an offset");
            }
            for s in [
                "",
                " ",
                "red",
                "px",
                "%",
                "5",
                "0.5",
                "NaN%",
                "to",
                "right",
                "\u{1F600}",
                "contain",
            ] {
                assert!(!is_likely_offset(s), "{s:?} should not look like an offset");
            }
        }
        #[test]
        fn autotest_is_likely_offset_is_a_shape_check_not_a_validator() {
            // Pinned: it only requires "contains an ASCII digit" + "ends with a unit",
            // so plainly invalid tokens pass. The real parse still rejects them.
            assert!(is_likely_offset("abc1px"));
            assert!(is_likely_offset("\u{1F600}5%"));
            assert!(is_likely_offset("--1--px"));
            assert!(is_likely_offset("1%%%"));
            // ... and the digit check must be ASCII: an Arabic-Indic digit does not
            // count, so this is *not* treated as an offset.
            assert!(!is_likely_offset("\u{0661}%"));
            let huge = "9".repeat(100_000) + "%";
            assert!(is_likely_offset(&huge));
            for input in ADVERSARIAL {
                assert_eq!(is_likely_offset(input), is_likely_offset(input));
            }
        }
        // ---------------------------------------------------------------
        // parser: parse_conic_first_item (private)
        // ---------------------------------------------------------------
        #[test]
        fn autotest_parse_conic_first_item_valid_and_absent() {
            // Not a "from ..." prelude -> Ok(None), so the item is a color stop.
            assert_eq!(parse_conic_first_item("").unwrap(), None);
            assert_eq!(parse_conic_first_item("red").unwrap(), None);
            assert_eq!(parse_conic_first_item("   ").unwrap(), None);
            let (angle, pos) = parse_conic_first_item("from 90deg").unwrap().unwrap();
            assert_eq!(angle, AngleValue::deg(90.0));
            assert_eq!(pos, StyleBackgroundPosition::default());
            let (angle, pos) = parse_conic_first_item("from 0deg at center")
                .unwrap()
                .unwrap();
            assert_eq!(angle, AngleValue::deg(0.0));
            assert_eq!(pos.horizontal, BackgroundPositionHorizontal::Center);
            assert_eq!(pos.vertical, BackgroundPositionVertical::Center);
        }
        #[test]
        fn autotest_parse_conic_first_item_rejects_malformed_preludes() {
            // "from" with no angle.
            assert!(parse_conic_first_item("from").is_err());
            assert!(parse_conic_first_item("from at center").is_err());
            // Pinned quirk: any token *starting with* "from" enters the prelude branch,
            // so a would-be color like "fromage" becomes an angle error.
            assert!(parse_conic_first_item("fromage").is_err());
            // Too many position components.
            assert!(matches!(
                parse_conic_first_item("from 90deg at left top center"),
                Err(CssConicGradientParseError::Position(_))
            ));
            let huge = alloc::format!("from {}", "9".repeat(100_000));
            let _ = parse_conic_first_item(&huge);
            for input in ADVERSARIAL {
                let a = parse_conic_first_item(input);
                let b = parse_conic_first_item(input);
                assert_eq!(a, b, "non-deterministic for {input:?}");
            }
        }
        #[test]
        fn autotest_conic_gradient_end_to_end() {
            let g = conic("conic-gradient(from 45deg, red, blue)");
            assert_eq!(g.angle, AngleValue::deg(45.0));
            assert_eq!(g.extend_mode, ExtendMode::Clamp);
            assert_eq!(g.stops.len(), 2);
            assert_eq!(g.stops.as_ref()[0].angle.to_degrees_raw(), 0.0);
            assert_eq!(g.stops.as_ref()[1].angle.to_degrees_raw(), 360.0);
            // Conic stop angles are monotonic and finite, even for silly inputs.
            for input in [
                "conic-gradient(red, blue)",
                "conic-gradient(red 0deg, blue 180deg, green 360deg)",
                "conic-gradient(red 180deg, blue 90deg)",
                "conic-gradient(red -90deg, blue)",
                "repeating-conic-gradient(red, blue 30deg)",
            ] {
                let g = conic(input);
                let mut prev = f32::NEG_INFINITY;
                for s in &g.stops {
                    let deg = s.angle.to_degrees_raw();
                    assert!(deg.is_finite(), "non-finite angle in {input:?}");
                    assert!(deg >= prev, "angles not monotonic in {input:?}");
                    prev = deg;
                }
            }
            // An overflowing angle saturates instead of leaking inf into the stops.
            let g = conic("conic-gradient(red 1e40deg, blue)");
            assert_eq!(g.stops.len(), 2);
            for s in &g.stops {
                assert!(s.angle.to_degrees_raw().is_finite());
            }
            assert!(parse_style_background_content("conic-gradient(from, red)").is_err());
        }
        // ---------------------------------------------------------------
        // parser: parse_background_position_{horizontal,vertical} (private)
        // ---------------------------------------------------------------
        #[test]
        fn autotest_parse_background_position_horizontal() {
            assert_eq!(
                parse_background_position_horizontal("left").unwrap(),
                BackgroundPositionHorizontal::Left
            );
            assert_eq!(
                parse_background_position_horizontal("center").unwrap(),
                BackgroundPositionHorizontal::Center
            );
            assert_eq!(
                parse_background_position_horizontal("right").unwrap(),
                BackgroundPositionHorizontal::Right
            );
            assert_eq!(
                parse_background_position_horizontal("10px").unwrap(),
                BackgroundPositionHorizontal::Exact(PixelValue::px(10.0))
            );
            // Vertical keywords are not horizontal ones.
            assert!(parse_background_position_horizontal("top").is_err());
            // Pinned: no trimming here (callers pass whitespace-split tokens).
            assert!(parse_background_position_horizontal(" left").is_err());
            assert!(parse_background_position_horizontal("").is_err());
            assert!(parse_background_position_horizontal("\u{1F600}").is_err());
            let huge = "a".repeat(100_000);
            assert!(parse_background_position_horizontal(&huge).is_err());
        }
        #[test]
        fn autotest_parse_background_position_vertical() {
            assert_eq!(
                parse_background_position_vertical("top").unwrap(),
                BackgroundPositionVertical::Top
            );
            assert_eq!(
                parse_background_position_vertical("center").unwrap(),
                BackgroundPositionVertical::Center
            );
            assert_eq!(
                parse_background_position_vertical("bottom").unwrap(),
                BackgroundPositionVertical::Bottom
            );
            assert_eq!(
                parse_background_position_vertical("-10px").unwrap(),
                BackgroundPositionVertical::Exact(PixelValue::px(-10.0))
            );
            assert!(parse_background_position_vertical("left").is_err());
            assert!(parse_background_position_vertical("").is_err());
            assert!(parse_background_position_vertical("\u{1F600}").is_err());
            let huge = "a".repeat(100_000);
            assert!(parse_background_position_vertical(&huge).is_err());
        }
        // ---------------------------------------------------------------
        // parser: parse_shape / parse_radial_gradient_size (private)
        // ---------------------------------------------------------------
        #[test]
        fn autotest_parse_shape() {
            assert_eq!(parse_shape("circle").unwrap(), Shape::Circle);
            assert_eq!(parse_shape("  ellipse  ").unwrap(), Shape::Ellipse);
            for input in [
                "",
                "   ",
                "Circle",
                "CIRCLE",
                "circles",
                "!!!",
                "\u{1F600}",
                "0",
            ] {
                assert!(parse_shape(input).is_err(), "{input:?} unexpectedly parsed");
            }
            let huge = "a".repeat(100_000);
            assert!(parse_shape(&huge).is_err());
            for input in ADVERSARIAL {
                assert_eq!(parse_shape(input), parse_shape(input));
            }
        }
        #[test]
        fn autotest_parse_radial_gradient_size() {
            assert_eq!(
                parse_radial_gradient_size("closest-side").unwrap(),
                RadialGradientSize::ClosestSide
            );
            assert_eq!(
                parse_radial_gradient_size("  closest-corner ").unwrap(),
                RadialGradientSize::ClosestCorner
            );
            assert_eq!(
                parse_radial_gradient_size("farthest-side").unwrap(),
                RadialGradientSize::FarthestSide
            );
            assert_eq!(
                parse_radial_gradient_size("farthest-corner").unwrap(),
                RadialGradientSize::FarthestCorner
            );
            for input in [
                "",
                "   ",
                "closest",
                "CLOSEST-SIDE",
                "farthest-corners",
                "!!!",
                "\u{1F600}",
            ] {
                assert!(
                    parse_radial_gradient_size(input).is_err(),
                    "{input:?} unexpectedly parsed"
                );
            }
            let huge = "a".repeat(100_000);
            assert!(parse_radial_gradient_size(&huge).is_err());
        }
        // ---------------------------------------------------------------
        // round-trips: print_as_css_value -> parse
        // ---------------------------------------------------------------
        #[test]
        fn autotest_round_trip_background_repeat() {
            for r in [
                StyleBackgroundRepeat::NoRepeat,
                StyleBackgroundRepeat::PatternRepeat,
                StyleBackgroundRepeat::RepeatX,
                StyleBackgroundRepeat::RepeatY,
            ] {
                let printed = r.print_as_css_value();
                assert!(!printed.is_empty());
                assert_eq!(parse_style_background_repeat(&printed).unwrap(), r);
            }
        }
        #[test]
        fn autotest_round_trip_background_size() {
            for s in [
                StyleBackgroundSize::Contain,
                StyleBackgroundSize::Cover,
                StyleBackgroundSize::ExactSize(PixelValueSize {
                    width: PixelValue::px(100.0),
                    height: PixelValue::em(20.0),
                }),
                StyleBackgroundSize::ExactSize(PixelValueSize {
                    width: PixelValue::percent(50.0),
                    height: PixelValue::percent(50.0),
                }),
                StyleBackgroundSize::ExactSize(PixelValueSize {
                    width: PixelValue::px(0.0),
                    height: PixelValue::px(-25.5),
                }),
            ] {
                let printed = s.print_as_css_value();
                assert_eq!(
                    parse_style_background_size(&printed).unwrap(),
                    s,
                    "round-trip failed for {printed:?}"
                );
            }
        }
        #[test]
        fn autotest_round_trip_background_position() {
            let horizontals = [
                BackgroundPositionHorizontal::Left,
                BackgroundPositionHorizontal::Center,
                BackgroundPositionHorizontal::Right,
                BackgroundPositionHorizontal::Exact(PixelValue::px(50.0)),
                BackgroundPositionHorizontal::Exact(PixelValue::percent(25.0)),
            ];
            let verticals = [
                BackgroundPositionVertical::Top,
                BackgroundPositionVertical::Center,
                BackgroundPositionVertical::Bottom,
                BackgroundPositionVertical::Exact(PixelValue::px(-10.0)),
                BackgroundPositionVertical::Exact(PixelValue::em(2.5)),
            ];
            for horizontal in horizontals {
                for vertical in verticals {
                    let pos = StyleBackgroundPosition {
                        horizontal,
                        vertical,
                    };
                    let printed = pos.print_as_css_value();
                    assert_eq!(
                        parse_style_background_position(&printed).unwrap(),
                        pos,
                        "round-trip failed for {printed:?}"
                    );
                }
            }
        }
        #[test]
        fn autotest_round_trip_background_content_colors_and_images() {
            for content in [
                StyleBackgroundContent::Color(ColorU::RED),
                StyleBackgroundContent::Color(ColorU::TRANSPARENT),
                StyleBackgroundContent::Color(ColorU::rgba(1, 2, 3, 4)),
                StyleBackgroundContent::Color(ColorU::WHITE),
                StyleBackgroundContent::Image("a.png".into()),
                StyleBackgroundContent::Image("some/deep/path.jpeg".into()),
                StyleBackgroundContent::SystemColor(SystemColorRef::Accent),
                StyleBackgroundContent::SystemColor(SystemColorRef::SelectionText),
            ] {
                let printed = content.print_as_css_value();
                assert_eq!(
                    parse_style_background_content(&printed).unwrap(),
                    content,
                    "round-trip failed for {printed:?}"
                );
            }
            assert_eq!(
                StyleBackgroundContent::default(),
                StyleBackgroundContent::Color(ColorU::TRANSPARENT)
            );
        }
        #[test]
        fn autotest_round_trip_gradients() {
            for input in [
                "linear-gradient(to right, red 0%, blue 100%)",
                "repeating-linear-gradient(to bottom, red 25%, blue 75%)",
                "linear-gradient(45deg, red 0%, blue 50%)",
                "radial-gradient(circle farthest-corner at left top, red 0%, blue 100%)",
                "conic-gradient(from 90deg at left top, red 0deg, blue 360deg)",
                "repeating-conic-gradient(from 0deg at left top, red 0deg, blue 180deg)",
            ] {
                let parsed = parse_style_background_content(input).unwrap();
                let printed = parsed.print_as_css_value();
                let reparsed = parse_style_background_content(&printed).unwrap();
                assert_eq!(
                    parsed, reparsed,
                    "gradient did not survive print -> parse ({printed:?})"
                );
                // ... and printing is stable across the round-trip.
                assert_eq!(printed, reparsed.print_as_css_value());
            }
        }
        #[test]
        fn autotest_round_trip_vec_printing_is_comma_separated() {
            let contents = parse_style_background_content_multiple("red, blue").unwrap();
            assert_eq!(contents.print_as_css_value(), "#ff0000ff, #0000ffff");
            assert_eq!(
                contents.as_slice()[1],
                StyleBackgroundContent::Color(blue())
            );
            let reparsed =
                parse_style_background_content_multiple(&contents.print_as_css_value()).unwrap();
            assert_eq!(reparsed, contents);
            let sizes = parse_style_background_size_multiple("contain, 10px 20px").unwrap();
            assert_eq!(
                parse_style_background_size_multiple(&sizes.print_as_css_value()).unwrap(),
                sizes
            );
            let repeats = parse_style_background_repeat_multiple("repeat, no-repeat").unwrap();
            assert_eq!(
                parse_style_background_repeat_multiple(&repeats.print_as_css_value()).unwrap(),
                repeats
            );
            let positions =
                parse_style_background_position_multiple("left top, 10px 20px").unwrap();
            assert_eq!(
                parse_style_background_position_multiple(&positions.print_as_css_value()).unwrap(),
                positions
            );
        }
        #[test]
        fn autotest_normalized_stop_printing_is_reparseable() {
            let stop = NormalizedLinearColorStop::new(PercentageValue::new(25.0), ColorU::RED);
            assert_eq!(stop.print_as_css_value(), "#ff0000ff 25%");
            let reparsed = parse_linear_color_stop(&stop.print_as_css_value()).unwrap();
            assert_eq!(reparsed.color, stop.color);
            assert_eq!(
                reparsed.offset1,
                OptionPercentageValue::Some(PercentageValue::new(25.0))
            );
            let rstop = NormalizedRadialColorStop::new(AngleValue::deg(90.0), blue());
            assert_eq!(rstop.print_as_css_value(), "#0000ffff 90deg");
            let reparsed = parse_radial_color_stop(&rstop.print_as_css_value()).unwrap();
            assert_eq!(reparsed.color, rstop.color);
            assert_eq!(
                reparsed.offset1,
                OptionAngleValue::Some(AngleValue::deg(90.0))
            );
            // System-colored stops print their `system:*` name and re-parse.
            let sys = NormalizedLinearColorStop {
                offset: PercentageValue::new(50.0),
                color: ColorOrSystem::System(SystemColorRef::Accent),
            };
            assert_eq!(sys.print_as_css_value(), "system:accent 50%");
            assert_eq!(
                parse_linear_color_stop(&sys.print_as_css_value())
                    .unwrap()
                    .color,
                ColorOrSystem::System(SystemColorRef::Accent)
            );
        }
        #[test]
        fn autotest_empty_gradient_printing_does_not_panic() {
            // Default gradients have zero stops -- printing must still produce
            // something well-formed (and not, say, index out of bounds).
            let lg = StyleBackgroundContent::LinearGradient(LinearGradient::default());
            assert!(lg.print_as_css_value().starts_with("linear-gradient("));
            let rg = StyleBackgroundContent::RadialGradient(RadialGradient::default());
            assert!(rg.print_as_css_value().starts_with("radial-gradient("));
            let cg = StyleBackgroundContent::ConicGradient(ConicGradient::default());
            assert!(cg.print_as_css_value().starts_with("conic-gradient("));
            // A gradient built from an empty stop list is also printable.
            let empty_stops = StyleBackgroundContent::LinearGradient(LinearGradient {
                extend_mode: ExtendMode::Repeat,
                stops: Vec::<NormalizedLinearColorStop>::new().into(),
                ..LinearGradient::default()
            });
            assert!(empty_stops
                .print_as_css_value()
                .starts_with("repeating-linear-gradient("));
        }
    }
}
#[cfg(feature = "parser")]
pub use self::parser::*;
#[cfg(all(test, feature = "parser"))]
mod tests {
    use super::*;
    use crate::props::basic::{DirectionCorner, DirectionCorners};
    #[test]
1
    fn test_parse_single_background_content() {
        // Color
1
        assert_eq!(
1
            parse_style_background_content("red").unwrap(),
            StyleBackgroundContent::Color(ColorU::RED)
        );
1
        assert_eq!(
1
            parse_style_background_content("#ff00ff").unwrap(),
1
            StyleBackgroundContent::Color(ColorU::new_rgb(255, 0, 255))
        );
        // Image
1
        assert_eq!(
1
            parse_style_background_content("url(\"image.png\")").unwrap(),
1
            StyleBackgroundContent::Image("image.png".into())
        );
        // Linear Gradient
1
        let lg = parse_style_background_content("linear-gradient(to right, red, blue)").unwrap();
1
        assert!(matches!(lg, StyleBackgroundContent::LinearGradient(_)));
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
1
            assert_eq!(grad.stops.len(), 2);
1
            assert_eq!(
                grad.direction,
                Direction::FromTo(DirectionCorners {
                    dir_from: DirectionCorner::Left,
                    dir_to: DirectionCorner::Right
                })
            );
        }
        // Radial Gradient
1
        let rg = parse_style_background_content("radial-gradient(circle, white, black)").unwrap();
1
        assert!(matches!(rg, StyleBackgroundContent::RadialGradient(_)));
1
        if let StyleBackgroundContent::RadialGradient(grad) = rg {
1
            assert_eq!(grad.stops.len(), 2);
1
            assert_eq!(grad.shape, Shape::Circle);
        }
        // Conic Gradient
1
        let cg = parse_style_background_content("conic-gradient(from 90deg, red, blue)").unwrap();
1
        assert!(matches!(cg, StyleBackgroundContent::ConicGradient(_)));
1
        if let StyleBackgroundContent::ConicGradient(grad) = cg {
1
            assert_eq!(grad.stops.len(), 2);
1
            assert_eq!(grad.angle, AngleValue::deg(90.0));
        }
1
    }
    #[test]
1
    fn test_parse_multiple_background_content() {
1
        let result =
1
            parse_style_background_content_multiple("url(foo.png), linear-gradient(red, blue)")
1
                .unwrap();
1
        assert_eq!(result.len(), 2);
1
        assert!(matches!(
1
            result.as_slice()[0],
            StyleBackgroundContent::Image(_)
        ));
1
        assert!(matches!(
1
            result.as_slice()[1],
            StyleBackgroundContent::LinearGradient(_)
        ));
1
    }
    #[test]
1
    fn test_parse_background_position() {
        // One value
1
        let result = parse_style_background_position("center").unwrap();
1
        assert_eq!(result.horizontal, BackgroundPositionHorizontal::Center);
1
        assert_eq!(result.vertical, BackgroundPositionVertical::Center);
1
        let result = parse_style_background_position("25%").unwrap();
1
        assert_eq!(
            result.horizontal,
1
            BackgroundPositionHorizontal::Exact(PixelValue::percent(25.0))
        );
1
        assert_eq!(result.vertical, BackgroundPositionVertical::Center);
        // Two values
1
        let result = parse_style_background_position("right 50px").unwrap();
1
        assert_eq!(result.horizontal, BackgroundPositionHorizontal::Right);
1
        assert_eq!(
            result.vertical,
1
            BackgroundPositionVertical::Exact(PixelValue::px(50.0))
        );
        // Four values (not supported by this parser, should fail)
1
        assert!(parse_style_background_position("left 10px top 20px").is_err());
1
    }
    #[test]
1
    fn test_parse_background_size() {
1
        assert_eq!(
1
            parse_style_background_size("contain").unwrap(),
            StyleBackgroundSize::Contain
        );
1
        assert_eq!(
1
            parse_style_background_size("cover").unwrap(),
            StyleBackgroundSize::Cover
        );
1
        assert_eq!(
1
            parse_style_background_size("50%").unwrap(),
1
            StyleBackgroundSize::ExactSize(PixelValueSize {
1
                width: PixelValue::percent(50.0),
1
                height: PixelValue::percent(50.0)
1
            })
        );
1
        assert_eq!(
1
            parse_style_background_size("100px 20em").unwrap(),
1
            StyleBackgroundSize::ExactSize(PixelValueSize {
1
                width: PixelValue::px(100.0),
1
                height: PixelValue::em(20.0)
1
            })
        );
1
        assert!(parse_style_background_size("auto").is_err());
1
    }
    #[test]
1
    fn test_parse_background_repeat() {
1
        assert_eq!(
1
            parse_style_background_repeat("repeat").unwrap(),
            StyleBackgroundRepeat::PatternRepeat
        );
1
        assert_eq!(
1
            parse_style_background_repeat("repeat-x").unwrap(),
            StyleBackgroundRepeat::RepeatX
        );
1
        assert_eq!(
1
            parse_style_background_repeat("repeat-y").unwrap(),
            StyleBackgroundRepeat::RepeatY
        );
1
        assert_eq!(
1
            parse_style_background_repeat("no-repeat").unwrap(),
            StyleBackgroundRepeat::NoRepeat
        );
1
        assert!(parse_style_background_repeat("repeat-xy").is_err());
1
    }
    // =========================================================================
    // W3C CSS Images Level 3 - Gradient Parsing Tests
    // =========================================================================
    #[test]
1
    fn test_gradient_no_position_stops() {
        // "linear-gradient(red, blue)" - no positions specified
1
        let lg = parse_style_background_content("linear-gradient(red, blue)").unwrap();
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
1
            assert_eq!(grad.stops.len(), 2);
            // First stop should default to 0%
1
            assert!((grad.stops.as_ref()[0].offset.normalized() - 0.0).abs() < 0.001);
            // Last stop should default to 100%
1
            assert!((grad.stops.as_ref()[1].offset.normalized() - 1.0).abs() < 0.001);
        } else {
            panic!("Expected LinearGradient");
        }
1
    }
    #[test]
1
    fn test_gradient_single_position_stops() {
        // "linear-gradient(red 25%, blue 75%)" - one position per stop
1
        let lg = parse_style_background_content("linear-gradient(red 25%, blue 75%)").unwrap();
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
1
            assert_eq!(grad.stops.len(), 2);
1
            assert!((grad.stops.as_ref()[0].offset.normalized() - 0.25).abs() < 0.001);
1
            assert!((grad.stops.as_ref()[1].offset.normalized() - 0.75).abs() < 0.001);
        } else {
            panic!("Expected LinearGradient");
        }
1
    }
    #[test]
1
    fn test_gradient_multi_position_stops() {
        // "linear-gradient(red 10% 30%, blue)" - two positions create two stops
1
        let lg = parse_style_background_content("linear-gradient(red 10% 30%, blue)").unwrap();
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
            // Should have 3 stops: red@10%, red@30%, blue@100%
1
            assert_eq!(grad.stops.len(), 3, "Expected 3 stops for multi-position");
1
            assert!((grad.stops.as_ref()[0].offset.normalized() - 0.10).abs() < 0.001);
1
            assert!((grad.stops.as_ref()[1].offset.normalized() - 0.30).abs() < 0.001);
1
            assert!((grad.stops.as_ref()[2].offset.normalized() - 1.0).abs() < 0.001);
            // Both first two stops should have same color (red)
1
            assert_eq!(grad.stops.as_ref()[0].color, grad.stops.as_ref()[1].color);
        } else {
            panic!("Expected LinearGradient");
        }
1
    }
    #[test]
1
    fn test_gradient_three_colors_no_positions() {
        // "linear-gradient(red, green, blue)" - evenly distributed
1
        let lg = parse_style_background_content("linear-gradient(red, green, blue)").unwrap();
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
1
            assert_eq!(grad.stops.len(), 3);
            // Positions: 0%, 50%, 100%
1
            assert!((grad.stops.as_ref()[0].offset.normalized() - 0.0).abs() < 0.001);
1
            assert!((grad.stops.as_ref()[1].offset.normalized() - 0.5).abs() < 0.001);
1
            assert!((grad.stops.as_ref()[2].offset.normalized() - 1.0).abs() < 0.001);
        } else {
            panic!("Expected LinearGradient");
        }
1
    }
    #[test]
1
    fn test_gradient_fixup_ascending_order() {
        // "linear-gradient(red 50%, blue 20%)" - blue position < red position
        // W3C says: clamp to max of previous positions
1
        let lg = parse_style_background_content("linear-gradient(red 50%, blue 20%)").unwrap();
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
1
            assert_eq!(grad.stops.len(), 2);
            // First stop at 50%
1
            assert!((grad.stops.as_ref()[0].offset.normalized() - 0.50).abs() < 0.001);
            // Second stop clamped to 50% (not 20%)
1
            assert!((grad.stops.as_ref()[1].offset.normalized() - 0.50).abs() < 0.001);
        } else {
            panic!("Expected LinearGradient");
        }
1
    }
    #[test]
1
    fn test_gradient_distribute_unpositioned() {
        // "linear-gradient(red 0%, yellow, green, blue 100%)"
        // yellow and green should be distributed evenly between 0% and 100%
1
        let lg =
1
            parse_style_background_content("linear-gradient(red 0%, yellow, green, blue 100%)")
1
                .unwrap();
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
1
            assert_eq!(grad.stops.len(), 4);
            // Positions: 0%, 33.3%, 66.6%, 100%
1
            assert!((grad.stops.as_ref()[0].offset.normalized() - 0.0).abs() < 0.001);
1
            assert!((grad.stops.as_ref()[1].offset.normalized() - 0.333).abs() < 0.01);
1
            assert!((grad.stops.as_ref()[2].offset.normalized() - 0.666).abs() < 0.01);
1
            assert!((grad.stops.as_ref()[3].offset.normalized() - 1.0).abs() < 0.001);
        } else {
            panic!("Expected LinearGradient");
        }
1
    }
    #[test]
1
    fn test_gradient_direction_to_corner() {
        // "linear-gradient(to top right, red, blue)"
1
        let lg =
1
            parse_style_background_content("linear-gradient(to top right, red, blue)").unwrap();
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
1
            assert_eq!(
                grad.direction,
                Direction::FromTo(DirectionCorners {
                    dir_from: DirectionCorner::BottomLeft,
                    dir_to: DirectionCorner::TopRight
                })
            );
        } else {
            panic!("Expected LinearGradient");
        }
1
    }
    #[test]
1
    fn test_gradient_direction_angle() {
        // "linear-gradient(45deg, red, blue)"
1
        let lg = parse_style_background_content("linear-gradient(45deg, red, blue)").unwrap();
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
1
            assert_eq!(grad.direction, Direction::Angle(AngleValue::deg(45.0)));
        } else {
            panic!("Expected LinearGradient");
        }
1
    }
    #[test]
1
    fn test_repeating_gradient() {
        // "repeating-linear-gradient(red, blue 20%)"
1
        let lg =
1
            parse_style_background_content("repeating-linear-gradient(red, blue 20%)").unwrap();
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
1
            assert_eq!(grad.extend_mode, ExtendMode::Repeat);
        } else {
            panic!("Expected LinearGradient");
        }
1
    }
    #[test]
1
    fn test_radial_gradient_circle() {
        // "radial-gradient(circle, red, blue)"
1
        let rg = parse_style_background_content("radial-gradient(circle, red, blue)").unwrap();
1
        if let StyleBackgroundContent::RadialGradient(grad) = rg {
1
            assert_eq!(grad.shape, Shape::Circle);
1
            assert_eq!(grad.stops.len(), 2);
            // Check default position is center
1
            assert_eq!(grad.position.horizontal, BackgroundPositionHorizontal::Left);
1
            assert_eq!(grad.position.vertical, BackgroundPositionVertical::Top);
        } else {
            panic!("Expected RadialGradient");
        }
1
    }
    #[test]
1
    fn test_radial_gradient_ellipse() {
        // "radial-gradient(ellipse, red, blue)"
1
        let rg = parse_style_background_content("radial-gradient(ellipse, red, blue)").unwrap();
1
        if let StyleBackgroundContent::RadialGradient(grad) = rg {
1
            assert_eq!(grad.shape, Shape::Ellipse);
1
            assert_eq!(grad.stops.len(), 2);
        } else {
            panic!("Expected RadialGradient");
        }
1
    }
    #[test]
1
    fn test_radial_gradient_size_keywords() {
        // Test different size keywords
1
        let rg = parse_style_background_content("radial-gradient(circle closest-side, red, blue)")
1
            .unwrap();
1
        if let StyleBackgroundContent::RadialGradient(grad) = rg {
1
            assert_eq!(grad.shape, Shape::Circle);
1
            assert_eq!(grad.size, RadialGradientSize::ClosestSide);
        } else {
            panic!("Expected RadialGradient");
        }
1
    }
    #[test]
1
    fn test_radial_gradient_stop_positions() {
        // "radial-gradient(red 0%, blue 100%)"
1
        let rg = parse_style_background_content("radial-gradient(red 0%, blue 100%)").unwrap();
1
        if let StyleBackgroundContent::RadialGradient(grad) = rg {
1
            assert_eq!(grad.stops.len(), 2);
1
            assert!((grad.stops.as_ref()[0].offset.normalized() - 0.0).abs() < 0.001);
1
            assert!((grad.stops.as_ref()[1].offset.normalized() - 1.0).abs() < 0.001);
        } else {
            panic!("Expected RadialGradient");
        }
1
    }
    #[test]
1
    fn test_repeating_radial_gradient() {
1
        let rg = parse_style_background_content("repeating-radial-gradient(circle, red, blue 20%)")
1
            .unwrap();
1
        if let StyleBackgroundContent::RadialGradient(grad) = rg {
1
            assert_eq!(grad.extend_mode, ExtendMode::Repeat);
1
            assert_eq!(grad.shape, Shape::Circle);
        } else {
            panic!("Expected RadialGradient");
        }
1
    }
    #[test]
1
    fn test_conic_gradient_angle() {
        // "conic-gradient(from 45deg, red, blue)"
1
        let cg = parse_style_background_content("conic-gradient(from 45deg, red, blue)").unwrap();
1
        if let StyleBackgroundContent::ConicGradient(grad) = cg {
1
            assert_eq!(grad.angle, AngleValue::deg(45.0));
1
            assert_eq!(grad.stops.len(), 2);
        } else {
            panic!("Expected ConicGradient");
        }
1
    }
    #[test]
1
    fn test_conic_gradient_default() {
        // "conic-gradient(red, blue)" - no angle specified
1
        let cg = parse_style_background_content("conic-gradient(red, blue)").unwrap();
1
        if let StyleBackgroundContent::ConicGradient(grad) = cg {
1
            assert_eq!(grad.stops.len(), 2);
            // First stop defaults to 0deg
1
            assert!(
1
                (grad.stops.as_ref()[0].angle.to_degrees_raw() - 0.0).abs() < 0.001,
                "First stop should be 0deg, got {}",
                grad.stops.as_ref()[0].angle.to_degrees_raw()
            );
            // Last stop defaults to 360deg (use to_degrees_raw to preserve 360)
1
            assert!(
1
                (grad.stops.as_ref()[1].angle.to_degrees_raw() - 360.0).abs() < 0.001,
                "Last stop should be 360deg, got {}",
                grad.stops.as_ref()[1].angle.to_degrees_raw()
            );
        } else {
            panic!("Expected ConicGradient");
        }
1
    }
    #[test]
1
    fn test_conic_gradient_with_positions() {
        // "conic-gradient(red 0deg, blue 180deg, green 360deg)"
1
        let cg =
1
            parse_style_background_content("conic-gradient(red 0deg, blue 180deg, green 360deg)")
1
                .unwrap();
1
        if let StyleBackgroundContent::ConicGradient(grad) = cg {
1
            assert_eq!(grad.stops.len(), 3);
            // Use to_degrees_raw() to preserve 360deg
1
            assert!(
1
                (grad.stops.as_ref()[0].angle.to_degrees_raw() - 0.0).abs() < 0.001,
                "First stop should be 0deg, got {}",
                grad.stops.as_ref()[0].angle.to_degrees_raw()
            );
1
            assert!(
1
                (grad.stops.as_ref()[1].angle.to_degrees_raw() - 180.0).abs() < 0.001,
                "Second stop should be 180deg, got {}",
                grad.stops.as_ref()[1].angle.to_degrees_raw()
            );
1
            assert!(
1
                (grad.stops.as_ref()[2].angle.to_degrees_raw() - 360.0).abs() < 0.001,
                "Last stop should be 360deg, got {}",
                grad.stops.as_ref()[2].angle.to_degrees_raw()
            );
        } else {
            panic!("Expected ConicGradient");
        }
1
    }
    #[test]
1
    fn test_repeating_conic_gradient() {
1
        let cg =
1
            parse_style_background_content("repeating-conic-gradient(red, blue 30deg)").unwrap();
1
        if let StyleBackgroundContent::ConicGradient(grad) = cg {
1
            assert_eq!(grad.extend_mode, ExtendMode::Repeat);
        } else {
            panic!("Expected ConicGradient");
        }
1
    }
    #[test]
1
    fn test_gradient_with_rgba_color() {
        // Test parsing gradient with rgba color (contains spaces)
1
        let lg =
1
            parse_style_background_content("linear-gradient(rgba(255,0,0,0.5), blue)").unwrap();
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
1
            assert_eq!(grad.stops.len(), 2);
            // First color should have alpha of ~128 (0.5 * 255, may be 127 or 128 due to rounding)
1
            let first_color = grad.stops.as_ref()[0].color.to_color_u_default();
1
            assert!(first_color.a >= 127 && first_color.a <= 128);
        } else {
            panic!("Expected LinearGradient");
        }
1
    }
    #[test]
1
    fn test_gradient_with_rgba_and_position() {
        // Test parsing "rgba(0,0,0,0.5) 50%"
1
        let lg =
1
            parse_style_background_content("linear-gradient(rgba(0,0,0,0.5) 50%, white)").unwrap();
1
        if let StyleBackgroundContent::LinearGradient(grad) = lg {
1
            assert_eq!(grad.stops.len(), 2);
1
            assert!((grad.stops.as_ref()[0].offset.normalized() - 0.5).abs() < 0.001);
        } else {
            panic!("Expected LinearGradient");
        }
1
    }
    #[test]
1
    fn test_gradient_resolves_system_color_stop() {
        // A `system:accent` stop should round-trip through the parser as a
        // System variant and resolve against a populated `SystemColors` to
        // the live accent color, falling back to the supplied default when
        // the key is unset.
        use crate::{props::basic::color::ColorOrSystem, system::SystemColors};
1
        let lg = parse_style_background_content("linear-gradient(red, system:accent)").unwrap();
1
        let StyleBackgroundContent::LinearGradient(grad) = lg else {
            panic!("Expected LinearGradient");
        };
1
        let stops = grad.stops.as_ref();
1
        assert_eq!(stops.len(), 2);
1
        let accent_stop = &stops[1];
1
        assert!(matches!(accent_stop.color, ColorOrSystem::System(_)));
1
        let populated = SystemColors {
1
            accent: crate::props::basic::color::OptionColorU::Some(ColorU::new_rgb(0, 122, 255)),
1
            ..SystemColors::default()
1
        };
1
        let resolved = accent_stop.resolve(&populated, ColorU::TRANSPARENT);
1
        assert_eq!(resolved, ColorU::new_rgb(0, 122, 255));
1
        let empty = SystemColors::default();
1
        let fallback = accent_stop.resolve(&empty, ColorU::TRANSPARENT);
1
        assert_eq!(fallback, ColorU::TRANSPARENT);
1
    }
}