1
//! CSS properties for managing content overflow.
2

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

            
5
use crate::{
6
    corety::{AzString, OptionF32},
7
    props::formatter::PrintAsCssValue,
8
};
9

            
10
// +spec:overflow:647a7b - overflow property (visible/hidden/clip/scroll/auto),
11
// overflow-clip-margin, text-overflow defined in CSS Overflow 3
12
/// Represents an `overflow-x` or `overflow-y` property.
13
///
14
/// Determines what to do when content overflows an element's box.
15
// +spec:overflow:3526f7 - overflow property with scroll/clip/hidden/visible/auto values
16
// +spec:overflow:36c4f6 - overflow-x/overflow-y properties with clip value
17
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
18
#[repr(C)]
19
pub enum LayoutOverflow {
20
    /// Always shows a scroll bar, overflows on scroll.
21
    Scroll,
22
    /// Shows a scroll bar only when content overflows.
23
    Auto,
24
    /// Clips overflowing content. The rest of the content will be invisible.
25
    Hidden,
26
    /// Content is not clipped and renders outside the element's box. This is the CSS default.
27
    // +spec:overflow:236100 - initial value of 'overflow' is 'visible'
28
    #[default]
29
    Visible,
30
    /// Similar to `hidden`, clips the content at the box's edge.
31
    Clip,
32
}
33

            
34
impl LayoutOverflow {
35
    /// Returns whether this overflow value requires a scrollbar to be displayed.
36
    ///
37
    /// - `overflow: scroll` always shows the scrollbar.
38
    /// - `overflow: auto` only shows the scrollbar if the content is currently overflowing.
39
    /// - `overflow: hidden`, `overflow: visible`, and `overflow: clip` do not show any scrollbars.
40
    // +spec:overflow:2bf182 - overflow:scroll always shows scrollbar whether or not content is
41
    // clipped +spec:overflow:84cd40 - scroll value always displays scrollbar for accessing
42
    // clipped content +spec:overflow:8fcdd8 - auto causes scrolling mechanism for overflowing
43
    // boxes (table exception is UA-level)
44
    #[must_use]
45
20
    pub const fn needs_scrollbar(&self, currently_overflowing: bool) -> bool {
46
20
        match self {
47
4
            Self::Scroll => true,
48
5
            Self::Auto => currently_overflowing,
49
11
            Self::Hidden | Self::Visible | Self::Clip => false,
50
        }
51
20
    }
52

            
53
    // +spec:overflow:145749 - overflow:hidden clips content to containing element box
54
    // +spec:overflow:3dc18e - overflow:hidden clips content with no scrolling UI
55
    // +spec:overflow:81e306 - clipping region clips all aspects outside it; clipped content does
56
    // not cause overflow +spec:overflow:fd38ce - overflow properties specify whether a box's
57
    // content is clipped / scroll container
58
    /// Returns `true` if this overflow value clips content (everything except `visible`).
59
    #[must_use]
60
65
    pub const fn is_clipped(&self) -> bool {
61
        // All overflow values except 'visible' clip their content
62
65
        matches!(self, Self::Hidden | Self::Clip | Self::Auto | Self::Scroll)
63
65
    }
64

            
65
    /// Returns `true` if the overflow type is `scroll`.
66
    #[must_use]
67
7
    pub const fn is_scroll(&self) -> bool {
68
7
        matches!(self, Self::Scroll)
69
7
    }
70

            
71
    // +spec:overflow:3be57c - overflow:hidden disables user scrolling but programmatic scrolling
72
    // still works
73
    /// Does this value establish a SCROLL CONTAINER (css-overflow-3 §3.1)?
74
    ///
75
    /// `hidden`, `scroll` and `auto` all do — an `overflow: hidden` box is
76
    /// programmatically scrollable (scrollIntoView, scroll offsets set from
77
    /// callbacks) even though its user-facing scrolling UI is disabled.
78
    /// `visible` and `clip` do not scroll at all.
79
    #[must_use]
80
    pub const fn is_scroll_container(&self) -> bool {
81
        matches!(self, Self::Hidden | Self::Scroll | Self::Auto)
82
    }
83

            
84
    /// Does this value allow scrolling DIRECTLY TRIGGERED BY THE USER
85
    /// (wheel, trackpad, scrollbar drag, keyboard)? `hidden` does not —
86
    /// only programmatic scrolling reaches it.
87
    #[must_use]
88
    pub const fn allows_user_scrolling(&self) -> bool {
89
        matches!(self, Self::Scroll | Self::Auto)
90
    }
91

            
92
    /// Returns `true` if the overflow type is `visible`, which is the only
93
    /// overflow type that doesn't clip its children.
94
    #[must_use]
95
106
    pub fn is_overflow_visible(&self) -> bool {
96
106
        *self == Self::Visible
97
106
    }
98

            
99
    /// Returns `true` if the overflow type is `hidden`.
100
    #[must_use]
101
106
    pub fn is_overflow_hidden(&self) -> bool {
102
106
        *self == Self::Hidden
103
106
    }
104

            
105
    // +spec:overflow:833078 - visible/clip compute to auto/hidden if other axis is scrollable
106
    /// Resolves the computed value per CSS Overflow 3 § 3.1:
107
    /// visible/clip values compute to auto/hidden (respectively)
108
    /// if the other axis is neither visible nor clip.
109
    #[must_use]
110
2404605
    pub const fn resolve_computed(self, other_axis: Self) -> Self {
111
2404605
        let other_is_scrollable = !matches!(other_axis, Self::Visible | Self::Clip);
112
2404605
        if other_is_scrollable {
113
59056
            match self {
114
2749
                Self::Visible => Self::Auto,
115
84
                Self::Clip => Self::Hidden,
116
56223
                other => other,
117
            }
118
        } else {
119
2345549
            self
120
        }
121
2404605
    }
122
}
123

            
124
impl PrintAsCssValue for LayoutOverflow {
125
11
    fn print_as_css_value(&self) -> String {
126
11
        String::from(match self {
127
2
            Self::Scroll => "scroll",
128
3
            Self::Auto => "auto",
129
2
            Self::Hidden => "hidden",
130
2
            Self::Visible => "visible",
131
2
            Self::Clip => "clip",
132
        })
133
11
    }
134
}
135

            
136
// -- Parser
137

            
138
/// Error returned when parsing an `overflow` property fails.
139
#[derive(Clone, PartialEq, Eq)]
140
pub enum LayoutOverflowParseError<'a> {
141
    /// The provided value is not a valid `overflow` keyword.
142
    InvalidValue(&'a str),
143
}
144

            
145
impl_debug_as_display!(LayoutOverflowParseError<'a>);
146
impl_display! { LayoutOverflowParseError<'a>, {
147
    InvalidValue(val) => format!(
148
        "Invalid overflow value: \"{}\". Expected 'scroll', 'auto', 'hidden', 'visible', or 'clip'.", val
149
    ),
150
}}
151

            
152
/// An owned version of `LayoutOverflowParseError`.
153
#[derive(Debug, Clone, PartialEq, Eq)]
154
#[repr(C, u8)]
155
pub enum LayoutOverflowParseErrorOwned {
156
    InvalidValue(AzString),
157
}
158

            
159
impl LayoutOverflowParseError<'_> {
160
    /// Converts the borrowed error into an owned error.
161
    #[must_use]
162
15
    pub fn to_contained(&self) -> LayoutOverflowParseErrorOwned {
163
15
        match self {
164
15
            LayoutOverflowParseError::InvalidValue(s) => {
165
15
                LayoutOverflowParseErrorOwned::InvalidValue((*s).to_string().into())
166
            }
167
        }
168
15
    }
169
}
170

            
171
impl LayoutOverflowParseErrorOwned {
172
    /// Converts the owned error back into a borrowed error.
173
    #[must_use]
174
15
    pub fn to_shared(&self) -> LayoutOverflowParseError<'_> {
175
15
        match self {
176
15
            Self::InvalidValue(s) => LayoutOverflowParseError::InvalidValue(s.as_str()),
177
        }
178
15
    }
179
}
180

            
181
#[cfg(feature = "parser")]
182
/// Parses a `LayoutOverflow` from a string slice.
183
/// # Errors
184
///
185
/// Returns an error if `input` is not a valid CSS `overflow` value.
186
13803
pub fn parse_layout_overflow(input: &str) -> Result<LayoutOverflow, LayoutOverflowParseError<'_>> {
187
13803
    let input_trimmed = input.trim();
188
13803
    match input_trimmed {
189
13803
        "scroll" => Ok(LayoutOverflow::Scroll),
190
10765
        "auto" | "overlay" => Ok(LayoutOverflow::Auto), /* +spec:overflow:6120e6 - "overlay" is
191
                                                          * a legacy value alias of "auto" */
192
10193
        "hidden" => Ok(LayoutOverflow::Hidden),
193
82
        "visible" => Ok(LayoutOverflow::Visible),
194
67
        "clip" => Ok(LayoutOverflow::Clip),
195
52
        _ => Err(LayoutOverflowParseError::InvalidValue(input)),
196
    }
197
13803
}
198

            
199
// -- StyleScrollbarGutter --
200
// +spec:box-model:e98b7c - scrollbar gutter: space between inner border edge and outer padding edge
201

            
202
/// Represents the `scrollbar-gutter` CSS property.
203
///
204
/// Controls whether space is reserved for the scrollbar, preventing
205
/// layout shifts when content overflows.
206
// +spec:overflow:da4bbc - scrollbar-gutter affects gutter presence, not scrollbar visibility
207
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
208
#[repr(C)]
209
pub enum StyleScrollbarGutter {
210
    /// No scrollbar gutter is reserved.
211
    #[default]
212
    Auto,
213
    /// Space is reserved for the scrollbar on one edge.
214
    Stable,
215
    /// Space is reserved for the scrollbar on both edges.
216
    StableBothEdges,
217
}
218

            
219
impl PrintAsCssValue for StyleScrollbarGutter {
220
4
    fn print_as_css_value(&self) -> String {
221
4
        String::from(match self {
222
1
            Self::Auto => "auto",
223
1
            Self::Stable => "stable",
224
2
            Self::StableBothEdges => "stable both-edges",
225
        })
226
4
    }
227
}
228

            
229
// -- Parser for StyleScrollbarGutter
230

            
231
/// Error returned when parsing a `scrollbar-gutter` property fails.
232
#[derive(Clone, PartialEq, Eq)]
233
pub enum StyleScrollbarGutterParseError<'a> {
234
    /// The provided value is not a valid `scrollbar-gutter` keyword.
235
    InvalidValue(&'a str),
236
}
237

            
238
impl_debug_as_display!(StyleScrollbarGutterParseError<'a>);
239
impl_display! { StyleScrollbarGutterParseError<'a>, {
240
    InvalidValue(val) => format!(
241
        "Invalid scrollbar-gutter value: \"{}\". Expected 'auto', 'stable', or 'stable both-edges'.", val
242
    ),
243
}}
244

            
245
/// An owned version of `StyleScrollbarGutterParseError`.
246
#[derive(Debug, Clone, PartialEq, Eq)]
247
#[repr(C, u8)]
248
pub enum StyleScrollbarGutterParseErrorOwned {
249
    InvalidValue(AzString),
250
}
251

            
252
impl StyleScrollbarGutterParseError<'_> {
253
    /// Converts the borrowed error into an owned error.
254
    #[must_use]
255
15
    pub fn to_contained(&self) -> StyleScrollbarGutterParseErrorOwned {
256
15
        match self {
257
15
            StyleScrollbarGutterParseError::InvalidValue(s) => {
258
15
                StyleScrollbarGutterParseErrorOwned::InvalidValue((*s).to_string().into())
259
            }
260
        }
261
15
    }
262
}
263

            
264
impl StyleScrollbarGutterParseErrorOwned {
265
    /// Converts the owned error back into a borrowed error.
266
    #[must_use]
267
15
    pub fn to_shared(&self) -> StyleScrollbarGutterParseError<'_> {
268
15
        match self {
269
15
            Self::InvalidValue(s) => StyleScrollbarGutterParseError::InvalidValue(s.as_str()),
270
        }
271
15
    }
272
}
273

            
274
#[cfg(feature = "parser")]
275
/// Parses a `StyleScrollbarGutter` from a string slice.
276
/// # Errors
277
///
278
/// Returns an error if `input` is not a valid CSS `scrollbar-gutter` value.
279
32
pub fn parse_style_scrollbar_gutter(
280
32
    input: &str,
281
32
) -> Result<StyleScrollbarGutter, StyleScrollbarGutterParseError<'_>> {
282
32
    let input_trimmed = input.trim();
283
32
    match input_trimmed {
284
32
        "auto" => Ok(StyleScrollbarGutter::Auto),
285
31
        "stable" => Ok(StyleScrollbarGutter::Stable),
286
30
        "stable both-edges" => Ok(StyleScrollbarGutter::StableBothEdges),
287
27
        _ => Err(StyleScrollbarGutterParseError::InvalidValue(input)),
288
    }
289
32
}
290

            
291
// -- StyleTextOverflow --
292
// +spec:overflow:647a7b - text-overflow property defined in CSS Overflow 3
293

            
294
/// Represents the `text-overflow` CSS property.
295
///
296
/// Determines how inline content that is clipped (because the block container
297
/// has `overflow` other than `visible`) is signaled to the user at the end of
298
/// the line box.
299
///
300
/// CSS Overflow Module Level 3 §5: <https://www.w3.org/TR/css-overflow-3/#text-overflow>
301
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
302
#[repr(C)]
303
pub enum StyleTextOverflow {
304
    /// Clip the inline content at the edge of its line box. This is the initial value.
305
    #[default]
306
    Clip,
307
    /// Render an ellipsis (`…`, U+2026) to represent clipped inline content.
308
    Ellipsis,
309
}
310

            
311
impl PrintAsCssValue for StyleTextOverflow {
312
4
    fn print_as_css_value(&self) -> String {
313
4
        String::from(match self {
314
1
            Self::Clip => "clip",
315
3
            Self::Ellipsis => "ellipsis",
316
        })
317
4
    }
318
}
319

            
320
// -- Parser for StyleTextOverflow
321

            
322
/// Error returned when parsing a `text-overflow` property fails.
323
#[derive(Clone, PartialEq, Eq)]
324
pub enum StyleTextOverflowParseError<'a> {
325
    /// The provided value is not a valid `text-overflow` keyword.
326
    InvalidValue(&'a str),
327
}
328

            
329
impl_debug_as_display!(StyleTextOverflowParseError<'a>);
330
impl_display! { StyleTextOverflowParseError<'a>, {
331
    InvalidValue(val) => format!(
332
        "Invalid text-overflow value: \"{}\". Expected 'clip' or 'ellipsis'.", val
333
    ),
334
}}
335

            
336
/// An owned version of `StyleTextOverflowParseError`.
337
#[derive(Debug, Clone, PartialEq, Eq)]
338
#[repr(C, u8)]
339
pub enum StyleTextOverflowParseErrorOwned {
340
    InvalidValue(AzString),
341
}
342

            
343
impl StyleTextOverflowParseError<'_> {
344
    /// Converts the borrowed error into an owned error.
345
    #[must_use]
346
1
    pub fn to_contained(&self) -> StyleTextOverflowParseErrorOwned {
347
1
        match self {
348
1
            StyleTextOverflowParseError::InvalidValue(s) => {
349
1
                StyleTextOverflowParseErrorOwned::InvalidValue((*s).to_string().into())
350
            }
351
        }
352
1
    }
353
}
354

            
355
impl StyleTextOverflowParseErrorOwned {
356
    /// Converts the owned error back into a borrowed error.
357
    #[must_use]
358
1
    pub fn to_shared(&self) -> StyleTextOverflowParseError<'_> {
359
1
        match self {
360
1
            Self::InvalidValue(s) => StyleTextOverflowParseError::InvalidValue(s.as_str()),
361
        }
362
1
    }
363
}
364

            
365
#[cfg(feature = "parser")]
366
/// Parses a `StyleTextOverflow` from a string slice.
367
/// # Errors
368
///
369
/// Returns an error if `input` is not a valid CSS `text-overflow` value.
370
39
pub fn parse_style_text_overflow(
371
39
    input: &str,
372
39
) -> Result<StyleTextOverflow, StyleTextOverflowParseError<'_>> {
373
39
    match input.trim() {
374
39
        "clip" => Ok(StyleTextOverflow::Clip),
375
37
        "ellipsis" => Ok(StyleTextOverflow::Ellipsis),
376
5
        other => Err(StyleTextOverflowParseError::InvalidValue(other)),
377
    }
378
39
}
379

            
380
// -- VisualBox --
381

            
382
// +spec:overflow:f6955f - box edge origin for overflow-clip-margin
383
/// Represents the `<visual-box>` value used as the overflow clip edge origin.
384
///
385
/// Specifies which box edge to use as the starting point for the clip region.
386
/// Defaults to `padding-box` per CSS Overflow Module Level 3.
387
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
388
#[repr(C)]
389
pub enum VisualBox {
390
    /// Clip edge starts at the content box edge.
391
    ContentBox,
392
    /// Clip edge starts at the padding box edge (default).
393
    #[default]
394
    PaddingBox,
395
    /// Clip edge starts at the border box edge.
396
    BorderBox,
397
}
398

            
399
impl PrintAsCssValue for VisualBox {
400
23
    fn print_as_css_value(&self) -> String {
401
23
        String::from(match self {
402
8
            Self::ContentBox => "content-box",
403
9
            Self::PaddingBox => "padding-box",
404
6
            Self::BorderBox => "border-box",
405
        })
406
23
    }
407
}
408

            
409
// -- StyleOverflowClipMargin --
410

            
411
/// Represents the `overflow-clip-margin` CSS property.
412
///
413
/// Determines how far outside the element's box the content may paint
414
/// before being clipped when `overflow: clip` is used.
415
/// Syntax: `<visual-box> || <length [0,∞]>`
416
// +spec:overflow:455786 - overflow-clip-margin has no effect on hidden/scroll, only on clip
417
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
418
#[repr(C)]
419
pub struct StyleOverflowClipMargin {
420
    /// The box edge to use as the clip origin (content-box, padding-box, or border-box).
421
    pub clip_edge: VisualBox,
422
    /// The clip margin distance beyond the clip edge.
423
    pub inner: crate::props::basic::pixel::PixelValue,
424
}
425

            
426
impl PrintAsCssValue for StyleOverflowClipMargin {
427
20
    fn print_as_css_value(&self) -> String {
428
20
        let edge = self.clip_edge.print_as_css_value();
429
20
        let len = self.inner.print_as_css_value();
430
        #[allow(clippy::float_cmp)] // exact zero check: value is default-initialized, not computed
431
20
        if self.inner.number.get() == 0.0 {
432
4
            edge
433
16
        } else if self.clip_edge == VisualBox::PaddingBox {
434
6
            len
435
        } else {
436
10
            format!("{edge} {len}")
437
        }
438
20
    }
439
}
440

            
441
/// Error returned when parsing an `overflow-clip-margin` property fails.
442
#[derive(Clone, PartialEq, Eq)]
443
pub enum StyleOverflowClipMarginParseError<'a> {
444
    /// The provided value is not a valid `overflow-clip-margin` value.
445
    InvalidValue(&'a str),
446
}
447

            
448
impl_debug_as_display!(StyleOverflowClipMarginParseError<'a>);
449
impl_display! { StyleOverflowClipMarginParseError<'a>, {
450
    InvalidValue(val) => format!("Invalid overflow-clip-margin value: \"{}\"", val),
451
}}
452

            
453
/// An owned version of `StyleOverflowClipMarginParseError`.
454
#[derive(Debug, Clone, PartialEq, Eq)]
455
#[repr(C, u8)]
456
pub enum StyleOverflowClipMarginParseErrorOwned {
457
    InvalidValue(AzString),
458
}
459

            
460
impl StyleOverflowClipMarginParseError<'_> {
461
    /// Converts the borrowed error into an owned error.
462
    #[must_use]
463
15
    pub fn to_contained(&self) -> StyleOverflowClipMarginParseErrorOwned {
464
15
        match self {
465
15
            StyleOverflowClipMarginParseError::InvalidValue(s) => {
466
15
                StyleOverflowClipMarginParseErrorOwned::InvalidValue((*s).to_string().into())
467
            }
468
        }
469
15
    }
470
}
471

            
472
impl StyleOverflowClipMarginParseErrorOwned {
473
    /// Converts the owned error back into a borrowed error.
474
    #[must_use]
475
15
    pub fn to_shared(&self) -> StyleOverflowClipMarginParseError<'_> {
476
15
        match self {
477
15
            Self::InvalidValue(s) => StyleOverflowClipMarginParseError::InvalidValue(s.as_str()),
478
        }
479
15
    }
480
}
481

            
482
#[cfg(feature = "parser")]
483
/// Parses a `StyleOverflowClipMargin` from a string slice.
484
///
485
/// Syntax: `<visual-box> || <length [0,∞]>`
486
/// The `<visual-box>` defaults to `padding-box` if omitted.
487
/// The `<length>` defaults to `0px` if omitted.
488
/// # Errors
489
///
490
/// Returns an error if `input` is not a valid CSS `overflow-clip-margin` value.
491
57
pub fn parse_style_overflow_clip_margin(
492
57
    input: &str,
493
57
) -> Result<StyleOverflowClipMargin, StyleOverflowClipMarginParseError<'_>> {
494
    use crate::props::basic::pixel::parse_pixel_value;
495

            
496
57
    let input_trimmed = input.trim();
497
57
    let mut clip_edge = None;
498
57
    let mut length = None;
499

            
500
76
    for token in input_trimmed.split_whitespace() {
501
52
        match token {
502
76
            "content-box" if clip_edge.is_none() => clip_edge = Some(VisualBox::ContentBox),
503
61
            "padding-box" if clip_edge.is_none() => clip_edge = Some(VisualBox::PaddingBox),
504
58
            "border-box" if clip_edge.is_none() => clip_edge = Some(VisualBox::BorderBox),
505
52
            _ if length.is_none() => match parse_pixel_value(token) {
506
31
                Ok(pv) => length = Some(pv),
507
17
                Err(_) => return Err(StyleOverflowClipMarginParseError::InvalidValue(input)),
508
            },
509
4
            _ => return Err(StyleOverflowClipMarginParseError::InvalidValue(input)),
510
        }
511
    }
512

            
513
36
    if clip_edge.is_none() && length.is_none() {
514
3
        return Err(StyleOverflowClipMarginParseError::InvalidValue(input));
515
33
    }
516

            
517
33
    Ok(StyleOverflowClipMargin {
518
33
        clip_edge: clip_edge.unwrap_or_default(),
519
33
        inner: length.unwrap_or_default(),
520
33
    })
521
57
}
522

            
523
// -- StyleClipRect --
524

            
525
/// Represents the deprecated CSS `clip` property value `rect(top, right, bottom, left)`.
526
///
527
/// Each edge can be a length or `auto`. When `auto`, the edge matches the
528
/// element's generated border box edge:
529
/// - `auto` for top/left = 0
530
/// - `auto` for bottom = used height + vertical padding + vertical border
531
/// - `auto` for right = used width + horizontal padding + horizontal border
532
///
533
/// Negative lengths are permitted.
534
// +spec:overflow:297dc3 - clip rect() auto values resolve to border box edges
535
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
536
#[repr(C)]
537
pub struct StyleClipRect {
538
    /// Top edge offset in pixels. `None` means `auto` (= 0).
539
    pub top: OptionF32,
540
    /// Right edge offset in pixels. `None` means `auto` (= used width + horiz padding + horiz
541
    /// border).
542
    pub right: OptionF32,
543
    /// Bottom edge offset in pixels. `None` means `auto` (= used height + vert padding + vert
544
    /// border).
545
    pub bottom: OptionF32,
546
    /// Left edge offset in pixels. `None` means `auto` (= 0).
547
    pub left: OptionF32,
548
}
549

            
550
impl StyleClipRect {
551
    /// Resolves `auto` values to border box edges given the element's
552
    /// used width/height and padding/border sizes.
553
    ///
554
    /// Returns `(top, right, bottom, left)` in pixels.
555
    #[must_use]
556
12
    pub fn resolve(
557
12
        &self,
558
12
        used_width: f32,
559
12
        used_height: f32,
560
12
        padding_left: f32,
561
12
        padding_right: f32,
562
12
        padding_top: f32,
563
12
        padding_bottom: f32,
564
12
        border_left: f32,
565
12
        border_right: f32,
566
12
        border_top: f32,
567
12
        border_bottom: f32,
568
12
    ) -> (f32, f32, f32, f32) {
569
12
        let top = self.top.into_option().unwrap_or(0.0);
570
12
        let left = self.left.into_option().unwrap_or(0.0);
571
12
        let bottom = self
572
12
            .bottom
573
12
            .into_option()
574
12
            .unwrap_or(used_height + padding_top + padding_bottom + border_top + border_bottom);
575
12
        let right = self
576
12
            .right
577
12
            .into_option()
578
12
            .unwrap_or(used_width + padding_left + padding_right + border_left + border_right);
579
12
        (top, right, bottom, left)
580
12
    }
581
}
582

            
583
impl PrintAsCssValue for StyleClipRect {
584
5
    fn print_as_css_value(&self) -> String {
585
20
        fn fmt_edge(o: OptionF32) -> String {
586
20
            o.into_option()
587
20
                .map_or_else(|| String::from("auto"), |v| format!("{v}px"))
588
20
        }
589
5
        format!(
590
5
            "rect({}, {}, {}, {})",
591
5
            fmt_edge(self.top),
592
5
            fmt_edge(self.right),
593
5
            fmt_edge(self.bottom),
594
5
            fmt_edge(self.left)
595
        )
596
5
    }
597
}
598

            
599
// -- Parser for StyleClipRect
600

            
601
/// Error returned when parsing a CSS `clip` property value fails.
602
#[derive(Clone, PartialEq, Eq)]
603
pub enum StyleClipRectParseError<'a> {
604
    /// The provided value is not a valid `clip` value.
605
    InvalidValue(&'a str),
606
}
607

            
608
impl_debug_as_display!(StyleClipRectParseError<'a>);
609
impl_display! { StyleClipRectParseError<'a>, {
610
    InvalidValue(val) => format!(
611
        "Invalid clip value: \"{}\". Expected 'auto' or 'rect(<top>, <right>, <bottom>, <left>)'.", val
612
    ),
613
}}
614

            
615
/// An owned version of `StyleClipRectParseError`.
616
#[derive(Debug, Clone, PartialEq, Eq)]
617
#[repr(C, u8)]
618
pub enum StyleClipRectParseErrorOwned {
619
    InvalidValue(AzString),
620
}
621

            
622
impl StyleClipRectParseError<'_> {
623
    /// Converts the borrowed error into an owned error.
624
    #[must_use]
625
15
    pub fn to_contained(&self) -> StyleClipRectParseErrorOwned {
626
15
        match self {
627
15
            StyleClipRectParseError::InvalidValue(s) => {
628
15
                StyleClipRectParseErrorOwned::InvalidValue((*s).to_string().into())
629
            }
630
        }
631
15
    }
632
}
633

            
634
impl StyleClipRectParseErrorOwned {
635
    /// Converts the owned error back into a borrowed error.
636
    #[must_use]
637
15
    pub fn to_shared(&self) -> StyleClipRectParseError<'_> {
638
15
        match self {
639
15
            Self::InvalidValue(s) => StyleClipRectParseError::InvalidValue(s.as_str()),
640
        }
641
15
    }
642
}
643

            
644
#[cfg(feature = "parser")]
645
133
fn parse_clip_edge(token: &str) -> Result<OptionF32, StyleClipRectParseError<'_>> {
646
    use crate::props::basic::pixel::parse_pixel_value;
647

            
648
133
    let token = token.trim();
649
133
    if token.eq_ignore_ascii_case("auto") {
650
52
        return Ok(OptionF32::None);
651
81
    }
652
81
    let pv = parse_pixel_value(token).map_err(|_| StyleClipRectParseError::InvalidValue(token))?;
653
52
    Ok(OptionF32::Some(pv.number.get()))
654
133
}
655

            
656
#[cfg(feature = "parser")]
657
/// Parses a `StyleClipRect` from a string slice.
658
///
659
/// Accepts:
660
/// - `auto` — equivalent to `rect(auto, auto, auto, auto)`.
661
/// - `rect(<top>, <right>, <bottom>, <left>)` — comma-separated form.
662
/// - `rect(<top> <right> <bottom> <left>)` — legacy space-separated form.
663
///
664
/// Each edge is either `auto` or a `<length>`. Negative lengths are permitted.
665
/// # Errors
666
///
667
/// Returns an error if `input` is not a valid CSS `clip-rect` value.
668
66
pub fn parse_clip_rect(input: &str) -> Result<StyleClipRect, StyleClipRectParseError<'_>> {
669
66
    let trimmed = input.trim();
670

            
671
66
    if trimmed.eq_ignore_ascii_case("auto") {
672
5
        return Ok(StyleClipRect::default());
673
61
    }
674

            
675
61
    let inner = trimmed
676
61
        .strip_prefix("rect(")
677
61
        .or_else(|| trimmed.strip_prefix("RECT("))
678
61
        .and_then(|s| s.strip_suffix(')'))
679
61
        .ok_or(StyleClipRectParseError::InvalidValue(input))?;
680

            
681
40
    let inner = inner.trim();
682
40
    let parts: Vec<&str> = if inner.contains(',') {
683
31
        inner.split(',').map(str::trim).collect()
684
    } else {
685
9
        inner.split_whitespace().collect()
686
    };
687

            
688
40
    if parts.len() != 4 {
689
13
        return Err(StyleClipRectParseError::InvalidValue(input));
690
27
    }
691

            
692
    Ok(StyleClipRect {
693
27
        top: parse_clip_edge(parts[0])?,
694
21
        right: parse_clip_edge(parts[1])?,
695
19
        bottom: parse_clip_edge(parts[2])?,
696
19
        left: parse_clip_edge(parts[3])?,
697
    })
698
66
}
699

            
700
#[cfg(all(test, feature = "parser"))]
701
mod tests {
702
    use super::*;
703

            
704
    #[test]
705
1
    fn test_parse_layout_overflow_valid() {
706
1
        assert_eq!(
707
1
            parse_layout_overflow("visible").unwrap(),
708
            LayoutOverflow::Visible
709
        );
710
1
        assert_eq!(
711
1
            parse_layout_overflow("hidden").unwrap(),
712
            LayoutOverflow::Hidden
713
        );
714
1
        assert_eq!(parse_layout_overflow("clip").unwrap(), LayoutOverflow::Clip);
715
1
        assert_eq!(
716
1
            parse_layout_overflow("scroll").unwrap(),
717
            LayoutOverflow::Scroll
718
        );
719
1
        assert_eq!(parse_layout_overflow("auto").unwrap(), LayoutOverflow::Auto);
720
1
    }
721

            
722
    #[test]
723
1
    fn test_parse_style_text_overflow_valid() {
724
1
        assert_eq!(
725
1
            parse_style_text_overflow("clip").unwrap(),
726
            StyleTextOverflow::Clip
727
        );
728
1
        assert_eq!(
729
1
            parse_style_text_overflow("ellipsis").unwrap(),
730
            StyleTextOverflow::Ellipsis
731
        );
732
        // whitespace is tolerated
733
1
        assert_eq!(
734
1
            parse_style_text_overflow("  ellipsis  ").unwrap(),
735
            StyleTextOverflow::Ellipsis
736
        );
737
        // initial value is `clip`
738
1
        assert_eq!(StyleTextOverflow::default(), StyleTextOverflow::Clip);
739
1
    }
740

            
741
    #[test]
742
1
    fn test_parse_style_text_overflow_invalid() {
743
1
        assert!(parse_style_text_overflow("none").is_err());
744
1
        assert!(parse_style_text_overflow("").is_err());
745
1
        assert!(parse_style_text_overflow("fade").is_err());
746
        // error message names the property and quotes the value
747
1
        let msg = format!("{}", StyleTextOverflowParseError::InvalidValue("fade"));
748
1
        assert!(
749
1
            msg.contains("text-overflow") && msg.contains("fade"),
750
            "{msg}"
751
        );
752
        // owned <-> shared round-trips
753
1
        let e = parse_style_text_overflow("fade").unwrap_err();
754
1
        assert_eq!(e.to_contained().to_shared(), e);
755
1
    }
756

            
757
    #[test]
758
1
    fn test_style_text_overflow_print_round_trip() {
759
2
        for v in [StyleTextOverflow::Clip, StyleTextOverflow::Ellipsis] {
760
2
            let printed = v.print_as_css_value();
761
2
            assert_eq!(parse_style_text_overflow(&printed).unwrap(), v);
762
        }
763
1
    }
764

            
765
    #[test]
766
1
    fn test_parse_layout_overflow_whitespace() {
767
1
        assert_eq!(
768
1
            parse_layout_overflow("  scroll  ").unwrap(),
769
            LayoutOverflow::Scroll
770
        );
771
1
    }
772

            
773
    #[test]
774
1
    fn test_parse_layout_overflow_invalid() {
775
1
        assert!(parse_layout_overflow("none").is_err());
776
1
        assert!(parse_layout_overflow("").is_err());
777
1
        assert!(parse_layout_overflow("auto scroll").is_err());
778
1
        assert!(parse_layout_overflow("hidden-x").is_err());
779
1
    }
780

            
781
    #[test]
782
1
    fn test_needs_scrollbar() {
783
1
        assert!(LayoutOverflow::Scroll.needs_scrollbar(false));
784
1
        assert!(LayoutOverflow::Scroll.needs_scrollbar(true));
785
1
        assert!(LayoutOverflow::Auto.needs_scrollbar(true));
786
1
        assert!(!LayoutOverflow::Auto.needs_scrollbar(false));
787
1
        assert!(!LayoutOverflow::Hidden.needs_scrollbar(true));
788
1
        assert!(!LayoutOverflow::Visible.needs_scrollbar(true));
789
1
        assert!(!LayoutOverflow::Clip.needs_scrollbar(true));
790
1
    }
791

            
792
    #[test]
793
1
    fn test_parse_clip_rect_auto_keyword() {
794
1
        let r = parse_clip_rect("auto").unwrap();
795
1
        assert_eq!(r.top, OptionF32::None);
796
1
        assert_eq!(r.right, OptionF32::None);
797
1
        assert_eq!(r.bottom, OptionF32::None);
798
1
        assert_eq!(r.left, OptionF32::None);
799
1
    }
800

            
801
    #[test]
802
1
    fn test_parse_clip_rect_all_auto_in_rect() {
803
1
        let r = parse_clip_rect("rect(auto, auto, auto, auto)").unwrap();
804
1
        assert_eq!(r.top, OptionF32::None);
805
1
        assert_eq!(r.right, OptionF32::None);
806
1
        assert_eq!(r.bottom, OptionF32::None);
807
1
        assert_eq!(r.left, OptionF32::None);
808
1
    }
809

            
810
    #[test]
811
1
    fn test_parse_clip_rect_mixed_auto_and_lengths() {
812
1
        let r = parse_clip_rect("rect(10px, auto, 30px, auto)").unwrap();
813
1
        assert_eq!(r.top, OptionF32::Some(10.0));
814
1
        assert_eq!(r.right, OptionF32::None);
815
1
        assert_eq!(r.bottom, OptionF32::Some(30.0));
816
1
        assert_eq!(r.left, OptionF32::None);
817
1
    }
818

            
819
    #[test]
820
1
    fn test_parse_clip_rect_negative_lengths() {
821
1
        let r = parse_clip_rect("rect(-5px, 0px, -10px, 0px)").unwrap();
822
1
        assert_eq!(r.top, OptionF32::Some(-5.0));
823
1
        assert_eq!(r.right, OptionF32::Some(0.0));
824
1
        assert_eq!(r.bottom, OptionF32::Some(-10.0));
825
1
        assert_eq!(r.left, OptionF32::Some(0.0));
826
1
    }
827

            
828
    #[test]
829
1
    fn test_parse_clip_rect_legacy_space_separated() {
830
        // Legacy CSS 2.1 syntax used spaces instead of commas.
831
1
        let r = parse_clip_rect("rect(1px 2px 3px 4px)").unwrap();
832
1
        assert_eq!(r.top, OptionF32::Some(1.0));
833
1
        assert_eq!(r.right, OptionF32::Some(2.0));
834
1
        assert_eq!(r.bottom, OptionF32::Some(3.0));
835
1
        assert_eq!(r.left, OptionF32::Some(4.0));
836
1
    }
837

            
838
    #[test]
839
1
    fn test_parse_clip_rect_malformed() {
840
1
        assert!(parse_clip_rect("").is_err());
841
1
        assert!(parse_clip_rect("none").is_err());
842
        // Wrong number of edges.
843
1
        assert!(parse_clip_rect("rect(10px, 20px, 30px)").is_err());
844
        // Missing closing paren.
845
1
        assert!(parse_clip_rect("rect(10px, 20px, 30px, 40px").is_err());
846
        // Garbage edge.
847
1
        assert!(parse_clip_rect("rect(10px, abc, 30px, 40px)").is_err());
848
1
    }
849
}
850

            
851
#[cfg(all(test, feature = "parser"))]
852
mod autotest_generated {
853
    use super::*;
854
    use crate::props::basic::{length::SizeMetric, pixel::PixelValue};
855

            
856
    // ---------------------------------------------------------------------
857
    // Variant tables. Each is kept honest by an exhaustive `match` below:
858
    // adding a variant to the enum stops the index fn from compiling.
859
    // ---------------------------------------------------------------------
860

            
861
    const ALL_OVERFLOW: [LayoutOverflow; 5] = [
862
        LayoutOverflow::Scroll,
863
        LayoutOverflow::Auto,
864
        LayoutOverflow::Hidden,
865
        LayoutOverflow::Visible,
866
        LayoutOverflow::Clip,
867
    ];
868

            
869
    const fn overflow_variant_index(o: LayoutOverflow) -> usize {
870
        match o {
871
            LayoutOverflow::Scroll => 0,
872
            LayoutOverflow::Auto => 1,
873
            LayoutOverflow::Hidden => 2,
874
            LayoutOverflow::Visible => 3,
875
            LayoutOverflow::Clip => 4,
876
        }
877
    }
878

            
879
    const ALL_GUTTER: [StyleScrollbarGutter; 3] = [
880
        StyleScrollbarGutter::Auto,
881
        StyleScrollbarGutter::Stable,
882
        StyleScrollbarGutter::StableBothEdges,
883
    ];
884

            
885
    const fn gutter_variant_index(g: StyleScrollbarGutter) -> usize {
886
        match g {
887
            StyleScrollbarGutter::Auto => 0,
888
            StyleScrollbarGutter::Stable => 1,
889
            StyleScrollbarGutter::StableBothEdges => 2,
890
        }
891
    }
892

            
893
    const ALL_VISUAL_BOX: [VisualBox; 3] = [
894
        VisualBox::ContentBox,
895
        VisualBox::PaddingBox,
896
        VisualBox::BorderBox,
897
    ];
898

            
899
    const fn visual_box_variant_index(v: VisualBox) -> usize {
900
        match v {
901
            VisualBox::ContentBox => 0,
902
            VisualBox::PaddingBox => 1,
903
            VisualBox::BorderBox => 2,
904
        }
905
    }
906

            
907
    /// A value is "scrollable" (per CSS Overflow 3 § 3.1) when it is neither
908
    /// `visible` nor `clip` — i.e. it establishes a scroll container.
909
    const fn is_scrollable(o: LayoutOverflow) -> bool {
910
        !matches!(o, LayoutOverflow::Visible | LayoutOverflow::Clip)
911
    }
912

            
913
    #[test]
914
    fn variant_tables_cover_every_variant_exactly_once() {
915
        for (i, o) in ALL_OVERFLOW.iter().enumerate() {
916
            assert_eq!(overflow_variant_index(*o), i);
917
        }
918
        for (i, g) in ALL_GUTTER.iter().enumerate() {
919
            assert_eq!(gutter_variant_index(*g), i);
920
        }
921
        for (i, v) in ALL_VISUAL_BOX.iter().enumerate() {
922
            assert_eq!(visual_box_variant_index(*v), i);
923
        }
924
    }
925

            
926
    // ---------------------------------------------------------------------
927
    // LayoutOverflow — predicates & invariants
928
    // ---------------------------------------------------------------------
929

            
930
    #[test]
931
    fn needs_scrollbar_truth_table_is_monotone_in_currently_overflowing() {
932
        for o in ALL_OVERFLOW {
933
            let idle = o.needs_scrollbar(false);
934
            let overflowing = o.needs_scrollbar(true);
935

            
936
            // A scrollbar that is shown while *not* overflowing must also be
937
            // shown while overflowing — the flag can only ever add scrollbars.
938
            assert!(
939
                !idle || overflowing,
940
                "{o:?} shows a scrollbar when idle but hides it when overflowing"
941
            );
942

            
943
            // Only `scroll` shows a scrollbar unconditionally; only `auto`
944
            // reacts to the flag; nothing else ever shows one.
945
            let (expect_idle, expect_overflowing) = match o {
946
                LayoutOverflow::Scroll => (true, true),
947
                LayoutOverflow::Auto => (false, true),
948
                LayoutOverflow::Hidden | LayoutOverflow::Visible | LayoutOverflow::Clip => {
949
                    (false, false)
950
                }
951
            };
952
            assert_eq!(idle, expect_idle, "needs_scrollbar(false) wrong for {o:?}");
953
            assert_eq!(
954
                overflowing, expect_overflowing,
955
                "needs_scrollbar(true) wrong for {o:?}"
956
            );
957

            
958
            // Anything that can show a scrollbar must also clip.
959
            assert!(!overflowing || o.is_clipped());
960
        }
961
    }
962

            
963
    #[test]
964
    fn is_clipped_is_exactly_the_negation_of_is_overflow_visible() {
965
        for o in ALL_OVERFLOW {
966
            assert_eq!(
967
                o.is_clipped(),
968
                !o.is_overflow_visible(),
969
                "is_clipped/is_overflow_visible disagree for {o:?}"
970
            );
971
            // Deterministic: repeated calls on the same value never differ.
972
            assert_eq!(o.is_clipped(), o.is_clipped());
973
        }
974
        assert!(!LayoutOverflow::Visible.is_clipped());
975
        assert!(LayoutOverflow::Hidden.is_clipped());
976
    }
977

            
978
    #[test]
979
    fn is_scroll_and_is_overflow_hidden_match_exactly_one_variant_each() {
980
        let scrolls: Vec<LayoutOverflow> = ALL_OVERFLOW
981
            .into_iter()
982
            .filter(LayoutOverflow::is_scroll)
983
            .collect();
984
        assert_eq!(scrolls, vec![LayoutOverflow::Scroll]);
985

            
986
        let hiddens: Vec<LayoutOverflow> = ALL_OVERFLOW
987
            .into_iter()
988
            .filter(LayoutOverflow::is_overflow_hidden)
989
            .collect();
990
        assert_eq!(hiddens, vec![LayoutOverflow::Hidden]);
991

            
992
        // `auto` is not `scroll`, even though both can produce a scrollbar.
993
        assert!(!LayoutOverflow::Auto.is_scroll());
994
        assert!(LayoutOverflow::Auto.needs_scrollbar(true));
995
    }
996

            
997
    #[test]
998
    fn default_overflow_is_visible_and_neither_clips_nor_scrolls() {
999
        let d = LayoutOverflow::default();
        assert_eq!(d, LayoutOverflow::Visible);
        assert!(d.is_overflow_visible());
        assert!(!d.is_clipped());
        assert!(!d.is_scroll());
        assert!(!d.is_overflow_hidden());
        assert!(!d.needs_scrollbar(false));
        assert!(!d.needs_scrollbar(true));
    }
    // ---------------------------------------------------------------------
    // LayoutOverflow::resolve_computed — CSS Overflow 3 § 3.1
    // ---------------------------------------------------------------------
    #[test]
    fn resolve_computed_is_identity_when_the_other_axis_is_not_scrollable() {
        for other in [LayoutOverflow::Visible, LayoutOverflow::Clip] {
            for o in ALL_OVERFLOW {
                assert_eq!(
                    o.resolve_computed(other),
                    o,
                    "{o:?} must be untouched when the other axis is {other:?}"
                );
            }
        }
    }
    #[test]
    fn resolve_computed_promotes_visible_to_auto_and_clip_to_hidden() {
        for other in [
            LayoutOverflow::Scroll,
            LayoutOverflow::Auto,
            LayoutOverflow::Hidden,
        ] {
            assert_eq!(
                LayoutOverflow::Visible.resolve_computed(other),
                LayoutOverflow::Auto
            );
            assert_eq!(
                LayoutOverflow::Clip.resolve_computed(other),
                LayoutOverflow::Hidden
            );
            // Already-scrollable values are left alone.
            for o in [
                LayoutOverflow::Scroll,
                LayoutOverflow::Auto,
                LayoutOverflow::Hidden,
            ] {
                assert_eq!(o.resolve_computed(other), o);
            }
        }
    }
    #[test]
    fn resolve_computed_is_idempotent_and_never_removes_clipping() {
        for o in ALL_OVERFLOW {
            for other in ALL_OVERFLOW {
                let once = o.resolve_computed(other);
                assert_eq!(
                    once.resolve_computed(other),
                    once,
                    "resolve_computed not idempotent for ({o:?}, {other:?})"
                );
                // Resolution only ever adds clipping, never takes it away.
                assert!(
                    !o.is_clipped() || once.is_clipped(),
                    "({o:?}, {other:?}) lost clipping"
                );
                // ...and never turns a scroll container back into a non-scroller.
                assert!(!is_scrollable(o) || is_scrollable(once));
            }
        }
    }
    #[test]
    fn resolve_computed_leaves_both_axes_consistently_scrollable() {
        // The whole point of the rule: after resolving *both* axes against each
        // other you can never end up with one scrollable axis and one that is
        // still visible/clip (which would be unrenderable).
        for x in ALL_OVERFLOW {
            for y in ALL_OVERFLOW {
                let rx = x.resolve_computed(y);
                let ry = y.resolve_computed(x);
                assert_eq!(
                    is_scrollable(rx),
                    is_scrollable(ry),
                    "({x:?}, {y:?}) resolved to the mismatched pair ({rx:?}, {ry:?})"
                );
            }
        }
        // Spot-check the documented pairs.
        assert_eq!(
            LayoutOverflow::Visible.resolve_computed(LayoutOverflow::Scroll),
            LayoutOverflow::Auto
        );
        assert_eq!(
            LayoutOverflow::Scroll.resolve_computed(LayoutOverflow::Visible),
            LayoutOverflow::Scroll
        );
        // visible + clip is a legal pair and must survive untouched.
        assert_eq!(
            LayoutOverflow::Visible.resolve_computed(LayoutOverflow::Clip),
            LayoutOverflow::Visible
        );
        assert_eq!(
            LayoutOverflow::Clip.resolve_computed(LayoutOverflow::Visible),
            LayoutOverflow::Clip
        );
    }
    // ---------------------------------------------------------------------
    // parse_layout_overflow
    // ---------------------------------------------------------------------
    #[test]
    fn layout_overflow_round_trips_through_print_as_css_value() {
        for o in ALL_OVERFLOW {
            let printed = o.print_as_css_value();
            assert_eq!(
                parse_layout_overflow(&printed).unwrap(),
                o,
                "{o:?} printed as {printed:?} did not round-trip"
            );
            // The printed form is a bare keyword: no whitespace, all lowercase.
            assert!(!printed.is_empty());
            assert!(!printed.contains(char::is_whitespace));
            assert_eq!(printed, printed.to_lowercase());
        }
    }
    #[test]
    fn parse_layout_overflow_treats_overlay_as_a_one_way_alias_of_auto() {
        // "overlay" is a legacy alias that parses to Auto but is never printed,
        // so the round-trip is stable only after the first normalisation.
        assert_eq!(
            parse_layout_overflow("overlay").unwrap(),
            LayoutOverflow::Auto
        );
        let normalised = parse_layout_overflow("overlay")
            .unwrap()
            .print_as_css_value();
        assert_eq!(normalised, "auto");
        assert_eq!(
            parse_layout_overflow(&normalised).unwrap(),
            LayoutOverflow::Auto
        );
        for o in ALL_OVERFLOW {
            assert_ne!(o.print_as_css_value(), "overlay");
        }
    }
    #[test]
    fn parse_layout_overflow_rejects_empty_and_whitespace_only_input() {
        for input in ["", " ", "   ", "\t", "\n", "\r\n", "\t \n \r", "\u{00A0}"] {
            assert!(
                parse_layout_overflow(input).is_err(),
                "{input:?} must not parse"
            );
        }
    }
    #[test]
    fn parse_layout_overflow_error_carries_the_untrimmed_input() {
        // The parser trims for matching but reports the *original* slice.
        let err = parse_layout_overflow("  bogus  ").unwrap_err();
        assert_eq!(err, LayoutOverflowParseError::InvalidValue("  bogus  "));
        let msg = format!("{err}");
        assert!(msg.contains("bogus"), "{msg}");
        assert!(
            msg.contains("scroll"),
            "error should list the valid keywords: {msg}"
        );
    }
    #[test]
    fn parse_layout_overflow_is_ascii_case_sensitive() {
        // NOTE: CSS keywords are ASCII case-insensitive, but this parser only
        // accepts the lowercase spelling (property *names* are lowercased
        // upstream, values are not). Characterised here so a future fix has to
        // update the test deliberately.
        for input in [
            "SCROLL", "Scroll", "sCrOlL", "AUTO", "Hidden", "VISIBLE", "Clip",
        ] {
            assert!(
                parse_layout_overflow(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
        assert_eq!(
            parse_layout_overflow("scroll").unwrap(),
            LayoutOverflow::Scroll
        );
    }
    #[test]
    fn parse_layout_overflow_trims_unicode_whitespace_but_not_zero_width_chars() {
        // `str::trim` uses the Unicode White_Space property, which is wider than
        // CSS whitespace: NBSP and the ideographic space are stripped too.
        assert_eq!(
            parse_layout_overflow("\u{00A0}scroll\u{00A0}").unwrap(),
            LayoutOverflow::Scroll
        );
        assert_eq!(
            parse_layout_overflow("\u{3000}auto").unwrap(),
            LayoutOverflow::Auto
        );
        // ...but a zero-width space is not whitespace, so it stays and rejects.
        assert!(parse_layout_overflow("\u{200B}scroll").is_err());
        assert!(parse_layout_overflow("scroll\u{FEFF}").is_err());
    }
    #[test]
    fn parse_layout_overflow_rejects_garbage_unicode_and_boundary_numbers() {
        for input in [
            "none",
            "hidden-x",
            "auto scroll",
            "scroll;",
            "scroll garbage",
            "visible !important",
            "\0",
            "scroll\0",
            "!@#$%^&*()",
            "\u{1F600}",
            "scroll\u{1F600}",
            "e\u{0301}",
            "scroll",
            "скролл",
            "0",
            "-0",
            "0.0",
            "NaN",
            "nan",
            "inf",
            "-inf",
            "infinity",
            "9223372036854775807",
            "-9223372036854775808",
            "1e400",
            "1e-400",
        ] {
            assert!(
                parse_layout_overflow(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
    }
    #[test]
    fn parse_layout_overflow_survives_extremely_long_and_deeply_nested_input() {
        let long = "scroll".repeat(200_000);
        assert!(parse_layout_overflow(&long).is_err());
        let junk = "a".repeat(1_000_000);
        assert!(parse_layout_overflow(&junk).is_err());
        let nested = format!("{}{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(parse_layout_overflow(&nested).is_err());
        // A valid keyword buried in megabytes of padding is still just padding.
        let padded = format!("{}scroll{}", " ".repeat(500_000), " ".repeat(500_000));
        assert_eq!(
            parse_layout_overflow(&padded).unwrap(),
            LayoutOverflow::Scroll
        );
    }
    // ---------------------------------------------------------------------
    // parse_style_scrollbar_gutter
    // ---------------------------------------------------------------------
    #[test]
    fn scrollbar_gutter_round_trips_through_print_as_css_value() {
        for g in ALL_GUTTER {
            let printed = g.print_as_css_value();
            assert_eq!(
                parse_style_scrollbar_gutter(&printed).unwrap(),
                g,
                "{g:?} printed as {printed:?} did not round-trip"
            );
        }
        assert_eq!(
            StyleScrollbarGutter::StableBothEdges.print_as_css_value(),
            "stable both-edges"
        );
        assert_eq!(StyleScrollbarGutter::default(), StyleScrollbarGutter::Auto);
    }
    #[test]
    fn parse_style_scrollbar_gutter_matches_the_keyword_string_verbatim() {
        // The parser compares the whole trimmed string, so it accepts exactly
        // one ASCII space between `stable` and `both-edges`. Per the grammar
        // (`auto | stable && both-edges?`) the reversed order and collapsed
        // runs of whitespace should also be legal — characterising the gap.
        assert_eq!(
            parse_style_scrollbar_gutter("stable both-edges").unwrap(),
            StyleScrollbarGutter::StableBothEdges
        );
        for rejected in [
            "stable  both-edges", // two spaces
            "stable\tboth-edges",
            "stable\nboth-edges",
            "both-edges stable", // `&&` allows either order
            "both-edges",
            "STABLE",
            "Stable Both-Edges",
            "stable both-edges stable",
        ] {
            assert!(
                parse_style_scrollbar_gutter(rejected).is_err(),
                "{rejected:?} unexpectedly parsed"
            );
        }
        // Outer whitespace *is* trimmed.
        assert_eq!(
            parse_style_scrollbar_gutter("  stable both-edges \n").unwrap(),
            StyleScrollbarGutter::StableBothEdges
        );
    }
    #[test]
    fn parse_style_scrollbar_gutter_rejects_empty_garbage_unicode_and_numbers() {
        for input in [
            "",
            " ",
            "\t\n",
            "none",
            "auto stable",
            "auto;",
            "stable;",
            "0",
            "-0",
            "NaN",
            "inf",
            "9223372036854775807",
            "\u{1F600}",
            "stable",
            "stable\0",
        ] {
            assert!(
                parse_style_scrollbar_gutter(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
        let err = parse_style_scrollbar_gutter("  nope  ").unwrap_err();
        assert_eq!(
            err,
            StyleScrollbarGutterParseError::InvalidValue("  nope  ")
        );
        assert!(format!("{err}").contains("scrollbar-gutter"));
    }
    #[test]
    fn parse_style_scrollbar_gutter_survives_long_and_nested_input() {
        let long = "stable ".repeat(200_000);
        assert!(parse_style_scrollbar_gutter(&long).is_err());
        let nested = format!("{}{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(parse_style_scrollbar_gutter(&nested).is_err());
    }
    // ---------------------------------------------------------------------
    // parse_style_overflow_clip_margin
    // ---------------------------------------------------------------------
    #[test]
    fn parse_style_overflow_clip_margin_accepts_either_component_in_either_order() {
        // <visual-box> only — length defaults to 0.
        let only_box = parse_style_overflow_clip_margin("content-box").unwrap();
        assert_eq!(only_box.clip_edge, VisualBox::ContentBox);
        assert_eq!(only_box.inner, PixelValue::default());
        // <length> only — box defaults to padding-box.
        let only_len = parse_style_overflow_clip_margin("20px").unwrap();
        assert_eq!(only_len.clip_edge, VisualBox::PaddingBox);
        assert_eq!(only_len.inner, PixelValue::const_px(20));
        // `||` means either order is valid.
        let a = parse_style_overflow_clip_margin("border-box 10px").unwrap();
        let b = parse_style_overflow_clip_margin("10px border-box").unwrap();
        assert_eq!(a, b);
        assert_eq!(a.clip_edge, VisualBox::BorderBox);
        assert_eq!(a.inner, PixelValue::const_px(10));
        // Interior whitespace is collapsed by split_whitespace.
        let c = parse_style_overflow_clip_margin("  border-box \t\n  10px  ").unwrap();
        assert_eq!(c, a);
        assert_eq!(VisualBox::default(), VisualBox::PaddingBox);
    }
    #[test]
    fn parse_style_overflow_clip_margin_rejects_empty_duplicates_and_garbage() {
        for input in [
            "",
            "   ",
            "\t\n",
            "content-box content-box", // duplicate box
            "10px 20px",               // duplicate length
            "content-box 10px 20px",
            "content-box padding-box",
            "content-box 10px border-box",
            "none",
            "auto",
            "margin-box",
            "10px;",
            "10 px extra",
            "px",
            "\u{1F600}",
            "10\u{1F600}",
            "content-box",
            "content_box",
            "CONTENT-BOX",
        ] {
            assert!(
                parse_style_overflow_clip_margin(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
        let err = parse_style_overflow_clip_margin("  nope  ").unwrap_err();
        assert_eq!(
            err,
            StyleOverflowClipMarginParseError::InvalidValue("  nope  ")
        );
        assert!(format!("{err}").contains("overflow-clip-margin"));
    }
    #[test]
    fn parse_style_overflow_clip_margin_accepts_out_of_range_lengths() {
        // The declared syntax is `<visual-box> || <length [0,∞]>`: negatives and
        // percentages are invalid CSS. The parser delegates to parse_pixel_value
        // and clamps nothing, so both are accepted. Characterised, not endorsed.
        let neg = parse_style_overflow_clip_margin("-5px").unwrap();
        assert!(neg.inner.number.get() < 0.0);
        let pct = parse_style_overflow_clip_margin("50%").unwrap();
        assert_eq!(pct.inner.metric, SizeMetric::Percent);
        assert_eq!(pct.inner.number.get(), 50.0);
        // Unitless non-zero numbers are also let through (CSS requires a unit).
        let unitless = parse_style_overflow_clip_margin("7").unwrap();
        assert_eq!(unitless.inner.metric, SizeMetric::Px);
        assert_eq!(unitless.inner.number.get(), 7.0);
    }
    #[test]
    fn parse_style_overflow_clip_margin_saturates_nan_and_infinity() {
        // Rust's f32 parser accepts "NaN"/"inf", so these reach PixelValue.
        // FloatValue stores milli-units in an isize: NaN saturates to 0 and the
        // infinities to the isize bounds — no non-finite value can escape into
        // layout, which is the property that actually matters.
        let nan = parse_style_overflow_clip_margin("NaN").unwrap();
        assert!(!nan.inner.number.get().is_nan());
        assert_eq!(nan.inner.number.get(), 0.0);
        let pos_inf = parse_style_overflow_clip_margin("inf").unwrap();
        assert!(pos_inf.inner.number.get().is_finite());
        assert!(pos_inf.inner.number.get() > 0.0);
        let neg_inf = parse_style_overflow_clip_margin("-inf").unwrap();
        assert!(neg_inf.inner.number.get().is_finite());
        assert!(neg_inf.inner.number.get() < 0.0);
        // A number far beyond f32 range overflows to inf during parsing and
        // then saturates the same way.
        let huge = format!("{}px", "9".repeat(4096));
        let huge = parse_style_overflow_clip_margin(&huge).unwrap();
        assert!(huge.inner.number.get().is_finite());
        // Sub-milli precision is quantised away rather than rounded up.
        let tiny = parse_style_overflow_clip_margin("0.0001px").unwrap();
        assert_eq!(tiny.inner.number.get(), 0.0);
    }
    #[test]
    fn parse_style_overflow_clip_margin_survives_long_and_nested_input() {
        let long_token = format!("{}px", "a".repeat(1_000_000));
        assert!(parse_style_overflow_clip_margin(&long_token).is_err());
        let many_tokens = "content-box ".repeat(100_000);
        assert!(parse_style_overflow_clip_margin(&many_tokens).is_err());
        let nested = format!("{}{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(parse_style_overflow_clip_margin(&nested).is_err());
    }
    #[test]
    fn overflow_clip_margin_round_trips_through_print_as_css_value() {
        let lengths = [
            PixelValue::const_px(12),
            PixelValue::px(1.5),
            PixelValue::const_em(2),
            PixelValue::const_percent(50),
            PixelValue::px(-3.25),
        ];
        for edge in ALL_VISUAL_BOX {
            for inner in lengths {
                let original = StyleOverflowClipMargin {
                    clip_edge: edge,
                    inner,
                };
                let printed = original.print_as_css_value();
                let reparsed = parse_style_overflow_clip_margin(&printed).unwrap_or_else(|e| {
                    panic!("{original:?} printed as {printed:?} but failed to reparse: {e}")
                });
                assert_eq!(reparsed, original, "round-trip broke via {printed:?}");
            }
        }
    }
    #[test]
    fn overflow_clip_margin_zero_length_prints_only_the_box_and_forgets_the_unit() {
        // A zero length is elided from the printed form, so its unit is lost on
        // the way back (0em == 0px semantically, so this is benign — but the
        // struct is *not* preserved bit-for-bit, which a naive round-trip
        // assertion would trip over).
        let zero_em = StyleOverflowClipMargin {
            clip_edge: VisualBox::ContentBox,
            inner: PixelValue::const_em(0),
        };
        assert_eq!(zero_em.print_as_css_value(), "content-box");
        let back = parse_style_overflow_clip_margin(&zero_em.print_as_css_value()).unwrap();
        assert_eq!(back.clip_edge, VisualBox::ContentBox);
        assert_eq!(back.inner.number.get(), 0.0);
        assert_eq!(back.inner.metric, SizeMetric::Px);
        assert_ne!(back, zero_em);
        // The all-default value prints as the bare default box.
        let default = StyleOverflowClipMargin::default();
        assert_eq!(default.print_as_css_value(), "padding-box");
        assert_eq!(
            parse_style_overflow_clip_margin(&default.print_as_css_value()).unwrap(),
            default
        );
        // padding-box + non-zero length prints only the length.
        let padding_len = StyleOverflowClipMargin {
            clip_edge: VisualBox::PaddingBox,
            inner: PixelValue::const_px(4),
        };
        assert_eq!(padding_len.print_as_css_value(), "4px");
    }
    #[test]
    fn visual_box_round_trips_through_the_clip_margin_parser() {
        for v in ALL_VISUAL_BOX {
            let printed = v.print_as_css_value();
            let parsed = parse_style_overflow_clip_margin(&printed).unwrap();
            assert_eq!(parsed.clip_edge, v, "{printed:?} did not round-trip");
        }
    }
    // ---------------------------------------------------------------------
    // parse_clip_edge (private)
    // ---------------------------------------------------------------------
    #[test]
    fn parse_clip_edge_auto_is_ascii_case_insensitive_and_trimmed() {
        for input in ["auto", "AUTO", "Auto", "aUtO", "  auto  ", "\tauto\n"] {
            assert_eq!(
                parse_clip_edge(input).unwrap(),
                OptionF32::None,
                "{input:?} should be auto"
            );
        }
        // ...but only the whole token: `auto` glued to anything else is invalid.
        assert!(parse_clip_edge("auto5").is_err());
        assert!(parse_clip_edge("autopx").is_err());
        assert!(parse_clip_edge("auto auto").is_err());
    }
    #[test]
    fn parse_clip_edge_silently_discards_the_unit() {
        // BUG (characterised): the edge keeps only `PixelValue::number`, so the
        // metric is thrown away — `rect(5em, ...)` is treated as 5 *pixels*, and
        // percentages (invalid for `clip`) are accepted as raw numbers.
        for input in [
            "5px", "5em", "5rem", "5pt", "5in", "5cm", "5mm", "5vw", "5vh", "5%",
        ] {
            assert_eq!(
                parse_clip_edge(input).unwrap(),
                OptionF32::Some(5.0),
                "{input:?} did not collapse to a bare 5.0"
            );
        }
        // A unitless number is accepted as well (CSS requires a unit here).
        assert_eq!(parse_clip_edge("5").unwrap(), OptionF32::Some(5.0));
        // And whitespace between number and unit is tolerated by the pixel parser.
        assert_eq!(parse_clip_edge("5 px").unwrap(), OptionF32::Some(5.0));
    }
    #[test]
    fn parse_clip_edge_quantises_to_thousandths_and_normalises_negative_zero() {
        // FloatValue is a fixed-point isize in milli-units: anything below 1/1000
        // truncates toward zero rather than rounding.
        assert_eq!(parse_clip_edge("0.001px").unwrap(), OptionF32::Some(0.001));
        assert_eq!(parse_clip_edge("0.0001px").unwrap(), OptionF32::Some(0.0));
        assert_eq!(parse_clip_edge("-0.0009px").unwrap(), OptionF32::Some(0.0));
        assert_eq!(parse_clip_edge("1.9999px").unwrap(), OptionF32::Some(1.999));
        // -0 loses its sign, so it can never poison downstream sign checks.
        let minus_zero = parse_clip_edge("-0px").unwrap().into_option().unwrap();
        assert_eq!(minus_zero, 0.0);
        assert!(minus_zero.is_sign_positive());
        // Negative lengths are explicitly legal for `clip`.
        assert_eq!(parse_clip_edge("-10px").unwrap(), OptionF32::Some(-10.0));
    }
    #[test]
    fn parse_clip_edge_saturates_nan_and_infinity_to_finite_values() {
        let nan = parse_clip_edge("NaN").unwrap().into_option().unwrap();
        assert!(!nan.is_nan(), "NaN must not survive into a clip edge");
        assert_eq!(nan, 0.0);
        let pos_inf = parse_clip_edge("inf").unwrap().into_option().unwrap();
        assert!(pos_inf.is_finite());
        assert!(pos_inf > 0.0);
        let neg_inf = parse_clip_edge("-infinity").unwrap().into_option().unwrap();
        assert!(neg_inf.is_finite());
        assert!(neg_inf < 0.0);
        let huge = format!("{}px", "9".repeat(4096));
        let huge = parse_clip_edge(&huge).unwrap().into_option().unwrap();
        assert!(huge.is_finite());
    }
    #[test]
    fn parse_clip_edge_rejects_empty_bare_units_and_garbage() {
        for input in [
            "",
            "   ",
            "\t\n",
            "px",
            "em",
            "%",
            "abc",
            "10px;",
            "10px 20px",
            "(10px)",
            "\0",
            "\u{1F600}",
            "1px",
            "1px\u{0301}",
            "0x10",
        ] {
            assert!(
                parse_clip_edge(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
        // The error carries the *trimmed token*, not the surrounding input.
        assert_eq!(
            parse_clip_edge("  abc  ").unwrap_err(),
            StyleClipRectParseError::InvalidValue("abc")
        );
    }
    // ---------------------------------------------------------------------
    // parse_clip_rect
    // ---------------------------------------------------------------------
    #[test]
    fn clip_rect_round_trips_through_print_as_css_value() {
        let rects = [
            StyleClipRect::default(),
            StyleClipRect {
                top: OptionF32::Some(0.0),
                right: OptionF32::Some(-2.25),
                bottom: OptionF32::Some(1.5),
                left: OptionF32::None,
            },
            StyleClipRect {
                top: OptionF32::Some(10.0),
                right: OptionF32::Some(20.0),
                bottom: OptionF32::Some(30.0),
                left: OptionF32::Some(40.0),
            },
            StyleClipRect {
                top: OptionF32::None,
                right: OptionF32::Some(-1.0),
                bottom: OptionF32::None,
                left: OptionF32::Some(-1.0),
            },
        ];
        for original in rects {
            let printed = original.print_as_css_value();
            let reparsed = parse_clip_rect(&printed).unwrap_or_else(|e| {
                panic!("{original:?} printed as {printed:?} but failed to reparse: {e}")
            });
            assert_eq!(reparsed, original, "round-trip broke via {printed:?}");
        }
        assert_eq!(
            StyleClipRect::default().print_as_css_value(),
            "rect(auto, auto, auto, auto)"
        );
    }
    #[test]
    fn parse_clip_rect_accepts_the_auto_comma_and_legacy_space_forms() {
        let all_auto = StyleClipRect::default();
        for input in [
            "auto",
            "AUTO",
            "  auto  ",
            "\u{00A0}auto", // NBSP is Unicode whitespace, so `trim` eats it
            "rect(auto, auto, auto, auto)",
            "rect(auto auto auto auto)",
            "RECT(auto, auto, auto, auto)",
            "  rect( auto , auto , auto , auto )  ",
        ] {
            assert_eq!(
                parse_clip_rect(input).unwrap(),
                all_auto,
                "{input:?} should be all-auto"
            );
        }
        let mixed = parse_clip_rect("rect(1px, auto, -3px, 4px)").unwrap();
        assert_eq!(mixed.top, OptionF32::Some(1.0));
        assert_eq!(mixed.right, OptionF32::None);
        assert_eq!(mixed.bottom, OptionF32::Some(-3.0));
        assert_eq!(mixed.left, OptionF32::Some(4.0));
        // No space after the commas is fine too.
        assert_eq!(
            parse_clip_rect("rect(1px,2px,3px,4px)").unwrap(),
            StyleClipRect {
                top: OptionF32::Some(1.0),
                right: OptionF32::Some(2.0),
                bottom: OptionF32::Some(3.0),
                left: OptionF32::Some(4.0),
            }
        );
    }
    #[test]
    fn parse_clip_rect_rejects_wrong_arity_mixed_separators_and_trailing_junk() {
        for input in [
            "rect()",
            "rect(,,,)",
            "rect(1px)",
            "rect(1px, 2px, 3px)",
            "rect(1px, 2px, 3px, 4px, 5px)",
            "rect(1px, 2px, 3px, 4px,)",
            "rect(1px 2px, 3px 4px)", // half comma-separated, half not
            "rect(1px 2px 3px)",
            "rect(1px 2px 3px 4px 5px)",
            "rect(1px, 2px, 3px, 4px",   // no closing paren
            "rect 1px, 2px, 3px, 4px)",  // no opening paren
            "rect (1px, 2px, 3px, 4px)", // space before the paren
            "rect(1px, 2px, 3px, 4px) trailing",
            "rect(1px, 2px, 3px, 4px);",
            "junk rect(1px, 2px, 3px, 4px)",
            "rect(auto, auto, auto, abc)",
            "",
            "   ",
            "none",
            "inherit",
            "0",
        ] {
            assert!(
                parse_clip_rect(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
    }
    #[test]
    fn parse_clip_rect_function_name_accepts_only_all_lower_or_all_upper_case() {
        // `rect(` and `RECT(` are special-cased; every mixed casing is rejected,
        // even though CSS function names are ASCII case-insensitive.
        assert!(parse_clip_rect("rect(auto, auto, auto, auto)").is_ok());
        assert!(parse_clip_rect("RECT(auto, auto, auto, auto)").is_ok());
        for input in [
            "Rect(auto, auto, auto, auto)",
            "rECT(auto, auto, auto, auto)",
            "ReCt(auto, auto, auto, auto)",
        ] {
            assert!(
                parse_clip_rect(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
    }
    #[test]
    fn parse_clip_rect_errors_point_at_the_offending_token() {
        // A bad *edge* reports just the token...
        let err = parse_clip_rect("rect(1px, abc, 3px, 4px)").unwrap_err();
        assert_eq!(err, StyleClipRectParseError::InvalidValue("abc"));
        let msg = format!("{err}");
        assert!(msg.contains("abc"), "{msg}");
        // (the message's own "Expected rect(...)" hint aside, none of the *input*
        // apart from the bad token is echoed back)
        assert!(
            !msg.contains("1px"),
            "message leaked the whole input: {msg}"
        );
        // ...while a structural error reports the untrimmed input.
        let err = parse_clip_rect("  rect(1px)  ").unwrap_err();
        assert_eq!(err, StyleClipRectParseError::InvalidValue("  rect(1px)  "));
    }
    #[test]
    fn parse_clip_rect_survives_deep_nesting_and_huge_input() {
        // Not a recursive-descent parser, so nesting cannot blow the stack.
        let nested = format!("{}{}", "rect(".repeat(10_000), ")".repeat(10_000));
        assert!(parse_clip_rect(&nested).is_err());
        let parens = format!("{}{}", "(".repeat(100_000), ")".repeat(100_000));
        assert!(parse_clip_rect(&parens).is_err());
        // 50k edges: rejected on arity, not by hanging.
        let wide = format!("rect({})", "1px,".repeat(50_000));
        assert!(parse_clip_rect(&wide).is_err());
        let long_token = format!("rect({}, auto, auto, auto)", "a".repeat(1_000_000));
        assert!(parse_clip_rect(&long_token).is_err());
        // A legitimately huge magnitude parses and saturates instead of overflowing.
        let huge = format!("rect({}px, auto, auto, auto)", "9".repeat(4096));
        let huge = parse_clip_rect(&huge).unwrap();
        let top = huge.top.into_option().unwrap();
        assert!(top.is_finite());
        assert!(top > 0.0);
    }
    #[test]
    fn parse_clip_rect_does_not_panic_on_multibyte_input() {
        for input in [
            "rect(\u{1F600}, \u{1F600}, \u{1F600}, \u{1F600})",
            "rect(1px\u{0301}, auto, auto, auto)",
            "réct(1px, 2px, 3px, 4px)",
            "rect(1px, auto, auto, auto)", // fullwidth digit
            "rect(1px, auto, auto, auto\u{200B})",
            "\u{1F600}",
            "автo",
            "rect(٣px, auto, auto, auto)", // arabic-indic digit
        ] {
            assert!(
                parse_clip_rect(input).is_err(),
                "{input:?} unexpectedly parsed"
            );
        }
    }
    // ---------------------------------------------------------------------
    // StyleClipRect::resolve
    // ---------------------------------------------------------------------
    #[test]
    fn clip_rect_default_is_all_auto() {
        let d = StyleClipRect::default();
        assert_eq!(d.top, OptionF32::None);
        assert_eq!(d.right, OptionF32::None);
        assert_eq!(d.bottom, OptionF32::None);
        assert_eq!(d.left, OptionF32::None);
    }
    #[test]
    fn clip_rect_resolve_expands_auto_edges_to_the_border_box() {
        // auto: top/left = 0, bottom/right = the border-box extent.
        let (top, right, bottom, left) = StyleClipRect::default().resolve(
            100.0, 50.0, // used width / height
            1.0, 2.0, 3.0, 4.0, // padding l / r / t / b
            5.0, 6.0, 7.0, 8.0, // border  l / r / t / b
        );
        assert_eq!(top, 0.0);
        assert_eq!(left, 0.0);
        assert_eq!(right, 100.0 + 1.0 + 2.0 + 5.0 + 6.0);
        assert_eq!(bottom, 50.0 + 3.0 + 4.0 + 7.0 + 8.0);
    }
    #[test]
    fn clip_rect_resolve_at_zero_and_with_negative_geometry() {
        let all_zero =
            StyleClipRect::default().resolve(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
        assert_eq!(all_zero, (0.0, 0.0, 0.0, 0.0));
        // Negative geometry is summed as-is (no clamping): deterministic, finite.
        let (top, right, bottom, left) = StyleClipRect::default()
            .resolve(-10.0, -20.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0);
        assert_eq!(top, 0.0);
        assert_eq!(left, 0.0);
        assert_eq!(right, -14.0);
        assert_eq!(bottom, -24.0);
    }
    #[test]
    fn clip_rect_resolve_ignores_the_geometry_for_explicit_edges() {
        let explicit = StyleClipRect {
            top: OptionF32::Some(1.0),
            right: OptionF32::Some(2.0),
            bottom: OptionF32::Some(3.0),
            left: OptionF32::Some(4.0),
        };
        // Even with hostile geometry the explicit edges come back untouched.
        for geometry in [
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::MAX,
            f32::MIN,
            f32::MIN_POSITIVE,
        ] {
            let resolved = explicit.resolve(
                geometry, geometry, geometry, geometry, geometry, geometry, geometry, geometry,
                geometry, geometry,
            );
            assert_eq!(
                resolved,
                (1.0, 2.0, 3.0, 4.0),
                "explicit edges were perturbed by geometry {geometry:?}"
            );
        }
    }
    #[test]
    fn clip_rect_resolve_saturates_at_f32_max_and_keeps_nan_contained() {
        // f32::MAX + f32::MAX overflows to +inf rather than panicking.
        let (top, right, bottom, left) = StyleClipRect::default().resolve(
            f32::MAX,
            f32::MAX,
            f32::MAX,
            f32::MAX,
            f32::MAX,
            f32::MAX,
            f32::MAX,
            f32::MAX,
            f32::MAX,
            f32::MAX,
        );
        assert_eq!(top, 0.0);
        assert_eq!(left, 0.0);
        assert!(right.is_infinite() && right.is_sign_positive());
        assert!(bottom.is_infinite() && bottom.is_sign_positive());
        // NaN geometry propagates into the auto edges only (documented result:
        // NaN in, NaN out — no panic, and the fixed edges stay clean).
        let (top, right, bottom, left) = StyleClipRect::default().resolve(
            f32::NAN,
            f32::NAN,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
        );
        assert_eq!(top, 0.0);
        assert_eq!(left, 0.0);
        assert!(right.is_nan());
        assert!(bottom.is_nan());
        // +inf added to -inf is NaN — still no panic.
        let (_, right, bottom, _) = StyleClipRect::default().resolve(
            f32::INFINITY,
            f32::INFINITY,
            f32::NEG_INFINITY,
            0.0,
            f32::NEG_INFINITY,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
        );
        assert!(right.is_nan());
        assert!(bottom.is_nan());
    }
    // ---------------------------------------------------------------------
    // Error types: to_contained / to_shared
    // ---------------------------------------------------------------------
    /// Payloads that an error may have to carry: empty, whitespace, multibyte,
    /// combining marks, an embedded NUL, and a large string.
    fn error_payloads() -> Vec<String> {
        vec![
            String::new(),
            String::from(" "),
            String::from("bogus"),
            String::from("\u{1F600}\u{0301}"),
            String::from("a\0b"),
            String::from("rect(1px, 2px, 3px, 4px)"),
            "x".repeat(100_000),
        ]
    }
    macro_rules! assert_error_round_trips {
        ($borrowed:ident) => {{
            for payload in error_payloads() {
                let borrowed = $borrowed::InvalidValue(payload.as_str());
                let owned = borrowed.to_contained();
                let back = owned.to_shared();
                assert_eq!(
                    back,
                    borrowed,
                    "{}::InvalidValue({payload:?}) lost data on to_contained/to_shared",
                    stringify!($borrowed)
                );
                // ...and the owned form is stable under a second lap.
                assert_eq!(owned.to_shared().to_contained(), owned);
            }
        }};
    }
    #[test]
    fn parse_errors_round_trip_between_borrowed_and_owned_forms() {
        assert_error_round_trips!(LayoutOverflowParseError);
        assert_error_round_trips!(StyleScrollbarGutterParseError);
        assert_error_round_trips!(StyleOverflowClipMarginParseError);
        assert_error_round_trips!(StyleClipRectParseError);
    }
    #[test]
    fn parse_errors_produced_by_the_parsers_round_trip_too() {
        let e = parse_layout_overflow("nope").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        let e = parse_style_scrollbar_gutter("nope").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        let e = parse_style_overflow_clip_margin("nope nope").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
        let e = parse_clip_rect("rect(nope)").unwrap_err();
        assert_eq!(e.to_contained().to_shared(), e);
    }
    #[test]
    fn parse_error_messages_name_the_property_and_quote_the_value() {
        let msg = format!("{}", LayoutOverflowParseError::InvalidValue("zzz"));
        assert!(msg.contains("overflow") && msg.contains("zzz"), "{msg}");
        let msg = format!("{}", StyleScrollbarGutterParseError::InvalidValue("zzz"));
        assert!(
            msg.contains("scrollbar-gutter") && msg.contains("zzz"),
            "{msg}"
        );
        let msg = format!("{}", StyleOverflowClipMarginParseError::InvalidValue("zzz"));
        assert!(
            msg.contains("overflow-clip-margin") && msg.contains("zzz"),
            "{msg}"
        );
        let msg = format!("{}", StyleClipRectParseError::InvalidValue("zzz"));
        assert!(msg.contains("clip") && msg.contains("zzz"), "{msg}");
        // Debug is wired to Display: it must not panic on hostile payloads.
        let weird = StyleClipRectParseError::InvalidValue("\u{1F600}\0\u{0301}");
        assert!(!format!("{weird:?}").is_empty());
    }
}