1
//! CSS properties for styling scrollbars.
2

            
3
use alloc::string::{String, ToString};
4

            
5
use crate::{
6
    corety::AzString,
7
    props::{
8
        basic::color::{parse_css_color, ColorU, CssColorParseError, CssColorParseErrorOwned},
9
        formatter::PrintAsCssValue,
10
        layout::{
11
            dimensions::LayoutWidth,
12
            spacing::{LayoutPaddingLeft, LayoutPaddingRight},
13
        },
14
        style::background::StyleBackgroundContent,
15
    },
16
};
17

            
18
// ============================================================================
19
// CSS Standard Scroll Behavior Properties
20
// ============================================================================
21

            
22
/// CSS `scroll-behavior` property - controls smooth scrolling
23
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior>
24
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
25
#[repr(C)]
26
pub enum ScrollBehavior {
27
    /// Scrolling jumps instantly to the final position
28
    #[default]
29
    Auto,
30
    /// Scrolling animates smoothly to the final position
31
    Smooth,
32
}
33

            
34
impl PrintAsCssValue for ScrollBehavior {
35
2
    fn print_as_css_value(&self) -> String {
36
2
        match self {
37
1
            Self::Auto => "auto".to_string(),
38
1
            Self::Smooth => "smooth".to_string(),
39
        }
40
2
    }
41
}
42

            
43
/// CSS `overscroll-behavior` property - controls overscroll effects
44
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior>
45
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
46
#[repr(C)]
47
pub enum OverscrollBehavior {
48
    /// Default scroll overflow behavior (bounce/glow effects, scroll chaining)
49
    #[default]
50
    Auto,
51
    /// Prevents scroll chaining to parent elements, but allows local overscroll effects
52
    Contain,
53
    /// No scroll chaining and no overscroll effects (hard stop at boundaries)
54
    None,
55
}
56

            
57
impl PrintAsCssValue for OverscrollBehavior {
58
3
    fn print_as_css_value(&self) -> String {
59
3
        match self {
60
1
            Self::Auto => "auto".to_string(),
61
1
            Self::Contain => "contain".to_string(),
62
1
            Self::None => "none".to_string(),
63
        }
64
3
    }
65
}
66

            
67
// ============================================================================
68
// Extended Scroll Configuration (Azul-specific)
69
// ============================================================================
70

            
71
/// Scroll physics configuration for momentum scrolling
72
///
73
/// This controls how scrolling feels - the "weight" and "friction" of the scroll.
74
/// Different platforms have different scroll physics (iOS vs Android vs Windows).
75
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
76
#[repr(C)]
77
pub struct ScrollPhysics {
78
    /// Smooth scroll animation duration in milliseconds (default: 300ms)
79
    /// Only used when scroll-behavior: smooth
80
    pub smooth_scroll_duration_ms: u32,
81

            
82
    /// Deceleration rate for momentum scrolling (0.0 = instant stop, 1.0 = never stops)
83
    /// Typical values: 0.95 (fast deceleration) to 0.998 (slow, iOS-like)
84
    /// Default: 0.95
85
    pub deceleration_rate: f32,
86

            
87
    /// Minimum velocity threshold to start momentum scrolling (pixels/second)
88
    /// Below this, scrolling stops immediately. Default: 50.0
89
    pub min_velocity_threshold: f32,
90

            
91
    /// Maximum scroll velocity (pixels/second). Default: 8000.0
92
    pub max_velocity: f32,
93

            
94
    /// Scroll wheel multiplier. Default: 1.0
95
    /// Values > 1.0 make scrolling faster, < 1.0 slower
96
    pub wheel_multiplier: f32,
97

            
98
    /// Whether to invert scroll direction (natural scrolling). Default: false
99
    pub invert_direction: bool,
100

            
101
    /// Overscroll elasticity (0.0 = no bounce, 1.0 = full bounce like iOS)
102
    /// Only applies when overscroll-behavior: auto. Default: 0.0 (no bounce)
103
    pub overscroll_elasticity: f32,
104

            
105
    /// Maximum overscroll distance in pixels before rubber-banding stops
106
    /// Default: 100.0
107
    pub max_overscroll_distance: f32,
108

            
109
    /// Bounce-back duration when releasing overscroll (milliseconds)
110
    /// Default: 400
111
    pub bounce_back_duration_ms: u32,
112

            
113
    /// Timer tick interval in milliseconds for the scroll physics timer.
114
    /// Should match the monitor refresh rate (e.g. 16ms for 60Hz, 8ms for 120Hz).
115
    /// Default: 16 (60 Hz)
116
    pub timer_interval_ms: u32,
117

            
118
    /// Spring duration for target-seeking animated scrolls
119
    /// (`scroll_to_animated`) that originate from a MOUSE WHEEL. Wheel
120
    /// steps animated with the trackpad's long bounce constant feel
121
    /// jarring - a discrete click wants a short, snappy glide. Other
122
    /// devices use `bounce_back_duration_ms`. Default: 120.
123
    pub wheel_animate_bounce_ms: u32,
124
}
125

            
126
impl Default for ScrollPhysics {
127
66418
    fn default() -> Self {
128
66418
        Self {
129
66418
            smooth_scroll_duration_ms: 300,
130
66418
            deceleration_rate: 0.95,
131
66418
            min_velocity_threshold: 50.0,
132
66418
            max_velocity: 8000.0,
133
66418
            wheel_multiplier: 1.0,
134
66418
            invert_direction: false,
135
66418
            overscroll_elasticity: 0.0, // No bounce by default (Windows-like)
136
66418
            max_overscroll_distance: 100.0,
137
66418
            bounce_back_duration_ms: 400,
138
66418
            timer_interval_ms: 16,
139
66418
            wheel_animate_bounce_ms: 120,
140
66418
        }
141
66418
    }
142
}
143

            
144
impl ScrollPhysics {
145
    /// iOS-like scroll physics with momentum and bounce
146
    #[must_use]
147
79
    pub const fn ios() -> Self {
148
79
        Self {
149
79
            smooth_scroll_duration_ms: 300,
150
79
            deceleration_rate: 0.998,
151
79
            min_velocity_threshold: 20.0,
152
79
            max_velocity: 8000.0,
153
79
            wheel_multiplier: 1.0,
154
79
            invert_direction: true, // Natural scrolling
155
79
            overscroll_elasticity: 0.5,
156
79
            max_overscroll_distance: 120.0,
157
79
            bounce_back_duration_ms: 500,
158
79
            timer_interval_ms: 16,
159
79
            wheel_animate_bounce_ms: 120,
160
79
        }
161
79
    }
162

            
163
    /// macOS-like scroll physics
164
    #[must_use]
165
224
    pub const fn macos() -> Self {
166
224
        Self {
167
224
            smooth_scroll_duration_ms: 250,
168
224
            deceleration_rate: 0.997,
169
224
            min_velocity_threshold: 30.0,
170
224
            max_velocity: 6000.0,
171
224
            wheel_multiplier: 1.0,
172
224
            invert_direction: true, // Natural scrolling by default
173
224
            overscroll_elasticity: 0.3,
174
224
            max_overscroll_distance: 80.0,
175
224
            bounce_back_duration_ms: 400,
176
224
            timer_interval_ms: 16,
177
224
            wheel_animate_bounce_ms: 120,
178
224
        }
179
224
    }
180

            
181
    /// Windows-like scroll physics (no momentum, no bounce)
182
    #[must_use]
183
129
    pub const fn windows() -> Self {
184
129
        Self {
185
129
            smooth_scroll_duration_ms: 200,
186
129
            deceleration_rate: 0.9,
187
129
            min_velocity_threshold: 100.0,
188
129
            max_velocity: 4000.0,
189
129
            wheel_multiplier: 1.0,
190
129
            invert_direction: false,
191
129
            overscroll_elasticity: 0.0,
192
129
            max_overscroll_distance: 0.0,
193
129
            bounce_back_duration_ms: 200,
194
129
            timer_interval_ms: 16,
195
129
            wheel_animate_bounce_ms: 120,
196
129
        }
197
129
    }
198

            
199
    /// Android-like scroll physics
200
    #[must_use]
201
43
    pub const fn android() -> Self {
202
43
        Self {
203
43
            smooth_scroll_duration_ms: 250,
204
43
            deceleration_rate: 0.996,
205
43
            min_velocity_threshold: 40.0,
206
43
            max_velocity: 8000.0,
207
43
            wheel_multiplier: 1.0,
208
43
            invert_direction: false,
209
43
            overscroll_elasticity: 0.2, // Subtle glow effect
210
43
            max_overscroll_distance: 60.0,
211
43
            bounce_back_duration_ms: 300,
212
43
            timer_interval_ms: 16,
213
43
            wheel_animate_bounce_ms: 120,
214
43
        }
215
43
    }
216
}
217

            
218
impl_option!(
219
    ScrollPhysics,
220
    OptionScrollPhysics,
221
    [Debug, Copy, Clone, PartialEq, PartialOrd]
222
);
223

            
224
// ============================================================================
225
// Scrollbar Visibility Mode (CSS: -azul-scrollbar-visibility)
226
// ============================================================================
227

            
228
/// Controls when the scrollbar is displayed.
229
///
230
/// This is a per-element CSS property (`-azul-scrollbar-visibility`) that
231
/// determines the scrollbar presentation style. It interacts with the
232
/// OS-level `ScrollbarPreferences.visibility` (from System Preferences)
233
/// when set to `Auto`.
234
///
235
/// - `Always`: Classic, always-visible scrollbar (Chrome/Windows/Linux default). Scrollbar reserves
236
///   layout space.
237
/// - `WhenScrolling`: Overlay scrollbar that fades in on scroll activity and fades out after a
238
///   delay. Does not reserve layout space.
239
/// - `Auto`: Use the OS preference. On macOS this typically means `WhenScrolling`, on Windows/Linux
240
///   this typically means `Always`.
241
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
242
#[repr(C)]
243
pub enum ScrollbarVisibilityMode {
244
    /// Scrollbar is always visible (Chrome/Windows/Linux default).
245
    /// Reserves layout space.
246
    #[default]
247
    Always,
248
    /// Scrollbar appears on scroll and fades out after inactivity.
249
    /// Does not reserve layout space (overlay).
250
    WhenScrolling,
251
    /// Use the OS-level scrollbar preference.
252
    Auto,
253
}
254

            
255
impl PrintAsCssValue for ScrollbarVisibilityMode {
256
6
    fn print_as_css_value(&self) -> String {
257
6
        match self {
258
2
            Self::Always => "always".to_string(),
259
2
            Self::WhenScrolling => "when-scrolling".to_string(),
260
2
            Self::Auto => "auto".to_string(),
261
        }
262
6
    }
263
}
264

            
265
// ============================================================================
266
// Scrollbar Fade Delay (CSS: -azul-scrollbar-fade-delay)
267
// ============================================================================
268

            
269
/// Time in milliseconds before the overlay scrollbar starts fading out.
270
///
271
/// A value of 0 means the scrollbar never fades (always visible).
272
/// Typical values: 500ms (macOS), 0ms (Windows).
273
///
274
/// CSS syntax: `-azul-scrollbar-fade-delay: 500ms;` or `-azul-scrollbar-fade-delay: 0;`
275
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
276
#[repr(C)]
277
pub struct ScrollbarFadeDelay {
278
    /// Delay in milliseconds
279
    pub ms: u32,
280
}
281

            
282
impl ScrollbarFadeDelay {
283
    #[must_use]
284
366
    pub const fn new(ms: u32) -> Self {
285
366
        Self { ms }
286
366
    }
287
    pub const ZERO: Self = Self { ms: 0 };
288
}
289

            
290
impl PrintAsCssValue for ScrollbarFadeDelay {
291
16
    fn print_as_css_value(&self) -> String {
292
16
        if self.ms == 0 {
293
2
            "0".to_string()
294
        } else {
295
14
            format!("{}ms", self.ms)
296
        }
297
16
    }
298
}
299

            
300
// ============================================================================
301
// Scrollbar Fade Duration (CSS: -azul-scrollbar-fade-duration)
302
// ============================================================================
303

            
304
/// Duration in milliseconds of the scrollbar fade-out animation.
305
///
306
/// A value of 0 means instant disappearance (no animation).
307
/// Typical values: 200ms (macOS), 0ms (Windows).
308
///
309
/// CSS syntax: `-azul-scrollbar-fade-duration: 200ms;` or `-azul-scrollbar-fade-duration: 0;`
310
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
311
#[repr(C)]
312
pub struct ScrollbarFadeDuration {
313
    /// Duration in milliseconds
314
    pub ms: u32,
315
}
316

            
317
impl ScrollbarFadeDuration {
318
    #[must_use]
319
293
    pub const fn new(ms: u32) -> Self {
320
293
        Self { ms }
321
293
    }
322
    pub const ZERO: Self = Self { ms: 0 };
323
}
324

            
325
impl PrintAsCssValue for ScrollbarFadeDuration {
326
14
    fn print_as_css_value(&self) -> String {
327
14
        if self.ms == 0 {
328
2
            "0".to_string()
329
        } else {
330
12
            format!("{}ms", self.ms)
331
        }
332
14
    }
333
}
334

            
335
// ============================================================================
336
// Per-node Overflow Scrolling Mode (CSS: -azul-overflow-scrolling)
337
// ============================================================================
338

            
339
/// Controls per-node rubber-banding / momentum scrolling behavior.
340
///
341
/// Analogous to `-webkit-overflow-scrolling` on iOS Safari.
342
///
343
/// - `Auto`: Use the global `ScrollPhysics` from `SystemStyle`. On platforms with
344
///   `overscroll_elasticity == 0.0` (e.g. Windows), this means no rubber-banding.
345
/// - `Touch`: Force momentum scrolling with rubber-banding on this node, regardless of the global
346
///   `ScrollPhysics` setting. Uses iOS-like elasticity if the global elasticity is zero.
347
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
348
#[repr(C)]
349
pub enum OverflowScrolling {
350
    /// Use the global scroll physics (platform default). No rubber-banding on Windows.
351
    #[default]
352
    Auto,
353
    /// Force rubber-banding / momentum scrolling on this node (like iOS/macOS).
354
    Touch,
355
}
356

            
357
impl PrintAsCssValue for OverflowScrolling {
358
2
    fn print_as_css_value(&self) -> String {
359
2
        match self {
360
1
            Self::Auto => "auto".to_string(),
361
1
            Self::Touch => "touch".to_string(),
362
        }
363
2
    }
364
}
365

            
366
// ============================================================================
367
// Standard Properties
368
// ============================================================================
369

            
370
/// Represents the standard `scrollbar-width` property.
371
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
372
#[repr(C)]
373
#[derive(Default)]
374
pub enum LayoutScrollbarWidth {
375
    #[default]
376
    Auto,
377
    Thin,
378
    None,
379
}
380

            
381
impl PrintAsCssValue for LayoutScrollbarWidth {
382
6
    fn print_as_css_value(&self) -> String {
383
6
        match self {
384
2
            Self::Auto => "auto".to_string(),
385
2
            Self::Thin => "thin".to_string(),
386
2
            Self::None => "none".to_string(),
387
        }
388
6
    }
389
}
390

            
391
/// Wrapper struct for custom scrollbar colors (thumb and track)
392
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
393
#[repr(C)]
394
pub struct ScrollbarColorCustom {
395
    pub thumb: ColorU,
396
    pub track: ColorU,
397
}
398

            
399
/// Represents the standard `scrollbar-color` property.
400
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
401
#[repr(C, u8)]
402
#[derive(Default)]
403
pub enum StyleScrollbarColor {
404
    #[default]
405
    Auto,
406
    Custom(ScrollbarColorCustom),
407
}
408

            
409
impl PrintAsCssValue for StyleScrollbarColor {
410
7
    fn print_as_css_value(&self) -> String {
411
7
        match self {
412
2
            Self::Auto => "auto".to_string(),
413
5
            Self::Custom(c) => format!("{} {}", c.thumb.to_hash(), c.track.to_hash()),
414
        }
415
7
    }
416
}
417

            
418
// -- -webkit-prefixed Properties --
419

            
420
/// Holds info necessary for layouting / styling -webkit-scrollbar properties.
421
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
422
#[repr(C)]
423
pub struct ScrollbarInfo {
424
    /// Total width (or height for vertical scrollbars) of the scrollbar in pixels
425
    pub width: LayoutWidth,
426
    /// Padding of the scrollbar tracker, in pixels. The inner bar is `width - padding` pixels
427
    /// wide.
428
    pub padding_left: LayoutPaddingLeft,
429
    /// Padding of the scrollbar (right)
430
    pub padding_right: LayoutPaddingRight,
431
    /// Style of the scrollbar background
432
    /// (`-webkit-scrollbar` / `-webkit-scrollbar-track` / `-webkit-scrollbar-track-piece`
433
    /// combined)
434
    pub track: StyleBackgroundContent,
435
    /// Style of the scrollbar thumbs (the "up" / "down" arrows), (`-webkit-scrollbar-thumb`)
436
    pub thumb: StyleBackgroundContent,
437
    /// Styles the directional buttons on the scrollbar (`-webkit-scrollbar-button`)
438
    pub button: StyleBackgroundContent,
439
    /// If two scrollbars are present, addresses the (usually) bottom corner
440
    /// of the scrollable element, where two scrollbars might meet (`-webkit-scrollbar-corner`)
441
    pub corner: StyleBackgroundContent,
442
    /// Addresses the draggable resizing handle that appears above the
443
    /// `corner` at the bottom corner of some elements (`-webkit-resizer`)
444
    pub resizer: StyleBackgroundContent,
445
    /// Whether to clip the scrollbar to the container's border-radius.
446
    /// When true, if the container has rounded corners, the scrollbar will be
447
    /// clipped to those rounded corners instead of having rectangular edges.
448
    /// Default is false for classic scrollbars, true for overlay scrollbars.
449
    pub clip_to_container_border: bool,
450
    /// Scroll behavior for this scrollbar's container (auto or smooth)
451
    pub scroll_behavior: ScrollBehavior,
452
    /// Overscroll behavior for the X axis
453
    pub overscroll_behavior_x: OverscrollBehavior,
454
    /// Overscroll behavior for the Y axis  
455
    pub overscroll_behavior_y: OverscrollBehavior,
456
    /// Per-node overflow scrolling mode (`-azul-overflow-scrolling: auto | touch`)
457
    /// `Touch` forces rubber-banding on this node even when the global physics has no bounce.
458
    pub overflow_scrolling: OverflowScrolling,
459
}
460

            
461
impl Default for ScrollbarInfo {
462
14
    fn default() -> Self {
463
14
        SCROLLBAR_CLASSIC_LIGHT
464
14
    }
465
}
466

            
467
impl PrintAsCssValue for ScrollbarInfo {
468
3
    fn print_as_css_value(&self) -> String {
469
        // This is a custom format, not standard CSS
470
3
        format!(
471
3
            "width: {}; padding-left: {}; padding-right: {}; track: {}; thumb: {}; button: {}; \
472
3
             corner: {}; resizer: {}",
473
3
            self.width.print_as_css_value(),
474
3
            self.padding_left.print_as_css_value(),
475
3
            self.padding_right.print_as_css_value(),
476
3
            self.track.print_as_css_value(),
477
3
            self.thumb.print_as_css_value(),
478
3
            self.button.print_as_css_value(),
479
3
            self.corner.print_as_css_value(),
480
3
            self.resizer.print_as_css_value(),
481
        )
482
3
    }
483
}
484

            
485
/// Scrollbar style for both horizontal and vertical scrollbars.
486
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
487
#[repr(C)]
488
pub struct ScrollbarStyle {
489
    /// Horizontal scrollbar style, if any
490
    pub horizontal: ScrollbarInfo,
491
    /// Vertical scrollbar style, if any
492
    pub vertical: ScrollbarInfo,
493
}
494

            
495
impl PrintAsCssValue for ScrollbarStyle {
496
1
    fn print_as_css_value(&self) -> String {
497
        // This is a custom format, not standard CSS
498
1
        format!(
499
1
            "horz({}), vert({})",
500
1
            self.horizontal.print_as_css_value(),
501
1
            self.vertical.print_as_css_value()
502
        )
503
1
    }
504
}
505

            
506
// Formatting to Rust code
507
impl crate::codegen::format::FormatAsRustCode for ScrollbarStyle {
508
3
    fn format_as_rust_code(&self, tabs: usize) -> String {
509
3
        let t = String::from("    ").repeat(tabs);
510
3
        let t1 = String::from("    ").repeat(tabs + 1);
511
3
        format!(
512
3
            "ScrollbarStyle {{\r\n{}horizontal: {},\r\n{}vertical: {},\r\n{}}}",
513
            t1,
514
3
            crate::codegen::format::format_scrollbar_info(&self.horizontal, tabs + 1),
515
            t1,
516
3
            crate::codegen::format::format_scrollbar_info(&self.vertical, tabs + 1),
517
            t,
518
        )
519
3
    }
520
}
521

            
522
impl crate::codegen::format::FormatAsRustCode for OverscrollBehavior {
523
    fn format_as_rust_code(&self, _tabs: usize) -> String {
524
        match self {
525
            Self::Auto => String::from("OverscrollBehavior::Auto"),
526
            Self::Contain => String::from("OverscrollBehavior::Contain"),
527
            Self::None => String::from("OverscrollBehavior::None"),
528
        }
529
    }
530
}
531

            
532
impl crate::codegen::format::FormatAsRustCode for LayoutScrollbarWidth {
533
2
    fn format_as_rust_code(&self, _tabs: usize) -> String {
534
2
        match self {
535
            Self::Auto => String::from("LayoutScrollbarWidth::Auto"),
536
1
            Self::Thin => String::from("LayoutScrollbarWidth::Thin"),
537
1
            Self::None => String::from("LayoutScrollbarWidth::None"),
538
        }
539
2
    }
540
}
541

            
542
impl crate::codegen::format::FormatAsRustCode for StyleScrollbarColor {
543
2
    fn format_as_rust_code(&self, _tabs: usize) -> String {
544
2
        match self {
545
1
            Self::Auto => String::from("StyleScrollbarColor::Auto"),
546
1
            Self::Custom(c) => format!(
547
1
                "StyleScrollbarColor::Custom(ScrollbarColorCustom {{ thumb: {}, track: {} }})",
548
1
                crate::codegen::format::format_color_value(&c.thumb),
549
1
                crate::codegen::format::format_color_value(&c.track)
550
            ),
551
        }
552
2
    }
553
}
554

            
555
impl crate::codegen::format::FormatAsRustCode for ScrollbarVisibilityMode {
556
1
    fn format_as_rust_code(&self, _tabs: usize) -> String {
557
1
        match self {
558
            Self::Always => String::from("ScrollbarVisibilityMode::Always"),
559
1
            Self::WhenScrolling => String::from("ScrollbarVisibilityMode::WhenScrolling"),
560
            Self::Auto => String::from("ScrollbarVisibilityMode::Auto"),
561
        }
562
1
    }
563
}
564

            
565
impl crate::codegen::format::FormatAsRustCode for ScrollbarFadeDelay {
566
2
    fn format_as_rust_code(&self, _tabs: usize) -> String {
567
2
        format!("ScrollbarFadeDelay::new({})", self.ms)
568
2
    }
569
}
570

            
571
impl crate::codegen::format::FormatAsRustCode for ScrollbarFadeDuration {
572
1
    fn format_as_rust_code(&self, _tabs: usize) -> String {
573
1
        format!("ScrollbarFadeDuration::new({})", self.ms)
574
1
    }
575
}
576

            
577
// --- Final Computed Style ---
578

            
579
/// The final, resolved style for a scrollbar, after considering both
580
/// standard and -webkit- properties. This struct is intended for use by the layout engine.
581
#[derive(Debug, Clone, PartialEq)]
582
pub struct ComputedScrollbarStyle {
583
    /// The width of the scrollbar. `None` signifies `scrollbar-width: none`.
584
    pub width: Option<LayoutWidth>,
585
    /// The color of the scrollbar thumb. `None` means use UA default.
586
    pub thumb_color: Option<ColorU>,
587
    /// The color of the scrollbar track. `None` means use UA default.
588
    pub track_color: Option<ColorU>,
589
    /// How wide the HANDLE is, in logical px — which is not the same thing as
590
    /// how wide the scrollbar is.
591
    ///
592
    /// Breeze draws a 6px handle centred in a 21px groove; Adwaita and macOS
593
    /// also inset theirs. Deriving the handle from the groove instead produced
594
    /// a handle that fills the whole track, which is why an azul scrollbar
595
    /// read as a fat pill next to a native one. `None` = fill the groove
596
    /// (the previous behaviour).
597
    pub handle_width: Option<f32>,
598
    /// The handle's corner radius in logical px. `None` = half the handle
599
    /// width (a capsule), which is right for Breeze and Adwaita but wrong for
600
    /// the square handles of older/classic styles — so it is a value the
601
    /// platform gets to state rather than one the renderer assumes.
602
    pub handle_radius: Option<f32>,
603
}
604

            
605
impl Default for ComputedScrollbarStyle {
606
1
    fn default() -> Self {
607
1
        let default_info = ScrollbarInfo::default();
608
        Self {
609
1
            width: Some(default_info.width), // Default width from UA/platform
610
1
            handle_width: None,
611
1
            handle_radius: None,
612
1
            thumb_color: match default_info.thumb {
613
1
                StyleBackgroundContent::Color(c) => Some(c),
614
                _ => None,
615
            },
616
1
            track_color: match default_info.track {
617
1
                StyleBackgroundContent::Color(c) => Some(c),
618
                _ => None,
619
            },
620
        }
621
1
    }
622
}
623

            
624
// --- Default Style Constants ---
625

            
626
/// A classic light-themed scrollbar, similar to older Windows versions.
627
pub const SCROLLBAR_CLASSIC_LIGHT: ScrollbarInfo = ScrollbarInfo {
628
    width: LayoutWidth::Px(crate::props::basic::pixel::PixelValue::const_px(17)),
629
    padding_left: LayoutPaddingLeft {
630
        inner: crate::props::basic::pixel::PixelValue::const_px(2),
631
    },
632
    padding_right: LayoutPaddingRight {
633
        inner: crate::props::basic::pixel::PixelValue::const_px(2),
634
    },
635
    track: StyleBackgroundContent::Color(ColorU {
636
        r: 241,
637
        g: 241,
638
        b: 241,
639
        a: 255,
640
    }),
641
    thumb: StyleBackgroundContent::Color(ColorU {
642
        r: 193,
643
        g: 193,
644
        b: 193,
645
        a: 255,
646
    }),
647
    button: StyleBackgroundContent::Color(ColorU {
648
        r: 163,
649
        g: 163,
650
        b: 163,
651
        a: 255,
652
    }),
653
    corner: StyleBackgroundContent::Color(ColorU {
654
        r: 241,
655
        g: 241,
656
        b: 241,
657
        a: 255,
658
    }),
659
    resizer: StyleBackgroundContent::Color(ColorU {
660
        r: 241,
661
        g: 241,
662
        b: 241,
663
        a: 255,
664
    }),
665
    clip_to_container_border: false,
666
    scroll_behavior: ScrollBehavior::Auto,
667
    overscroll_behavior_x: OverscrollBehavior::Auto,
668
    overscroll_behavior_y: OverscrollBehavior::Auto,
669
    overflow_scrolling: OverflowScrolling::Auto,
670
};
671

            
672
/// A classic dark-themed scrollbar.
673
pub const SCROLLBAR_CLASSIC_DARK: ScrollbarInfo = ScrollbarInfo {
674
    width: LayoutWidth::Px(crate::props::basic::pixel::PixelValue::const_px(17)),
675
    padding_left: LayoutPaddingLeft {
676
        inner: crate::props::basic::pixel::PixelValue::const_px(2),
677
    },
678
    padding_right: LayoutPaddingRight {
679
        inner: crate::props::basic::pixel::PixelValue::const_px(2),
680
    },
681
    track: StyleBackgroundContent::Color(ColorU {
682
        r: 45,
683
        g: 45,
684
        b: 45,
685
        a: 255,
686
    }),
687
    thumb: StyleBackgroundContent::Color(ColorU {
688
        r: 100,
689
        g: 100,
690
        b: 100,
691
        a: 255,
692
    }),
693
    button: StyleBackgroundContent::Color(ColorU {
694
        r: 120,
695
        g: 120,
696
        b: 120,
697
        a: 255,
698
    }),
699
    corner: StyleBackgroundContent::Color(ColorU {
700
        r: 45,
701
        g: 45,
702
        b: 45,
703
        a: 255,
704
    }),
705
    resizer: StyleBackgroundContent::Color(ColorU {
706
        r: 45,
707
        g: 45,
708
        b: 45,
709
        a: 255,
710
    }),
711
    clip_to_container_border: false,
712
    scroll_behavior: ScrollBehavior::Auto,
713
    overscroll_behavior_x: OverscrollBehavior::Auto,
714
    overscroll_behavior_y: OverscrollBehavior::Auto,
715
    overflow_scrolling: OverflowScrolling::Auto,
716
};
717

            
718
/// A modern, thin, overlay scrollbar inspired by macOS (Light Theme).
719
pub const SCROLLBAR_MACOS_LIGHT: ScrollbarInfo = ScrollbarInfo {
720
    width: LayoutWidth::Px(crate::props::basic::pixel::PixelValue::const_px(8)),
721
    padding_left: LayoutPaddingLeft {
722
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
723
    },
724
    padding_right: LayoutPaddingRight {
725
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
726
    },
727
    track: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
728
    thumb: StyleBackgroundContent::Color(ColorU {
729
        r: 0,
730
        g: 0,
731
        b: 0,
732
        a: 100,
733
    }), // semi-transparent black
734
    button: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
735
    corner: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
736
    resizer: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
737
    clip_to_container_border: true, // Overlay scrollbars should clip to rounded borders
738
    scroll_behavior: ScrollBehavior::Smooth,
739
    overscroll_behavior_x: OverscrollBehavior::Auto,
740
    overscroll_behavior_y: OverscrollBehavior::Auto,
741
    overflow_scrolling: OverflowScrolling::Auto,
742
};
743

            
744
/// A modern, thin, overlay scrollbar inspired by macOS (Dark Theme).
745
pub const SCROLLBAR_MACOS_DARK: ScrollbarInfo = ScrollbarInfo {
746
    width: LayoutWidth::Px(crate::props::basic::pixel::PixelValue::const_px(8)),
747
    padding_left: LayoutPaddingLeft {
748
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
749
    },
750
    padding_right: LayoutPaddingRight {
751
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
752
    },
753
    track: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
754
    thumb: StyleBackgroundContent::Color(ColorU {
755
        r: 255,
756
        g: 255,
757
        b: 255,
758
        a: 100,
759
    }), // semi-transparent white
760
    button: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
761
    corner: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
762
    resizer: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
763
    clip_to_container_border: true, // Overlay scrollbars should clip to rounded borders
764
    scroll_behavior: ScrollBehavior::Smooth,
765
    overscroll_behavior_x: OverscrollBehavior::Auto,
766
    overscroll_behavior_y: OverscrollBehavior::Auto,
767
    overflow_scrolling: OverflowScrolling::Auto,
768
};
769

            
770
/// A modern scrollbar inspired by Windows 11 (Light Theme).
771
pub const SCROLLBAR_WINDOWS_LIGHT: ScrollbarInfo = ScrollbarInfo {
772
    width: LayoutWidth::Px(crate::props::basic::pixel::PixelValue::const_px(12)),
773
    padding_left: LayoutPaddingLeft {
774
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
775
    },
776
    padding_right: LayoutPaddingRight {
777
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
778
    },
779
    track: StyleBackgroundContent::Color(ColorU {
780
        r: 241,
781
        g: 241,
782
        b: 241,
783
        a: 255,
784
    }),
785
    thumb: StyleBackgroundContent::Color(ColorU {
786
        r: 130,
787
        g: 130,
788
        b: 130,
789
        a: 255,
790
    }),
791
    button: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
792
    corner: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
793
    resizer: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
794
    clip_to_container_border: false,
795
    scroll_behavior: ScrollBehavior::Auto,
796
    overscroll_behavior_x: OverscrollBehavior::None,
797
    overscroll_behavior_y: OverscrollBehavior::None,
798
    overflow_scrolling: OverflowScrolling::Auto,
799
};
800

            
801
/// A modern scrollbar inspired by Windows 11 (Dark Theme).
802
pub const SCROLLBAR_WINDOWS_DARK: ScrollbarInfo = ScrollbarInfo {
803
    width: LayoutWidth::Px(crate::props::basic::pixel::PixelValue::const_px(12)),
804
    padding_left: LayoutPaddingLeft {
805
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
806
    },
807
    padding_right: LayoutPaddingRight {
808
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
809
    },
810
    track: StyleBackgroundContent::Color(ColorU {
811
        r: 32,
812
        g: 32,
813
        b: 32,
814
        a: 255,
815
    }),
816
    thumb: StyleBackgroundContent::Color(ColorU {
817
        r: 110,
818
        g: 110,
819
        b: 110,
820
        a: 255,
821
    }),
822
    button: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
823
    corner: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
824
    resizer: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
825
    clip_to_container_border: false,
826
    scroll_behavior: ScrollBehavior::Auto,
827
    overscroll_behavior_x: OverscrollBehavior::None,
828
    overscroll_behavior_y: OverscrollBehavior::None,
829
    overflow_scrolling: OverflowScrolling::Auto,
830
};
831

            
832
/// A modern, thin, overlay scrollbar inspired by iOS (Light Theme).
833
pub const SCROLLBAR_IOS_LIGHT: ScrollbarInfo = ScrollbarInfo {
834
    width: LayoutWidth::Px(crate::props::basic::pixel::PixelValue::const_px(7)),
835
    padding_left: LayoutPaddingLeft {
836
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
837
    },
838
    padding_right: LayoutPaddingRight {
839
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
840
    },
841
    track: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
842
    thumb: StyleBackgroundContent::Color(ColorU {
843
        r: 0,
844
        g: 0,
845
        b: 0,
846
        a: 102,
847
    }), // rgba(0,0,0,0.4)
848
    button: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
849
    corner: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
850
    resizer: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
851
    clip_to_container_border: true, // Overlay scrollbars should clip to rounded borders
852
    scroll_behavior: ScrollBehavior::Smooth,
853
    overscroll_behavior_x: OverscrollBehavior::Auto,
854
    overscroll_behavior_y: OverscrollBehavior::Auto,
855
    overflow_scrolling: OverflowScrolling::Auto,
856
};
857

            
858
/// A modern, thin, overlay scrollbar inspired by iOS (Dark Theme).
859
pub const SCROLLBAR_IOS_DARK: ScrollbarInfo = ScrollbarInfo {
860
    width: LayoutWidth::Px(crate::props::basic::pixel::PixelValue::const_px(7)),
861
    padding_left: LayoutPaddingLeft {
862
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
863
    },
864
    padding_right: LayoutPaddingRight {
865
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
866
    },
867
    track: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
868
    thumb: StyleBackgroundContent::Color(ColorU {
869
        r: 255,
870
        g: 255,
871
        b: 255,
872
        a: 102,
873
    }), // rgba(255,255,255,0.4)
874
    button: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
875
    corner: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
876
    resizer: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
877
    clip_to_container_border: true, // Overlay scrollbars should clip to rounded borders
878
    scroll_behavior: ScrollBehavior::Smooth,
879
    overscroll_behavior_x: OverscrollBehavior::Auto,
880
    overscroll_behavior_y: OverscrollBehavior::Auto,
881
    overflow_scrolling: OverflowScrolling::Auto,
882
};
883

            
884
/// A modern, thin, overlay scrollbar inspired by Android (Light Theme).
885
pub const SCROLLBAR_ANDROID_LIGHT: ScrollbarInfo = ScrollbarInfo {
886
    width: LayoutWidth::Px(crate::props::basic::pixel::PixelValue::const_px(6)),
887
    padding_left: LayoutPaddingLeft {
888
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
889
    },
890
    padding_right: LayoutPaddingRight {
891
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
892
    },
893
    track: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
894
    thumb: StyleBackgroundContent::Color(ColorU {
895
        r: 0,
896
        g: 0,
897
        b: 0,
898
        a: 102,
899
    }), // rgba(0,0,0,0.4)
900
    button: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
901
    corner: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
902
    resizer: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
903
    clip_to_container_border: true, // Overlay scrollbars should clip to rounded borders
904
    scroll_behavior: ScrollBehavior::Smooth,
905
    overscroll_behavior_x: OverscrollBehavior::Contain,
906
    overscroll_behavior_y: OverscrollBehavior::Auto,
907
    overflow_scrolling: OverflowScrolling::Auto,
908
};
909

            
910
/// A modern, thin, overlay scrollbar inspired by Android (Dark Theme).
911
pub const SCROLLBAR_ANDROID_DARK: ScrollbarInfo = ScrollbarInfo {
912
    width: LayoutWidth::Px(crate::props::basic::pixel::PixelValue::const_px(6)),
913
    padding_left: LayoutPaddingLeft {
914
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
915
    },
916
    padding_right: LayoutPaddingRight {
917
        inner: crate::props::basic::pixel::PixelValue::const_px(0),
918
    },
919
    track: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
920
    thumb: StyleBackgroundContent::Color(ColorU {
921
        r: 255,
922
        g: 255,
923
        b: 255,
924
        a: 102,
925
    }), // rgba(255,255,255,0.4)
926
    button: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
927
    corner: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
928
    resizer: StyleBackgroundContent::Color(ColorU::TRANSPARENT),
929
    clip_to_container_border: true, // Overlay scrollbars should clip to rounded borders
930
    scroll_behavior: ScrollBehavior::Smooth,
931
    overscroll_behavior_x: OverscrollBehavior::Contain,
932
    overscroll_behavior_y: OverscrollBehavior::Auto,
933
    overflow_scrolling: OverflowScrolling::Auto,
934
};
935

            
936
// --- PARSERS ---
937

            
938
#[derive(Clone, PartialEq, Eq)]
939
pub enum OverscrollBehaviorParseError<'a> {
940
    InvalidValue(&'a str),
941
}
942
impl_debug_as_display!(OverscrollBehaviorParseError<'a>);
943
impl_display! { OverscrollBehaviorParseError<'a>, {
944
    InvalidValue(v) => format!("Invalid overscroll-behavior value: \"{}\"", v),
945
}}
946

            
947
#[derive(Debug, Clone, PartialEq, Eq)]
948
#[repr(C, u8)]
949
pub enum OverscrollBehaviorParseErrorOwned {
950
    InvalidValue(AzString),
951
}
952
impl OverscrollBehaviorParseError<'_> {
953
    #[must_use]
954
    pub fn to_contained(&self) -> OverscrollBehaviorParseErrorOwned {
955
        match self {
956
            Self::InvalidValue(s) => {
957
                OverscrollBehaviorParseErrorOwned::InvalidValue((*s).to_string().into())
958
            }
959
        }
960
    }
961
}
962
impl OverscrollBehaviorParseErrorOwned {
963
    #[must_use]
964
    pub fn to_shared(&self) -> OverscrollBehaviorParseError<'_> {
965
        match self {
966
            Self::InvalidValue(s) => OverscrollBehaviorParseError::InvalidValue(s.as_str()),
967
        }
968
    }
969
}
970

            
971
#[cfg(feature = "parser")]
972
/// # Errors
973
///
974
/// Returns an error if `input` is not a valid CSS `overscroll-behavior` value.
975
///
976
/// `contain` and `none` both stop scroll CHAINING to an ancestor; `none`
977
/// additionally suppresses the local bounce/glow. (CSS also defines `auto` as
978
/// the initial value.) The `-x` / `-y` longhands and the shorthand all parse
979
/// through here — the shorthand simply assigns the same value to both axes,
980
/// which is what the one-value form means in CSS.
981
pub fn parse_overscroll_behavior(
982
    input: &str,
983
) -> Result<OverscrollBehavior, OverscrollBehaviorParseError<'_>> {
984
    match input.trim() {
985
        "auto" => Ok(OverscrollBehavior::Auto),
986
        "contain" => Ok(OverscrollBehavior::Contain),
987
        "none" => Ok(OverscrollBehavior::None),
988
        _ => Err(OverscrollBehaviorParseError::InvalidValue(input)),
989
    }
990
}
991

            
992
#[derive(Clone, PartialEq, Eq)]
993
pub enum LayoutScrollbarWidthParseError<'a> {
994
    InvalidValue(&'a str),
995
}
996
impl_debug_as_display!(LayoutScrollbarWidthParseError<'a>);
997
impl_display! { LayoutScrollbarWidthParseError<'a>, {
998
    InvalidValue(v) => format!("Invalid scrollbar-width value: \"{}\"", v),
999
}}
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C, u8)]
pub enum LayoutScrollbarWidthParseErrorOwned {
    InvalidValue(AzString),
}
impl LayoutScrollbarWidthParseError<'_> {
    #[must_use]
18
    pub fn to_contained(&self) -> LayoutScrollbarWidthParseErrorOwned {
18
        match self {
18
            Self::InvalidValue(s) => {
18
                LayoutScrollbarWidthParseErrorOwned::InvalidValue((*s).to_string().into())
            }
        }
18
    }
}
impl LayoutScrollbarWidthParseErrorOwned {
    #[must_use]
18
    pub fn to_shared(&self) -> LayoutScrollbarWidthParseError<'_> {
18
        match self {
18
            Self::InvalidValue(s) => LayoutScrollbarWidthParseError::InvalidValue(s.as_str()),
        }
18
    }
}
#[cfg(feature = "parser")]
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `scrollbar-width` value.
43
pub fn parse_layout_scrollbar_width(
43
    input: &str,
43
) -> Result<LayoutScrollbarWidth, LayoutScrollbarWidthParseError<'_>> {
43
    match input.trim() {
43
        "auto" => Ok(LayoutScrollbarWidth::Auto),
40
        "thin" => Ok(LayoutScrollbarWidth::Thin),
36
        "none" => Ok(LayoutScrollbarWidth::None),
33
        _ => Err(LayoutScrollbarWidthParseError::InvalidValue(input)),
    }
43
}
#[derive(Clone, PartialEq)]
pub enum StyleScrollbarColorParseError<'a> {
    InvalidValue(&'a str),
    Color(CssColorParseError<'a>),
}
impl_debug_as_display!(StyleScrollbarColorParseError<'a>);
impl_display! { StyleScrollbarColorParseError<'a>, {
    InvalidValue(v) => format!("Invalid scrollbar-color value: \"{}\"", v),
    Color(e) => format!("Invalid color in scrollbar-color: {}", e),
}}
impl_from!(CssColorParseError<'a>, StyleScrollbarColorParseError::Color);
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum StyleScrollbarColorParseErrorOwned {
    InvalidValue(AzString),
    Color(CssColorParseErrorOwned),
}
impl StyleScrollbarColorParseError<'_> {
    #[must_use]
14
    pub fn to_contained(&self) -> StyleScrollbarColorParseErrorOwned {
14
        match self {
12
            Self::InvalidValue(s) => {
12
                StyleScrollbarColorParseErrorOwned::InvalidValue((*s).to_string().into())
            }
2
            Self::Color(e) => StyleScrollbarColorParseErrorOwned::Color(e.to_contained()),
        }
14
    }
}
impl StyleScrollbarColorParseErrorOwned {
    #[must_use]
14
    pub fn to_shared(&self) -> StyleScrollbarColorParseError<'_> {
14
        match self {
12
            Self::InvalidValue(s) => StyleScrollbarColorParseError::InvalidValue(s.as_str()),
2
            Self::Color(e) => StyleScrollbarColorParseError::Color(e.to_shared()),
        }
14
    }
}
#[cfg(feature = "parser")]
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `scrollbar-color` value.
61
pub fn parse_style_scrollbar_color(
61
    input: &str,
61
) -> Result<StyleScrollbarColor, StyleScrollbarColorParseError<'_>> {
61
    let input = input.trim();
61
    if input == "auto" {
4
        return Ok(StyleScrollbarColor::Auto);
57
    }
57
    let mut parts = input.split_whitespace();
57
    let thumb_str = parts
57
        .next()
57
        .ok_or(StyleScrollbarColorParseError::InvalidValue(input))?;
52
    let track_str = parts
52
        .next()
52
        .ok_or(StyleScrollbarColorParseError::InvalidValue(input))?;
32
    if parts.next().is_some() {
5
        return Err(StyleScrollbarColorParseError::InvalidValue(input));
27
    }
27
    let thumb = parse_css_color(thumb_str)?;
13
    let track = parse_css_color(track_str)?;
12
    Ok(StyleScrollbarColor::Custom(ScrollbarColorCustom {
12
        thumb,
12
        track,
12
    }))
61
}
// --- Scrollbar Visibility Mode Parser ---
#[derive(Clone, PartialEq, Eq)]
pub enum ScrollbarVisibilityModeParseError<'a> {
    InvalidValue(&'a str),
}
impl_debug_as_display!(ScrollbarVisibilityModeParseError<'a>);
impl_display! { ScrollbarVisibilityModeParseError<'a>, {
    InvalidValue(v) => format!("Invalid scrollbar-visibility value: \"{}\"", v),
}}
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C, u8)]
pub enum ScrollbarVisibilityModeParseErrorOwned {
    InvalidValue(AzString),
}
impl ScrollbarVisibilityModeParseError<'_> {
    #[must_use]
12
    pub fn to_contained(&self) -> ScrollbarVisibilityModeParseErrorOwned {
12
        match self {
12
            Self::InvalidValue(s) => {
12
                ScrollbarVisibilityModeParseErrorOwned::InvalidValue((*s).to_string().into())
            }
        }
12
    }
}
impl ScrollbarVisibilityModeParseErrorOwned {
    #[must_use]
12
    pub fn to_shared(&self) -> ScrollbarVisibilityModeParseError<'_> {
12
        match self {
12
            Self::InvalidValue(s) => ScrollbarVisibilityModeParseError::InvalidValue(s.as_str()),
        }
12
    }
}
#[cfg(feature = "parser")]
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `scrollbar-visibility-mode` value.
37
pub fn parse_scrollbar_visibility_mode(
37
    input: &str,
37
) -> Result<ScrollbarVisibilityMode, ScrollbarVisibilityModeParseError<'_>> {
37
    match input.trim() {
37
        "always" => Ok(ScrollbarVisibilityMode::Always),
35
        "when-scrolling" => Ok(ScrollbarVisibilityMode::WhenScrolling),
33
        "auto" => Ok(ScrollbarVisibilityMode::Auto),
31
        _ => Err(ScrollbarVisibilityModeParseError::InvalidValue(input)),
    }
37
}
// --- Scrollbar Fade Delay Parser ---
#[derive(Clone, PartialEq, Eq)]
pub enum ScrollbarFadeDelayParseError<'a> {
    InvalidValue(&'a str),
}
impl_debug_as_display!(ScrollbarFadeDelayParseError<'a>);
impl_display! { ScrollbarFadeDelayParseError<'a>, {
    InvalidValue(v) => format!("Invalid scrollbar-fade-delay value: \"{}\"", v),
}}
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C, u8)]
pub enum ScrollbarFadeDelayParseErrorOwned {
    InvalidValue(AzString),
}
impl ScrollbarFadeDelayParseError<'_> {
    #[must_use]
12
    pub fn to_contained(&self) -> ScrollbarFadeDelayParseErrorOwned {
12
        match self {
12
            Self::InvalidValue(s) => {
12
                ScrollbarFadeDelayParseErrorOwned::InvalidValue((*s).to_string().into())
            }
        }
12
    }
}
impl ScrollbarFadeDelayParseErrorOwned {
    #[must_use]
12
    pub fn to_shared(&self) -> ScrollbarFadeDelayParseError<'_> {
12
        match self {
12
            Self::InvalidValue(s) => ScrollbarFadeDelayParseError::InvalidValue(s.as_str()),
        }
12
    }
}
/// `scrollbar-fade-delay` / `scrollbar-fade-duration` are stored as a plain
/// millisecond `u32`, so a `t` (tick) value has to be converted here rather than
/// carried. `CssDuration::millis` does that at the nominal frame rate — reading
/// `d.inner` directly would hand a FRAME COUNT to a field every consumer reads as
/// milliseconds (`5t` would silently become 5ms, a 16x error).
#[cfg(feature = "parser")]
130
fn parse_time_ms(input: &str) -> Option<u32> {
130
    crate::props::basic::time::parse_duration(input)
130
        .ok()
130
        .map(|d| d.millis())
130
}
#[cfg(feature = "parser")]
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `scrollbar-fade-delay` value.
42
pub fn parse_scrollbar_fade_delay(
42
    input: &str,
42
) -> Result<ScrollbarFadeDelay, ScrollbarFadeDelayParseError<'_>> {
42
    parse_time_ms(input)
42
        .map(ScrollbarFadeDelay::new)
42
        .ok_or(ScrollbarFadeDelayParseError::InvalidValue(input))
42
}
// --- Scrollbar Fade Duration Parser ---
#[derive(Clone, PartialEq, Eq)]
pub enum ScrollbarFadeDurationParseError<'a> {
    InvalidValue(&'a str),
}
impl_debug_as_display!(ScrollbarFadeDurationParseError<'a>);
impl_display! { ScrollbarFadeDurationParseError<'a>, {
    InvalidValue(v) => format!("Invalid scrollbar-fade-duration value: \"{}\"", v),
}}
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C, u8)]
pub enum ScrollbarFadeDurationParseErrorOwned {
    InvalidValue(AzString),
}
impl ScrollbarFadeDurationParseError<'_> {
    #[must_use]
12
    pub fn to_contained(&self) -> ScrollbarFadeDurationParseErrorOwned {
12
        match self {
12
            Self::InvalidValue(s) => {
12
                ScrollbarFadeDurationParseErrorOwned::InvalidValue((*s).to_string().into())
            }
        }
12
    }
}
impl ScrollbarFadeDurationParseErrorOwned {
    #[must_use]
12
    pub fn to_shared(&self) -> ScrollbarFadeDurationParseError<'_> {
12
        match self {
12
            Self::InvalidValue(s) => ScrollbarFadeDurationParseError::InvalidValue(s.as_str()),
        }
12
    }
}
#[cfg(feature = "parser")]
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `scrollbar-fade-duration` value.
39
pub fn parse_scrollbar_fade_duration(
39
    input: &str,
39
) -> Result<ScrollbarFadeDuration, ScrollbarFadeDurationParseError<'_>> {
39
    parse_time_ms(input)
39
        .map(ScrollbarFadeDuration::new)
39
        .ok_or(ScrollbarFadeDurationParseError::InvalidValue(input))
39
}
#[cfg(all(test, feature = "parser"))]
mod tests {
    use super::*;
    use crate::props::basic::color::ColorU;
    #[test]
1
    fn test_parse_scrollbar_width() {
1
        assert_eq!(
1
            parse_layout_scrollbar_width("auto").unwrap(),
            LayoutScrollbarWidth::Auto
        );
1
        assert_eq!(
1
            parse_layout_scrollbar_width("thin").unwrap(),
            LayoutScrollbarWidth::Thin
        );
1
        assert_eq!(
1
            parse_layout_scrollbar_width("none").unwrap(),
            LayoutScrollbarWidth::None
        );
1
        assert!(parse_layout_scrollbar_width("thick").is_err());
1
    }
    #[test]
1
    fn test_parse_scrollbar_color() {
1
        assert_eq!(
1
            parse_style_scrollbar_color("auto").unwrap(),
            StyleScrollbarColor::Auto
        );
1
        let custom = parse_style_scrollbar_color("red blue").unwrap();
1
        assert_eq!(
            custom,
            StyleScrollbarColor::Custom(ScrollbarColorCustom {
                thumb: ColorU::RED,
                track: ColorU::BLUE
            })
        );
1
        let custom_hex = parse_style_scrollbar_color("#ff0000 #0000ff").unwrap();
1
        assert_eq!(
            custom_hex,
            StyleScrollbarColor::Custom(ScrollbarColorCustom {
                thumb: ColorU::RED,
                track: ColorU::BLUE
            })
        );
1
        assert!(parse_style_scrollbar_color("red").is_err());
1
        assert!(parse_style_scrollbar_color("red blue green").is_err());
1
    }
}
#[cfg(test)]
#[allow(clippy::unreadable_literal, clippy::float_cmp)]
mod autotest_generated {
    use super::*;
    use crate::codegen::format::FormatAsRustCode;
    /// Largest integer an `f32` represents exactly (`2^24`). Every millisecond
    /// count at or below this survives the `f32` hop inside `parse_duration`;
    /// above it, neighbouring `f32`s are more than 1ms apart.
    #[cfg(feature = "parser")]
    const TWO_POW_24: u32 = 16_777_216;
    /// Inputs that must never parse as anything, whatever the property.
    #[cfg(feature = "parser")]
    const GARBAGE: &[&str] = &[
        "",
        " ",
        "   ",
        "\t\n",
        "\u{a0}", // non-breaking space (trimmed away -> empty)
        "\0",
        "\u{1F600}",    // emoji
        "e\u{0301}",    // combining acute accent
        "\u{202e}auto", // RTL override prefix
        "аuto",         // Cyrillic 'а' homoglyph
        "AUTO",
        "auto;",
        "auto garbage",
        "-1",
        "NaN",
        "inf",
        "0x10",
        "9223372036854775807", // i64::MAX
        "1e400",
        "{[(<",
    ];
    // ======================================================================
    // ScrollPhysics presets  (other)
    // ======================================================================
    /// Every preset must be usable as-is by a scroll animator: no NaN/inf can
    /// reach the physics integrator, the deceleration rate has to stay strictly
    /// below 1.0 (at 1.0 momentum never decays -> the scroll timer never stops),
    /// and the timer tick must be non-zero (a 0ms tick is a busy-loop).
    fn assert_physics_invariants(p: ScrollPhysics, name: &str) {
        for (field, v) in [
            ("deceleration_rate", p.deceleration_rate),
            ("min_velocity_threshold", p.min_velocity_threshold),
            ("max_velocity", p.max_velocity),
            ("wheel_multiplier", p.wheel_multiplier),
            ("overscroll_elasticity", p.overscroll_elasticity),
            ("max_overscroll_distance", p.max_overscroll_distance),
        ] {
            assert!(v.is_finite(), "{name}.{field} is not finite: {v}");
            assert!(!v.is_nan(), "{name}.{field} is NaN");
            assert!(v >= 0.0, "{name}.{field} is negative: {v}");
        }
        assert!(
            p.deceleration_rate > 0.0 && p.deceleration_rate < 1.0,
            "{name}.deceleration_rate must stay inside (0.0, 1.0) or momentum never stops: {}",
            p.deceleration_rate
        );
        assert!(
            (0.0..=1.0).contains(&p.overscroll_elasticity),
            "{name}.overscroll_elasticity out of [0.0, 1.0]: {}",
            p.overscroll_elasticity
        );
        assert!(
            p.max_velocity > p.min_velocity_threshold,
            "{name}: max_velocity ({}) must exceed min_velocity_threshold ({})",
            p.max_velocity,
            p.min_velocity_threshold
        );
        assert!(
            p.wheel_multiplier > 0.0,
            "{name}.wheel_multiplier must be > 0 or the wheel does nothing"
        );
        assert!(
            p.timer_interval_ms > 0,
            "{name}.timer_interval_ms == 0 would spin the physics timer"
        );
        assert!(
            p.smooth_scroll_duration_ms > 0,
            "{name}.smooth_scroll_duration_ms == 0 makes `scroll-behavior: smooth` a no-op"
        );
    }
    #[test]
    fn scroll_physics_presets_hold_their_invariants() {
        assert_physics_invariants(ScrollPhysics::default(), "default");
        assert_physics_invariants(ScrollPhysics::ios(), "ios");
        assert_physics_invariants(ScrollPhysics::macos(), "macos");
        assert_physics_invariants(ScrollPhysics::windows(), "windows");
        assert_physics_invariants(ScrollPhysics::android(), "android");
    }
    #[test]
    fn scroll_physics_presets_are_pure_and_distinct() {
        // Called twice: no interior state, no drift.
        assert_eq!(ScrollPhysics::ios(), ScrollPhysics::ios());
        assert_eq!(ScrollPhysics::windows(), ScrollPhysics::windows());
        // A preset that silently equals another would mean a copy/paste bug.
        assert_ne!(ScrollPhysics::ios(), ScrollPhysics::macos());
        assert_ne!(ScrollPhysics::ios(), ScrollPhysics::android());
        assert_ne!(ScrollPhysics::macos(), ScrollPhysics::windows());
        assert_ne!(ScrollPhysics::android(), ScrollPhysics::windows());
        assert_ne!(ScrollPhysics::default(), ScrollPhysics::ios());
    }
    /// The documented platform character of each preset, asserted rather than
    /// assumed: Windows must not bounce, iOS/macOS must scroll naturally.
    #[test]
    fn scroll_physics_presets_match_their_documented_platform_behavior() {
        let win = ScrollPhysics::windows();
        assert_eq!(win.overscroll_elasticity, 0.0);
        assert_eq!(win.max_overscroll_distance, 0.0);
        assert!(!win.invert_direction);
        assert!(ScrollPhysics::ios().invert_direction);
        assert!(ScrollPhysics::macos().invert_direction);
        assert!(!ScrollPhysics::android().invert_direction);
        // iOS is the "slowest to stop" of the presets.
        assert!(
            ScrollPhysics::ios().deceleration_rate > ScrollPhysics::windows().deceleration_rate
        );
        // The default is Windows-like: no bounce.
        assert_eq!(ScrollPhysics::default().overscroll_elasticity, 0.0);
    }
    // ======================================================================
    // ScrollbarFadeDelay::new / ScrollbarFadeDuration::new  (constructors)
    // ======================================================================
    #[test]
    fn fade_delay_and_duration_constructors_store_their_argument_verbatim() {
        for ms in [0u32, 1, 16, 500, u32::MAX / 2, u32::MAX - 1, u32::MAX] {
            assert_eq!(ScrollbarFadeDelay::new(ms).ms, ms);
            assert_eq!(ScrollbarFadeDuration::new(ms).ms, ms);
        }
    }
    #[test]
    fn fade_zero_constants_agree_with_new_and_default() {
        assert_eq!(ScrollbarFadeDelay::ZERO, ScrollbarFadeDelay::new(0));
        assert_eq!(ScrollbarFadeDelay::ZERO, ScrollbarFadeDelay::default());
        assert_eq!(ScrollbarFadeDuration::ZERO, ScrollbarFadeDuration::new(0));
        assert_eq!(
            ScrollbarFadeDuration::ZERO,
            ScrollbarFadeDuration::default()
        );
        assert_eq!(ScrollbarFadeDelay::ZERO.ms, 0);
        assert_eq!(ScrollbarFadeDuration::ZERO.ms, 0);
    }
    /// The derived `Ord` must order by milliseconds, not by declaration order of
    /// some future field, otherwise "fades sooner" comparisons invert.
    #[test]
    fn fade_delay_orders_by_millisecond_count() {
        assert!(ScrollbarFadeDelay::new(0) < ScrollbarFadeDelay::new(1));
        assert!(ScrollbarFadeDelay::new(499) < ScrollbarFadeDelay::new(500));
        assert!(ScrollbarFadeDelay::new(u32::MAX) > ScrollbarFadeDelay::new(u32::MAX - 1));
        assert!(ScrollbarFadeDuration::new(0) < ScrollbarFadeDuration::new(u32::MAX));
    }
    // ======================================================================
    // print_as_css_value  (encoders)
    // ======================================================================
    #[test]
    fn enum_printers_emit_the_css_keywords() {
        assert_eq!(ScrollBehavior::Auto.print_as_css_value(), "auto");
        assert_eq!(ScrollBehavior::Smooth.print_as_css_value(), "smooth");
        assert_eq!(ScrollBehavior::default(), ScrollBehavior::Auto);
        assert_eq!(OverscrollBehavior::Auto.print_as_css_value(), "auto");
        assert_eq!(OverscrollBehavior::Contain.print_as_css_value(), "contain");
        assert_eq!(OverscrollBehavior::None.print_as_css_value(), "none");
        assert_eq!(OverscrollBehavior::default(), OverscrollBehavior::Auto);
        assert_eq!(OverflowScrolling::Auto.print_as_css_value(), "auto");
        assert_eq!(OverflowScrolling::Touch.print_as_css_value(), "touch");
        assert_eq!(OverflowScrolling::default(), OverflowScrolling::Auto);
        assert_eq!(LayoutScrollbarWidth::Auto.print_as_css_value(), "auto");
        assert_eq!(LayoutScrollbarWidth::Thin.print_as_css_value(), "thin");
        assert_eq!(LayoutScrollbarWidth::None.print_as_css_value(), "none");
        assert_eq!(LayoutScrollbarWidth::default(), LayoutScrollbarWidth::Auto);
        assert_eq!(
            ScrollbarVisibilityMode::Always.print_as_css_value(),
            "always"
        );
        assert_eq!(
            ScrollbarVisibilityMode::WhenScrolling.print_as_css_value(),
            "when-scrolling"
        );
        assert_eq!(ScrollbarVisibilityMode::Auto.print_as_css_value(), "auto");
        assert_eq!(
            ScrollbarVisibilityMode::default(),
            ScrollbarVisibilityMode::Always
        );
    }
    /// `0` is printed unit-less (a bare `0` is legal CSS for a time), everything
    /// else carries the `ms` unit — dropping the unit on a non-zero value would
    /// emit invalid CSS.
    #[test]
    fn fade_printers_special_case_zero_and_keep_the_unit_otherwise() {
        assert_eq!(ScrollbarFadeDelay::new(0).print_as_css_value(), "0");
        assert_eq!(ScrollbarFadeDelay::new(1).print_as_css_value(), "1ms");
        assert_eq!(ScrollbarFadeDelay::new(500).print_as_css_value(), "500ms");
        assert_eq!(
            ScrollbarFadeDelay::new(u32::MAX).print_as_css_value(),
            "4294967295ms"
        );
        assert_eq!(ScrollbarFadeDuration::new(0).print_as_css_value(), "0");
        assert_eq!(
            ScrollbarFadeDuration::new(200).print_as_css_value(),
            "200ms"
        );
        assert_eq!(
            ScrollbarFadeDuration::new(u32::MAX).print_as_css_value(),
            "4294967295ms"
        );
    }
    #[test]
    fn scrollbar_color_printer_emits_two_eight_digit_hashes() {
        assert_eq!(StyleScrollbarColor::Auto.print_as_css_value(), "auto");
        assert_eq!(StyleScrollbarColor::default(), StyleScrollbarColor::Auto);
        let custom = StyleScrollbarColor::Custom(ScrollbarColorCustom {
            thumb: ColorU::RED,
            track: ColorU::TRANSPARENT,
        });
        assert_eq!(custom.print_as_css_value(), "#ff0000ff #00000000");
    }
    /// The aggregate printers are non-standard debug formats; they must at least
    /// not panic and must include both sub-scrollbars.
    #[test]
    fn aggregate_printers_do_not_panic_and_mention_both_axes() {
        let printed = ScrollbarStyle::default().print_as_css_value();
        assert!(printed.contains("horz("), "{printed}");
        assert!(printed.contains("vert("), "{printed}");
        let info = ScrollbarInfo::default().print_as_css_value();
        assert!(info.contains("width:"), "{info}");
        assert!(info.contains("thumb:"), "{info}");
        assert!(info.contains("resizer:"), "{info}");
    }
    // ======================================================================
    // FormatAsRustCode  (codegen encoders)
    // ======================================================================
    #[test]
    fn format_as_rust_code_emits_constructible_expressions() {
        assert_eq!(
            LayoutScrollbarWidth::Thin.format_as_rust_code(0),
            "LayoutScrollbarWidth::Thin"
        );
        assert_eq!(
            LayoutScrollbarWidth::None.format_as_rust_code(7),
            "LayoutScrollbarWidth::None",
            "indent depth must not leak into a unit-variant literal"
        );
        assert_eq!(
            ScrollbarVisibilityMode::WhenScrolling.format_as_rust_code(0),
            "ScrollbarVisibilityMode::WhenScrolling"
        );
        assert_eq!(
            StyleScrollbarColor::Auto.format_as_rust_code(0),
            "StyleScrollbarColor::Auto"
        );
        // The `new(..)` codegen must round-trip the exact u32, including the extremes.
        assert_eq!(
            ScrollbarFadeDelay::new(0).format_as_rust_code(0),
            "ScrollbarFadeDelay::new(0)"
        );
        assert_eq!(
            ScrollbarFadeDelay::new(u32::MAX).format_as_rust_code(3),
            "ScrollbarFadeDelay::new(4294967295)"
        );
        assert_eq!(
            ScrollbarFadeDuration::new(u32::MAX).format_as_rust_code(0),
            "ScrollbarFadeDuration::new(4294967295)"
        );
    }
    #[test]
    fn format_as_rust_code_of_aggregates_does_not_panic() {
        let custom = StyleScrollbarColor::Custom(ScrollbarColorCustom {
            thumb: ColorU::TRANSPARENT,
            track: ColorU::WHITE,
        })
        .format_as_rust_code(0);
        assert!(
            custom.starts_with("StyleScrollbarColor::Custom(ScrollbarColorCustom {"),
            "{custom}"
        );
        assert!(
            custom.contains("thumb:") && custom.contains("track:"),
            "{custom}"
        );
        for tabs in [0usize, 1, 4] {
            let code = ScrollbarStyle::default().format_as_rust_code(tabs);
            assert!(code.starts_with("ScrollbarStyle {"), "{code}");
            assert!(code.contains("horizontal:"), "{code}");
            assert!(code.contains("vertical:"), "{code}");
        }
    }
    // ======================================================================
    // Defaults / constants  (invariants)
    // ======================================================================
    #[test]
    fn scrollbar_info_default_is_the_classic_light_constant() {
        assert_eq!(ScrollbarInfo::default(), SCROLLBAR_CLASSIC_LIGHT);
        let style = ScrollbarStyle::default();
        assert_eq!(style.horizontal, SCROLLBAR_CLASSIC_LIGHT);
        assert_eq!(style.vertical, SCROLLBAR_CLASSIC_LIGHT);
    }
    /// `ComputedScrollbarStyle::default()` reads its colors out of the default
    /// `ScrollbarInfo`; if the default track/thumb ever became a gradient the
    /// `match` would silently fall through to `None` (UA default) instead.
    #[test]
    fn computed_default_mirrors_the_default_scrollbar_info() {
        let computed = ComputedScrollbarStyle::default();
        let info = ScrollbarInfo::default();
        assert_eq!(computed.width, Some(info.width));
        assert_eq!(
            computed.thumb_color,
            Some(ColorU {
                r: 193,
                g: 193,
                b: 193,
                a: 255
            })
        );
        assert_eq!(
            computed.track_color,
            Some(ColorU {
                r: 241,
                g: 241,
                b: 241,
                a: 255
            })
        );
        assert!(
            computed.thumb_color.is_some() && computed.track_color.is_some(),
            "the classic-light default must resolve to solid colors, not None"
        );
    }
    /// Overlay presets must clip to the container border, classic (space-reserving)
    /// ones must not — the flag is what decides whether the bar is drawn inside
    /// rounded corners.
    #[test]
    fn preset_constants_agree_on_the_overlay_clipping_flag() {
        for info in [SCROLLBAR_CLASSIC_LIGHT, SCROLLBAR_CLASSIC_DARK] {
            assert!(!info.clip_to_container_border);
            assert_eq!(info.scroll_behavior, ScrollBehavior::Auto);
        }
        for info in [
            SCROLLBAR_MACOS_LIGHT,
            SCROLLBAR_MACOS_DARK,
            SCROLLBAR_IOS_LIGHT,
            SCROLLBAR_IOS_DARK,
            SCROLLBAR_ANDROID_LIGHT,
            SCROLLBAR_ANDROID_DARK,
        ] {
            assert!(info.clip_to_container_border);
            assert_eq!(info.scroll_behavior, ScrollBehavior::Smooth);
        }
        for info in [SCROLLBAR_WINDOWS_LIGHT, SCROLLBAR_WINDOWS_DARK] {
            assert!(!info.clip_to_container_border);
            assert_eq!(info.overscroll_behavior_x, OverscrollBehavior::None);
            assert_eq!(info.overscroll_behavior_y, OverscrollBehavior::None);
        }
    }
    /// Light and dark variants of the same platform must differ only in color,
    /// never in geometry — a width drift would make theme switching relayout.
    #[test]
    fn light_and_dark_presets_share_their_geometry() {
        for (light, dark) in [
            (SCROLLBAR_CLASSIC_LIGHT, SCROLLBAR_CLASSIC_DARK),
            (SCROLLBAR_MACOS_LIGHT, SCROLLBAR_MACOS_DARK),
            (SCROLLBAR_WINDOWS_LIGHT, SCROLLBAR_WINDOWS_DARK),
            (SCROLLBAR_IOS_LIGHT, SCROLLBAR_IOS_DARK),
            (SCROLLBAR_ANDROID_LIGHT, SCROLLBAR_ANDROID_DARK),
        ] {
            assert_eq!(light.width, dark.width);
            assert_eq!(light.padding_left, dark.padding_left);
            assert_eq!(light.padding_right, dark.padding_right);
            assert_eq!(
                light.clip_to_container_border,
                dark.clip_to_container_border
            );
            assert_ne!(light.thumb, dark.thumb, "light/dark thumbs must differ");
        }
    }
    // ======================================================================
    // parse_layout_scrollbar_width  (parser)
    // ======================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_width_parses_the_three_legal_keywords() {
        assert_eq!(
            parse_layout_scrollbar_width("auto"),
            Ok(LayoutScrollbarWidth::Auto)
        );
        assert_eq!(
            parse_layout_scrollbar_width("thin"),
            Ok(LayoutScrollbarWidth::Thin)
        );
        assert_eq!(
            parse_layout_scrollbar_width("none"),
            Ok(LayoutScrollbarWidth::None)
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_width_trims_surrounding_whitespace_but_rejects_inner_junk() {
        assert_eq!(
            parse_layout_scrollbar_width("  \t thin \n "),
            Ok(LayoutScrollbarWidth::Thin)
        );
        assert!(parse_layout_scrollbar_width("thin;").is_err());
        assert!(parse_layout_scrollbar_width("thin thin").is_err());
        assert!(parse_layout_scrollbar_width("th in").is_err());
    }
    /// Keyword matching is byte-exact: CSS keywords are case-insensitive in the
    /// spec, so an upper-case `AUTO` being rejected here is a real (if minor)
    /// conformance gap. Pinned so a future fix is a deliberate change.
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_width_keyword_matching_is_case_sensitive() {
        assert!(parse_layout_scrollbar_width("AUTO").is_err());
        assert!(parse_layout_scrollbar_width("Thin").is_err());
        assert!(parse_layout_scrollbar_width("NONE").is_err());
    }
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_width_rejects_every_garbage_input_without_panicking() {
        for input in GARBAGE {
            assert!(
                parse_layout_scrollbar_width(input).is_err(),
                "expected {input:?} to be rejected"
            );
        }
    }
    /// The error must carry the caller's *untrimmed* slice so diagnostics can
    /// point back at the original source text.
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_width_error_keeps_the_raw_untrimmed_input() {
        let raw = "  thick  ";
        assert_eq!(
            parse_layout_scrollbar_width(raw),
            Err(LayoutScrollbarWidthParseError::InvalidValue(raw))
        );
        let msg = format!("{}", parse_layout_scrollbar_width(raw).unwrap_err());
        assert!(msg.contains(raw), "{msg}");
    }
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_width_survives_a_megabyte_of_input_and_deep_nesting() {
        let huge = "a".repeat(1_000_000);
        assert!(parse_layout_scrollbar_width(&huge).is_err());
        let repeated_token = "auto".repeat(250_000);
        assert!(parse_layout_scrollbar_width(&repeated_token).is_err());
        let nested = "(".repeat(10_000);
        assert!(parse_layout_scrollbar_width(&nested).is_err());
    }
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_width_round_trips_through_its_printer() {
        for value in [
            LayoutScrollbarWidth::Auto,
            LayoutScrollbarWidth::Thin,
            LayoutScrollbarWidth::None,
        ] {
            let encoded = value.print_as_css_value();
            assert_eq!(
                parse_layout_scrollbar_width(&encoded),
                Ok(value),
                "{encoded} did not decode back to {value:?}"
            );
        }
    }
    // ======================================================================
    // parse_style_scrollbar_color  (parser)
    // ======================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_color_needs_exactly_two_colors_or_the_auto_keyword() {
        assert_eq!(
            parse_style_scrollbar_color("auto"),
            Ok(StyleScrollbarColor::Auto)
        );
        assert_eq!(
            parse_style_scrollbar_color("  auto  "),
            Ok(StyleScrollbarColor::Auto)
        );
        assert_eq!(
            parse_style_scrollbar_color("red blue"),
            Ok(StyleScrollbarColor::Custom(ScrollbarColorCustom {
                thumb: ColorU::RED,
                track: ColorU::BLUE,
            }))
        );
        // Too few / too many components: rejected as InvalidValue, not as a color error.
        for input in ["red", "#fff", "red blue green", "a b c d"] {
            assert!(
                matches!(
                    parse_style_scrollbar_color(input),
                    Err(StyleScrollbarColorParseError::InvalidValue(_))
                ),
                "expected {input:?} to be an InvalidValue error"
            );
        }
    }
    /// Component splitting is on *any* whitespace run, so tabs, newlines and
    /// repeated spaces are all legal separators.
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_color_accepts_any_whitespace_run_as_the_separator() {
        let expected = StyleScrollbarColor::Custom(ScrollbarColorCustom {
            thumb: ColorU::RED,
            track: ColorU::BLUE,
        });
        assert_eq!(parse_style_scrollbar_color("red\tblue"), Ok(expected));
        assert_eq!(parse_style_scrollbar_color("red\n blue"), Ok(expected));
        assert_eq!(
            parse_style_scrollbar_color("  red     blue  "),
            Ok(expected)
        );
    }
    /// Color *names* are case-insensitive (the color parser lowercases), unlike
    /// the `auto` keyword right above it, which is compared verbatim.
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_color_names_are_case_insensitive_but_the_auto_keyword_is_not() {
        assert_eq!(
            parse_style_scrollbar_color("RED BLUE"),
            Ok(StyleScrollbarColor::Custom(ScrollbarColorCustom {
                thumb: ColorU::RED,
                track: ColorU::BLUE,
            }))
        );
        // "AUTO" is a single token -> not the auto keyword, and not two colors.
        assert!(matches!(
            parse_style_scrollbar_color("AUTO"),
            Err(StyleScrollbarColorParseError::InvalidValue(_))
        ));
        // ...and `auto` is not a named color either, so it cannot sneak in as one.
        assert!(matches!(
            parse_style_scrollbar_color("auto auto"),
            Err(StyleScrollbarColorParseError::Color(_))
        ));
    }
    /// Whitespace-splitting happens *before* the color parser runs, so a
    /// functional color with spaces after its commas is torn into pieces.
    /// `rgb(255, 0, 0) blue` is valid CSS but is rejected here; the space-free
    /// spelling works. Pinned as a known limitation.
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_color_rejects_functional_colors_containing_spaces() {
        assert_eq!(
            parse_style_scrollbar_color("rgb(255,0,0) blue"),
            Ok(StyleScrollbarColor::Custom(ScrollbarColorCustom {
                thumb: ColorU::RED,
                track: ColorU::BLUE,
            }))
        );
        assert!(matches!(
            parse_style_scrollbar_color("rgb(255, 0, 0) blue"),
            Err(StyleScrollbarColorParseError::InvalidValue(_))
        ));
    }
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_color_reports_which_component_failed() {
        // A bad thumb is reported as a color error, not as InvalidValue.
        assert!(matches!(
            parse_style_scrollbar_color("notacolor blue"),
            Err(StyleScrollbarColorParseError::Color(_))
        ));
        assert!(matches!(
            parse_style_scrollbar_color("red notacolor"),
            Err(StyleScrollbarColorParseError::Color(_))
        ));
        assert!(matches!(
            parse_style_scrollbar_color("#gggggg #000000"),
            Err(StyleScrollbarColorParseError::Color(_))
        ));
    }
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_color_rejects_garbage_without_panicking() {
        for input in GARBAGE {
            assert!(
                parse_style_scrollbar_color(input).is_err(),
                "expected {input:?} to be rejected"
            );
        }
        // Boundary numerics as color components.
        for input in [
            "0 0",
            "-0 -0",
            "NaN NaN",
            "inf inf",
            "9223372036854775807 1",
            "1e400 1e400",
            "-1 -1",
        ] {
            assert!(
                parse_style_scrollbar_color(input).is_err(),
                "expected {input:?} to be rejected"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_color_survives_huge_and_deeply_nested_input() {
        let huge = "z".repeat(500_000);
        let two_huge = format!("{huge} {huge}");
        assert!(parse_style_scrollbar_color(&two_huge).is_err());
        let nested = "(".repeat(10_000);
        assert!(parse_style_scrollbar_color(&format!("{nested} {nested}")).is_err());
        // Many components: must be rejected on count, not walked color-by-color.
        let many = "red ".repeat(100_000);
        assert!(matches!(
            parse_style_scrollbar_color(&many),
            Err(StyleScrollbarColorParseError::InvalidValue(_))
        ));
    }
    /// The color error carries the *trimmed* input (the function rebinds `input`
    /// to the trimmed slice), unlike `parse_layout_scrollbar_width`, which keeps
    /// the raw slice. Pinned so the inconsistency is visible.
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_color_error_carries_the_trimmed_input() {
        assert_eq!(
            parse_style_scrollbar_color("  red  "),
            Err(StyleScrollbarColorParseError::InvalidValue("red"))
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_color_round_trips_through_its_printer() {
        let samples = [
            StyleScrollbarColor::Auto,
            StyleScrollbarColor::Custom(ScrollbarColorCustom {
                thumb: ColorU::RED,
                track: ColorU::BLUE,
            }),
            StyleScrollbarColor::Custom(ScrollbarColorCustom {
                thumb: ColorU::TRANSPARENT,
                track: ColorU::TRANSPARENT,
            }),
            StyleScrollbarColor::Custom(ScrollbarColorCustom {
                thumb: ColorU {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: 100,
                },
                track: ColorU {
                    r: 1,
                    g: 2,
                    b: 3,
                    a: 4,
                },
            }),
            StyleScrollbarColor::Custom(ScrollbarColorCustom {
                thumb: ColorU::WHITE,
                track: ColorU::BLACK,
            }),
        ];
        for value in samples {
            let encoded = value.print_as_css_value();
            assert_eq!(
                parse_style_scrollbar_color(&encoded),
                Ok(value),
                "{encoded} did not decode back to {value:?}"
            );
        }
    }
    // ======================================================================
    // parse_scrollbar_visibility_mode  (parser)
    // ======================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn visibility_mode_parses_its_three_keywords_and_trims() {
        assert_eq!(
            parse_scrollbar_visibility_mode("always"),
            Ok(ScrollbarVisibilityMode::Always)
        );
        assert_eq!(
            parse_scrollbar_visibility_mode(" when-scrolling\t"),
            Ok(ScrollbarVisibilityMode::WhenScrolling)
        );
        assert_eq!(
            parse_scrollbar_visibility_mode("auto"),
            Ok(ScrollbarVisibilityMode::Auto)
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn visibility_mode_rejects_near_misses_and_garbage() {
        for input in [
            "when scrolling", // space instead of hyphen
            "whenscrolling",
            "when-scrolling-",
            "-when-scrolling",
            "ALWAYS",
            "always;",
            "always auto",
        ] {
            assert!(
                parse_scrollbar_visibility_mode(input).is_err(),
                "expected {input:?} to be rejected"
            );
        }
        for input in GARBAGE {
            assert!(
                parse_scrollbar_visibility_mode(input).is_err(),
                "expected {input:?} to be rejected"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn visibility_mode_survives_huge_and_nested_input() {
        assert!(parse_scrollbar_visibility_mode(&"a".repeat(1_000_000)).is_err());
        assert!(parse_scrollbar_visibility_mode(&"always".repeat(200_000)).is_err());
        assert!(parse_scrollbar_visibility_mode(&"[".repeat(10_000)).is_err());
    }
    #[cfg(feature = "parser")]
    #[test]
    fn visibility_mode_round_trips_through_its_printer() {
        for value in [
            ScrollbarVisibilityMode::Always,
            ScrollbarVisibilityMode::WhenScrolling,
            ScrollbarVisibilityMode::Auto,
        ] {
            let encoded = value.print_as_css_value();
            assert_eq!(
                parse_scrollbar_visibility_mode(&encoded),
                Ok(value),
                "{encoded} did not decode back to {value:?}"
            );
        }
    }
    // ======================================================================
    // parse_time_ms  (private parser)
    // ======================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn parse_time_ms_accepts_bare_zero_and_both_units() {
        assert_eq!(parse_time_ms("0"), Some(0));
        assert_eq!(parse_time_ms("0ms"), Some(0));
        assert_eq!(parse_time_ms("0s"), Some(0));
        assert_eq!(parse_time_ms("500ms"), Some(500));
        assert_eq!(parse_time_ms("1s"), Some(1000));
        assert_eq!(parse_time_ms("1.5s"), Some(1500));
        assert_eq!(parse_time_ms("  200ms  "), Some(200));
        assert_eq!(
            parse_time_ms("200MS"),
            Some(200),
            "units are case-insensitive"
        );
    }
    /// The scrollbar fade fields are a bare millisecond `u32`, so a `t` (tick)
    /// value has to be CONVERTED at the nominal frame rate on the way in, not
    /// passed through. `60t` is one second; passing the raw tick count through
    /// would make it 60ms.
    #[cfg(feature = "parser")]
    #[test]
    fn parse_time_ms_converts_the_tick_unit_to_milliseconds() {
        assert_eq!(parse_time_ms("60t"), Some(1000));
        assert_eq!(parse_time_ms("30t"), Some(500));
        assert_eq!(parse_time_ms("1t"), Some(16));
        assert_eq!(parse_time_ms("0t"), Some(0));
        assert_ne!(parse_time_ms("60t"), Some(60), "ticks passed through as ms");
    }
    /// A unit is mandatory (except for a bare `0`) and must be attached to the
    /// number — `"1 s"` has an interior space and cannot parse.
    #[cfg(feature = "parser")]
    #[test]
    fn parse_time_ms_requires_an_attached_unit() {
        assert_eq!(parse_time_ms("500"), None);
        assert_eq!(parse_time_ms("1 s"), None);
        assert_eq!(parse_time_ms("500 ms"), None);
        assert_eq!(parse_time_ms("ms"), None);
        assert_eq!(parse_time_ms("s"), None);
        assert_eq!(parse_time_ms("500px"), None);
        assert_eq!(parse_time_ms("500msms"), None);
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_time_ms_rejects_empty_blank_unicode_and_garbage() {
        for input in [
            "",
            " ",
            "   ",
            "\t\n",
            "\u{1F600}",
            "e\u{0301}",
            "٥ms",
            "500ms",
        ] {
            assert_eq!(
                parse_time_ms(input),
                None,
                "expected {input:?} to be rejected"
            );
        }
    }
    #[cfg(feature = "parser")]
    #[test]
    fn parse_time_ms_rejects_negative_durations() {
        assert_eq!(parse_time_ms("-1ms"), None);
        assert_eq!(parse_time_ms("-0.5s"), None);
        assert_eq!(parse_time_ms("-inf ms"), None);
    }
    /// Negative *zero* is not less than zero in IEEE-754, so it slips past the
    /// `< 0.0` guard and casts to 0 — harmless, but worth pinning.
    #[cfg(feature = "parser")]
    #[test]
    fn parse_time_ms_accepts_negative_zero_as_zero() {
        assert_eq!(parse_time_ms("-0ms"), Some(0));
        assert_eq!(parse_time_ms("-0.0s"), Some(0));
    }
    /// The float -> u32 cast saturates instead of wrapping or panicking:
    /// `inf` clamps to `u32::MAX`, `NaN` becomes 0. Both are *safe* (no UB, no
    /// panic), but note that `"infms"` and `"NaNms"` are accepted as durations
    /// at all — a stricter parser would reject non-finite times outright.
    #[cfg(feature = "parser")]
    #[test]
    fn parse_time_ms_saturates_on_non_finite_and_huge_values() {
        assert_eq!(parse_time_ms("infms"), Some(u32::MAX));
        assert_eq!(parse_time_ms("infinityms"), Some(u32::MAX));
        assert_eq!(parse_time_ms("infs"), Some(u32::MAX));
        assert_eq!(parse_time_ms("nanms"), Some(0));
        assert_eq!(parse_time_ms("NaNms"), Some(0));
        assert_eq!(parse_time_ms("1e30ms"), Some(u32::MAX));
        assert_eq!(
            parse_time_ms("1e400ms"),
            Some(u32::MAX),
            "overflows f32 to inf"
        );
        assert_eq!(parse_time_ms("4294967296ms"), Some(u32::MAX), "2^32 clamps");
        assert_eq!(parse_time_ms("1e-30ms"), Some(0), "underflows to zero");
        // A million digits must saturate, not hang.
        let long_number = format!("{}ms", "9".repeat(100_000));
        assert_eq!(parse_time_ms(&long_number), Some(u32::MAX));
    }
    /// Seconds are multiplied by 1000 *before* the cast, so a value that fits in
    /// a u32 as seconds can still saturate as milliseconds.
    #[cfg(feature = "parser")]
    #[test]
    fn parse_time_ms_saturates_when_seconds_overflow_milliseconds() {
        // Exact while the millisecond product stays inside f32's integer range.
        assert_eq!(parse_time_ms("1000s"), Some(1_000_000));
        assert_eq!(parse_time_ms("16777s"), Some(16_777_000));
        // Past u32::MAX milliseconds the cast clamps instead of wrapping.
        assert_eq!(parse_time_ms("4294968s"), Some(u32::MAX));
        assert_eq!(parse_time_ms("5000000s"), Some(u32::MAX));
        // Just under the clamp, the f32 product is only accurate to ~256ms
        // (the ulp at that magnitude) — near, but no longer exact.
        let ms = parse_time_ms("4294967s").expect("4294967s must parse");
        assert!(
            ms.abs_diff(4_294_967_000) <= 512,
            "4294967s decoded to {ms}, which is nowhere near 4294967000ms"
        );
        assert_eq!(
            parse_time_ms("0.0005s"),
            Some(0),
            "sub-ms truncates toward zero"
        );
    }
    // ======================================================================
    // parse_scrollbar_fade_delay / parse_scrollbar_fade_duration  (parsers)
    // ======================================================================
    #[cfg(feature = "parser")]
    #[test]
    fn fade_parsers_accept_the_documented_syntax() {
        assert_eq!(
            parse_scrollbar_fade_delay("500ms"),
            Ok(ScrollbarFadeDelay::new(500))
        );
        assert_eq!(
            parse_scrollbar_fade_delay("0"),
            Ok(ScrollbarFadeDelay::ZERO)
        );
        assert_eq!(
            parse_scrollbar_fade_delay(" 1s "),
            Ok(ScrollbarFadeDelay::new(1000))
        );
        assert_eq!(
            parse_scrollbar_fade_duration("200ms"),
            Ok(ScrollbarFadeDuration::new(200))
        );
        assert_eq!(
            parse_scrollbar_fade_duration("0"),
            Ok(ScrollbarFadeDuration::ZERO)
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn fade_parsers_reject_garbage_and_keep_the_raw_input_in_the_error() {
        for input in GARBAGE {
            assert!(
                parse_scrollbar_fade_delay(input).is_err(),
                "delay: expected {input:?} to be rejected"
            );
            assert!(
                parse_scrollbar_fade_duration(input).is_err(),
                "duration: expected {input:?} to be rejected"
            );
        }
        let raw = "  bogus  ";
        assert_eq!(
            parse_scrollbar_fade_delay(raw),
            Err(ScrollbarFadeDelayParseError::InvalidValue(raw))
        );
        assert_eq!(
            parse_scrollbar_fade_duration(raw),
            Err(ScrollbarFadeDurationParseError::InvalidValue(raw))
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn fade_parsers_reject_negative_delays() {
        assert!(parse_scrollbar_fade_delay("-1ms").is_err());
        assert!(parse_scrollbar_fade_delay("-500ms").is_err());
        assert!(parse_scrollbar_fade_duration("-0.5s").is_err());
    }
    #[cfg(feature = "parser")]
    #[test]
    fn fade_parsers_saturate_instead_of_overflowing() {
        assert_eq!(
            parse_scrollbar_fade_delay("1e30ms"),
            Ok(ScrollbarFadeDelay::new(u32::MAX))
        );
        assert_eq!(
            parse_scrollbar_fade_duration("99999999999999s"),
            Ok(ScrollbarFadeDuration::new(u32::MAX))
        );
    }
    #[cfg(feature = "parser")]
    #[test]
    fn fade_parsers_survive_huge_and_nested_input() {
        assert!(parse_scrollbar_fade_delay(&"a".repeat(1_000_000)).is_err());
        assert!(parse_scrollbar_fade_duration(&"0ms".repeat(300_000)).is_err());
        assert!(parse_scrollbar_fade_delay(&"(".repeat(10_000)).is_err());
        assert!(parse_scrollbar_fade_duration(&"[".repeat(10_000)).is_err());
    }
    /// encode -> decode is the identity for every millisecond count an `f32` can
    /// represent exactly (`<= 2^24`), including the `0` special case and the
    /// `u32::MAX` extreme (whose f32 rounding lands back on `u32::MAX` after the
    /// saturating cast).
    #[cfg(feature = "parser")]
    #[test]
    fn fade_delay_round_trips_exactly_up_to_two_pow_24() {
        for ms in [
            0u32,
            1,
            8,
            16,
            200,
            500,
            65_535,
            1_000_000,
            TWO_POW_24 - 1,
            TWO_POW_24,
            u32::MAX,
        ] {
            let value = ScrollbarFadeDelay::new(ms);
            let encoded = value.print_as_css_value();
            assert_eq!(
                parse_scrollbar_fade_delay(&encoded),
                Ok(value),
                "{ms}ms encoded as {encoded:?} did not decode back"
            );
            let value = ScrollbarFadeDuration::new(ms);
            let encoded = value.print_as_css_value();
            assert_eq!(
                parse_scrollbar_fade_duration(&encoded),
                Ok(value),
                "{ms}ms encoded as {encoded:?} did not decode back"
            );
        }
    }
    /// Above 2^24 the round-trip is lossy: the value is snapped to the nearest
    /// representable `f32`. Pinned as a precision limit of the shared duration
    /// parser (a delay is never realistically > 4.6 hours, so this is benign).
    #[cfg(feature = "parser")]
    #[test]
    fn fade_delay_round_trip_is_lossy_above_two_pow_24() {
        let value = ScrollbarFadeDelay::new(TWO_POW_24 + 1);
        let decoded = parse_scrollbar_fade_delay(&value.print_as_css_value()).unwrap();
        assert_ne!(decoded, value, "expected precision loss above 2^24");
        assert_eq!(decoded.ms, TWO_POW_24, "must snap down to the nearest f32");
    }
    // ======================================================================
    // Error to_contained / to_shared  (getters)
    // ======================================================================
    /// Strings that stress the owned<->borrowed error conversions: empty, blank,
    /// multibyte, embedded NUL, and a 100k-byte payload.
    fn error_payloads() -> [String; 6] {
        [
            String::new(),
            String::from(" "),
            String::from("thick"),
            String::from("\u{1F600}\u{0301}"),
            String::from("nul\0inside"),
            "x".repeat(100_000),
        ]
    }
    #[test]
    fn layout_scrollbar_width_error_round_trips_through_owned_and_back() {
        for payload in error_payloads() {
            let shared = LayoutScrollbarWidthParseError::InvalidValue(&payload);
            let owned = shared.to_contained();
            assert_eq!(
                owned,
                LayoutScrollbarWidthParseErrorOwned::InvalidValue(payload.clone().into())
            );
            assert_eq!(
                owned.to_shared(),
                shared,
                "owned -> shared lost information"
            );
            assert_eq!(
                owned.to_shared().to_contained(),
                owned,
                "conversion is not idempotent"
            );
        }
    }
    #[test]
    fn visibility_mode_error_round_trips_through_owned_and_back() {
        for payload in error_payloads() {
            let shared = ScrollbarVisibilityModeParseError::InvalidValue(&payload);
            let owned = shared.to_contained();
            assert_eq!(owned.to_shared(), shared);
            assert_eq!(owned.to_shared().to_contained(), owned);
        }
    }
    #[test]
    fn fade_delay_and_duration_errors_round_trip_through_owned_and_back() {
        for payload in error_payloads() {
            let delay = ScrollbarFadeDelayParseError::InvalidValue(&payload);
            let owned_delay = delay.to_contained();
            assert_eq!(owned_delay.to_shared(), delay);
            assert_eq!(owned_delay.to_shared().to_contained(), owned_delay);
            let duration = ScrollbarFadeDurationParseError::InvalidValue(&payload);
            let owned_duration = duration.to_contained();
            assert_eq!(owned_duration.to_shared(), duration);
            assert_eq!(owned_duration.to_shared().to_contained(), owned_duration);
        }
    }
    #[test]
    fn scrollbar_color_invalid_value_error_round_trips_through_owned_and_back() {
        for payload in error_payloads() {
            let shared = StyleScrollbarColorParseError::InvalidValue(&payload);
            let owned = shared.to_contained();
            assert_eq!(
                owned,
                StyleScrollbarColorParseErrorOwned::InvalidValue(payload.clone().into())
            );
            assert_eq!(owned.to_shared(), shared);
            assert_eq!(owned.to_shared().to_contained(), owned);
        }
    }
    /// The nested `Color` variant must delegate to the color error's own
    /// conversion rather than flattening to a string.
    #[cfg(feature = "parser")]
    #[test]
    fn scrollbar_color_nested_color_error_round_trips_through_owned_and_back() {
        let shared = parse_style_scrollbar_color("notacolor blue").unwrap_err();
        assert!(matches!(shared, StyleScrollbarColorParseError::Color(_)));
        let owned = shared.to_contained();
        assert!(matches!(
            owned,
            StyleScrollbarColorParseErrorOwned::Color(_)
        ));
        assert_eq!(
            owned.to_shared(),
            shared,
            "nested color error lost information"
        );
        assert_eq!(owned.to_shared().to_contained(), owned);
    }
    /// Error `Display` must always name the offending input, otherwise a CSS
    /// diagnostic is useless. (`Debug` is implemented as `Display` here.)
    #[cfg(feature = "parser")]
    #[test]
    fn error_display_mentions_the_offending_input() {
        let width = parse_layout_scrollbar_width("thick").unwrap_err();
        assert!(format!("{width}").contains("thick"), "{width}");
        assert!(format!("{width:?}").contains("thick"), "{width:?}");
        let color = parse_style_scrollbar_color("red").unwrap_err();
        assert!(format!("{color}").contains("red"), "{color}");
        let vis = parse_scrollbar_visibility_mode("sometimes").unwrap_err();
        assert!(format!("{vis}").contains("sometimes"), "{vis}");
        let delay = parse_scrollbar_fade_delay("soon").unwrap_err();
        assert!(format!("{delay}").contains("soon"), "{delay}");
        let duration = parse_scrollbar_fade_duration("briefly").unwrap_err();
        assert!(format!("{duration}").contains("briefly"), "{duration}");
    }
    /// Displaying an error whose payload is empty or exotic must not panic on a
    /// byte/char boundary.
    #[test]
    fn error_display_does_not_panic_on_exotic_payloads() {
        for payload in error_payloads() {
            let err = LayoutScrollbarWidthParseError::InvalidValue(&payload);
            assert!(!format!("{err}").is_empty());
            let owned = err.to_contained();
            assert!(!format!("{}", owned.to_shared()).is_empty());
        }
    }
}