1
//! CSS properties for CSS Grid layout.
2

            
3
use alloc::{
4
    boxed::Box,
5
    string::{String, ToString},
6
    vec::Vec,
7
};
8
use core::mem::ManuallyDrop;
9

            
10
use crate::{
11
    codegen::format::FormatAsRustCode,
12
    corety::AzString,
13
    impl_vec, impl_vec_clone, impl_vec_debug, impl_vec_eq, impl_vec_hash, impl_vec_mut,
14
    impl_vec_ord, impl_vec_partialeq, impl_vec_partialord,
15
    props::{basic::pixel::PixelValue, formatter::PrintAsCssValue},
16
};
17

            
18
// --- grid-template-columns / grid-template-rows ---
19

            
20
/// Wrapper for minmax(min, max) to satisfy repr(C) (enum variants can only have 1 field)
21
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
22
#[repr(C)]
23
pub struct GridMinMax {
24
    /// `ManuallyDrop` so the owned `Box` is freed ONLY while `run_destructor`
25
    /// is still set (see `Drop`): the codegen FFI mirror of the enclosing
26
    /// `GridTrackSizing` embeds this by value AND drops the real type first,
27
    /// then Rust's drop glue drops the field a second time on the same bytes.
28
    /// Layout is unchanged — `ManuallyDrop<Box<T>>` is a single pointer.
29
    pub min: ManuallyDrop<Box<GridTrackSizing>>,
30
    pub max: ManuallyDrop<Box<GridTrackSizing>>,
31
    /// The double-drop gate (the `GlContextPtr` convention): cleared by the
32
    /// first drop, so the second one is a no-op.
33
    pub run_destructor: bool,
34
}
35

            
36
impl GridMinMax {
37
    #[must_use]
38
14833
    pub fn new(min: GridTrackSizing, max: GridTrackSizing) -> Self {
39
14833
        Self {
40
14833
            min: ManuallyDrop::new(Box::new(min)),
41
14833
            max: ManuallyDrop::new(Box::new(max)),
42
14833
            run_destructor: true,
43
14833
        }
44
14833
    }
45
}
46

            
47
impl Clone for GridMinMax {
48
13718
    fn clone(&self) -> Self {
49
13718
        Self::new((**self.min).clone(), (**self.max).clone())
50
13718
    }
51
}
52

            
53
impl Drop for GridMinMax {
54
14833
    fn drop(&mut self) {
55
14833
        if self.run_destructor {
56
14833
            self.run_destructor = false;
57
14833
            unsafe {
58
14833
                ManuallyDrop::drop(&mut self.min);
59
14833
                ManuallyDrop::drop(&mut self.max);
60
14833
            }
61
        }
62
14833
    }
63
}
64

            
65
impl core::fmt::Debug for GridMinMax {
66
1
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
67
1
        write!(
68
1
            f,
69
1
            "minmax({}, {})",
70
1
            self.min.print_as_css_value(),
71
1
            self.max.print_as_css_value()
72
        )
73
1
    }
74
}
75

            
76
/// Represents a single track sizing function for grid
77
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
78
#[repr(C, u8)]
79
#[derive(Default)]
80
pub enum GridTrackSizing {
81
    /// Fixed pixel/percent size
82
    Fixed(PixelValue),
83
    /// fr units (value multiplied by `FR_SCALING_FACTOR` to allow fractional
84
    /// values while satisfying Eq/Ord/Hash — e.g. `1fr` = `Fr(100)`, `0.5fr` = `Fr(50)`)
85
    Fr(i32),
86
    /// min-content
87
    MinContent,
88
    /// max-content
89
    MaxContent,
90
    /// auto
91
    #[default]
92
    Auto,
93
    /// minmax(min, max) - uses `GridMinMax` which contains Box<GridTrackSizing> for each bound
94
    MinMax(GridMinMax),
95
    /// fit-content(size)
96
    FitContent(PixelValue),
97
}
98

            
99
impl_option!(
100
    GridTrackSizing,
101
    OptionGridTrackSizing,
102
    copy = false,
103
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
104
);
105

            
106
impl core::fmt::Debug for GridTrackSizing {
107
1
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
108
1
        write!(f, "{}", self.print_as_css_value())
109
1
    }
110
}
111

            
112
impl PrintAsCssValue for GridTrackSizing {
113
76
    fn print_as_css_value(&self) -> String {
114
76
        match self {
115
42
            Self::Fixed(px) => px.print_as_css_value(),
116
22
            Self::Fr(f) => format!("{f}fr"),
117
1
            Self::MinContent => "min-content".to_string(),
118
3
            Self::MaxContent => "max-content".to_string(),
119
4
            Self::Auto => "auto".to_string(),
120
3
            Self::MinMax(minmax) => {
121
3
                format!(
122
3
                    "minmax({}, {})",
123
3
                    minmax.min.print_as_css_value(),
124
3
                    minmax.max.print_as_css_value()
125
                )
126
            }
127
1
            Self::FitContent(size) => {
128
1
                format!("fit-content({})", size.print_as_css_value())
129
            }
130
        }
131
76
    }
132
}
133

            
134
// C-compatible Vec for GridTrackSizing
135
impl_vec!(
136
    GridTrackSizing,
137
    GridTrackSizingVec,
138
    GridTrackSizingVecDestructor,
139
    GridTrackSizingVecDestructorType,
140
    GridTrackSizingVecSlice,
141
    OptionGridTrackSizing
142
);
143
impl_vec_clone!(
144
    GridTrackSizing,
145
    GridTrackSizingVec,
146
    GridTrackSizingVecDestructor
147
);
148
impl_vec_debug!(GridTrackSizing, GridTrackSizingVec);
149
impl_vec_partialeq!(GridTrackSizing, GridTrackSizingVec);
150
impl_vec_eq!(GridTrackSizing, GridTrackSizingVec);
151
impl_vec_partialord!(GridTrackSizing, GridTrackSizingVec);
152
impl_vec_ord!(GridTrackSizing, GridTrackSizingVec);
153
impl_vec_hash!(GridTrackSizing, GridTrackSizingVec);
154
impl_vec_mut!(GridTrackSizing, GridTrackSizingVec);
155

            
156
/// Represents `grid-template-columns` or `grid-template-rows`
157
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
158
#[repr(C)]
159
pub struct GridTemplate {
160
    pub tracks: GridTrackSizingVec,
161
}
162

            
163
impl core::fmt::Debug for GridTemplate {
164
15
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
165
15
        write!(f, "{}", self.print_as_css_value())
166
15
    }
167
}
168

            
169
impl Default for GridTemplate {
170
169
    fn default() -> Self {
171
169
        Self {
172
169
            tracks: GridTrackSizingVec::from_vec(Vec::new()),
173
169
        }
174
169
    }
175
}
176

            
177
impl PrintAsCssValue for GridTemplate {
178
21
    fn print_as_css_value(&self) -> String {
179
21
        let tracks_slice = self.tracks.as_ref();
180
21
        if tracks_slice.is_empty() {
181
2
            "none".to_string()
182
        } else {
183
19
            tracks_slice
184
19
                .iter()
185
19
                .map(PrintAsCssValue::print_as_css_value)
186
19
                .collect::<Vec<_>>()
187
19
                .join(" ")
188
        }
189
21
    }
190
}
191

            
192
// --- grid-auto-columns / grid-auto-rows ---
193

            
194
/// Represents `grid-auto-columns` or `grid-auto-rows`
195
/// Structurally identical to `GridTemplate` but semantically different
196
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
197
#[repr(C)]
198
pub struct GridAutoTracks {
199
    pub tracks: GridTrackSizingVec,
200
}
201

            
202
impl core::fmt::Debug for GridAutoTracks {
203
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
204
        write!(f, "{}", self.print_as_css_value())
205
    }
206
}
207

            
208
impl Default for GridAutoTracks {
209
145
    fn default() -> Self {
210
145
        Self {
211
145
            tracks: GridTrackSizingVec::from_vec(Vec::new()),
212
145
        }
213
145
    }
214
}
215

            
216
impl PrintAsCssValue for GridAutoTracks {
217
2
    fn print_as_css_value(&self) -> String {
218
2
        let tracks_slice = self.tracks.as_ref();
219
2
        if tracks_slice.is_empty() {
220
2
            "auto".to_string()
221
        } else {
222
            tracks_slice
223
                .iter()
224
                .map(PrintAsCssValue::print_as_css_value)
225
                .collect::<Vec<_>>()
226
                .join(" ")
227
        }
228
2
    }
229
}
230

            
231
impl From<GridTemplate> for GridAutoTracks {
232
1
    fn from(template: GridTemplate) -> Self {
233
1
        Self {
234
1
            tracks: template.tracks,
235
1
        }
236
1
    }
237
}
238

            
239
// --- grid-row / grid-column (grid line placement) ---
240

            
241
/// Named grid line with optional span count (FFI-safe wrapper)
242
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
243
#[repr(C)]
244
pub struct NamedGridLine {
245
    pub grid_line_name: AzString,
246
    /// Span count, 0 means no span specified
247
    pub span_count: i32,
248
}
249

            
250
impl NamedGridLine {
251
    #[must_use]
252
480
    pub fn create(name: AzString, span: Option<i32>) -> Self {
253
480
        Self {
254
480
            grid_line_name: name,
255
480
            span_count: span.unwrap_or(0),
256
480
        }
257
480
    }
258

            
259
    #[must_use]
260
12
    pub const fn span(&self) -> Option<i32> {
261
12
        if self.span_count == 0 {
262
3
            None
263
        } else {
264
9
            Some(self.span_count)
265
        }
266
12
    }
267
}
268
#[allow(variant_size_differences)]
269
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
270
// disparity accepted
271
/// Represents a grid line position (start or end)
272
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
273
#[repr(C, u8)]
274
#[derive(Default)]
275
pub enum GridLine {
276
    /// auto
277
    #[default]
278
    Auto,
279
    /// Line number (1-based, negative for counting from end)
280
    Line(i32),
281
    /// Named line with optional span count
282
    Named(NamedGridLine),
283
    /// span N
284
    Span(i32),
285
}
286

            
287
impl core::fmt::Debug for GridLine {
288
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
289
        write!(f, "{}", self.print_as_css_value())
290
    }
291
}
292

            
293
impl PrintAsCssValue for GridLine {
294
49
    fn print_as_css_value(&self) -> String {
295
49
        match self {
296
3
            Self::Auto => "auto".to_string(),
297
10
            Self::Line(n) => n.to_string(),
298
32
            Self::Named(named) => {
299
32
                if named.span_count == 0 {
300
30
                    named.grid_line_name.as_str().to_string()
301
                } else {
302
2
                    format!("{} {}", named.grid_line_name.as_str(), named.span_count)
303
                }
304
            }
305
4
            Self::Span(n) => format!("span {n}"),
306
        }
307
49
    }
308
}
309

            
310
/// Represents `grid-row` or `grid-column` (start / end)
311
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
312
#[repr(C)]
313
pub struct GridPlacement {
314
    pub grid_start: GridLine,
315
    pub grid_end: GridLine,
316
}
317

            
318
impl core::fmt::Debug for GridPlacement {
319
15
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
320
15
        write!(f, "{}", self.print_as_css_value())
321
15
    }
322
}
323

            
324
impl Default for GridPlacement {
325
5
    fn default() -> Self {
326
5
        Self {
327
5
            grid_start: GridLine::Auto,
328
5
            grid_end: GridLine::Auto,
329
5
        }
330
5
    }
331
}
332

            
333
impl PrintAsCssValue for GridPlacement {
334
25
    fn print_as_css_value(&self) -> String {
335
25
        if self.grid_end == GridLine::Auto {
336
5
            self.grid_start.print_as_css_value()
337
        } else {
338
20
            format!(
339
20
                "{} / {}",
340
20
                self.grid_start.print_as_css_value(),
341
20
                self.grid_end.print_as_css_value()
342
            )
343
        }
344
25
    }
345
}
346

            
347
#[cfg(feature = "parser")]
348
#[derive(Clone, PartialEq, Eq)]
349
pub enum GridParseError<'a> {
350
    InvalidValue(&'a str),
351
}
352

            
353
#[cfg(feature = "parser")]
354
impl_debug_as_display!(GridParseError<'a>);
355
#[cfg(feature = "parser")]
356
impl_display! { GridParseError<'a>, {
357
    InvalidValue(e) => format!("Invalid grid value: \"{}\"", e),
358
}}
359

            
360
#[cfg(feature = "parser")]
361
#[derive(Debug, Clone, PartialEq, Eq)]
362
#[repr(C, u8)]
363
pub enum GridParseErrorOwned {
364
    InvalidValue(AzString),
365
}
366

            
367
#[cfg(feature = "parser")]
368
impl GridParseError<'_> {
369
    #[must_use]
370
8
    pub fn to_contained(&self) -> GridParseErrorOwned {
371
8
        match self {
372
8
            GridParseError::InvalidValue(s) => {
373
8
                GridParseErrorOwned::InvalidValue((*s).to_string().into())
374
            }
375
        }
376
8
    }
377
}
378

            
379
#[cfg(feature = "parser")]
380
impl GridParseErrorOwned {
381
    #[must_use]
382
8
    pub fn to_shared(&self) -> GridParseError<'_> {
383
8
        match self {
384
8
            Self::InvalidValue(s) => GridParseError::InvalidValue(s.as_str()),
385
        }
386
8
    }
387
}
388

            
389
#[cfg(feature = "parser")]
390
227
fn split_respecting_parens(input: &str) -> Result<Vec<String>, ()> {
391
227
    let mut parts = Vec::new();
392
227
    let mut current = String::new();
393
227
    let mut paren_depth: i32 = 0;
394

            
395
2463741
    for ch in input.chars() {
396
100351
        match ch {
397
30143
            '(' => {
398
30143
                paren_depth += 1;
399
30143
                current.push(ch);
400
30143
            }
401
            ')' => {
402
30145
                paren_depth -= 1;
403
30145
                if paren_depth < 0 {
404
7
                    return Err(());
405
30138
                }
406
30138
                current.push(ch);
407
            }
408
100351
            ' ' if paren_depth == 0 => {
409
100212
                if !current.trim().is_empty() {
410
100205
                    parts.push(current.trim().to_string());
411
100205
                    current.clear();
412
100205
                }
413
            }
414
2303241
            _ => current.push(ch),
415
        }
416
    }
417
220
    if !current.trim().is_empty() {
418
210
        parts.push(current.trim().to_string());
419
210
    }
420
220
    Ok(parts)
421
227
}
422

            
423
#[cfg(feature = "parser")]
424
/// # Errors
425
///
426
/// Returns an error if `input` is not a valid CSS `grid-template` value.
427
183
pub fn parse_grid_template(input: &str) -> Result<GridTemplate, GridParseError<'_>> {
428
    use crate::props::basic::pixel::parse_pixel_value;
429

            
430
183
    let input = input.trim();
431

            
432
183
    if input == "none" {
433
4
        return Ok(GridTemplate::default());
434
179
    }
435

            
436
179
    let parts = split_respecting_parens(input).map_err(|()| GridParseError::InvalidValue(input))?;
437

            
438
176
    let mut tracks = Vec::new();
439
50515
    for part in &parts {
440
50360
        parse_grid_track_or_repeat(part, &mut tracks)
441
50360
            .map_err(|()| GridParseError::InvalidValue(input))?;
442
    }
443

            
444
155
    Ok(GridTemplate {
445
155
        tracks: GridTrackSizingVec::from_vec(tracks),
446
155
    })
447
183
}
448

            
449
/// Parse a single grid track token, which may be `repeat(N, track)` or a plain track.
450
/// For `repeat(N, track_list)`, the tracks are expanded inline.
451
#[cfg(feature = "parser")]
452
50387
fn parse_grid_track_or_repeat(input: &str, tracks: &mut Vec<GridTrackSizing>) -> Result<(), ()> {
453
    // Maximum repeat count accepted in `repeat(N, …)` to bound expansion.
454
    const MAX_GRID_REPEAT_COUNT: usize = 10_000;
455
50387
    let input = input.trim();
456

            
457
    // Handle repeat(N, track_list)
458
50387
    if input.starts_with("repeat(") && input.ends_with(')') {
459
41
        let content = &input[7..input.len() - 1];
460
        // Find the first comma that separates the count from the track list
461
41
        let comma_pos = content.find(',').ok_or(())?;
462
39
        let count_str = content[..comma_pos].trim();
463
39
        let track_list_str = content[comma_pos + 1..].trim();
464

            
465
39
        let count: usize = count_str.parse().map_err(|_| ())?;
466
32
        if count == 0 || count > MAX_GRID_REPEAT_COUNT {
467
3
            return Err(());
468
29
        }
469

            
470
        // Parse the track list (may contain multiple space-separated tracks)
471
29
        let parts = split_respecting_parens(track_list_str)?;
472
29
        let repeat_tracks: Vec<GridTrackSizing> = parts
473
29
            .iter()
474
38
            .map(|p| parse_grid_track_owned(p))
475
29
            .collect::<Result<Vec<_>, _>>()?;
476

            
477
        // Expand: repeat N times
478
20060
        for _ in 0..count {
479
20060
            tracks.extend(repeat_tracks.iter().cloned());
480
20060
        }
481
26
        return Ok(());
482
50346
    }
483

            
484
    // Plain single track
485
50346
    tracks.push(parse_grid_track_owned(input)?);
486
50318
    Ok(())
487
50387
}
488

            
489
#[cfg(feature = "parser")]
490
50697
fn parse_grid_track_owned(input: &str) -> Result<GridTrackSizing, ()> {
491
    use crate::props::basic::pixel::parse_pixel_value;
492

            
493
50697
    let input = input.trim();
494

            
495
50697
    if input == "auto" {
496
12
        return Ok(GridTrackSizing::Auto);
497
50685
    }
498

            
499
50685
    if input == "min-content" {
500
5
        return Ok(GridTrackSizing::MinContent);
501
50680
    }
502

            
503
50680
    if input == "max-content" {
504
6
        return Ok(GridTrackSizing::MaxContent);
505
50674
    }
506

            
507
50674
    if let Some(num_str) = input.strip_suffix("fr") {
508
        /// Fr values are stored as integers scaled by this factor (e.g. `1fr` = 100, `0.5fr` = 50).
509
        const FR_SCALING_FACTOR: f32 = 100.0;
510
50244
        let num_str = num_str.trim();
511
50244
        if let Ok(num) = num_str.parse::<f32>() {
512
50235
            let scaled = num * FR_SCALING_FACTOR;
513
50235
            if scaled.is_nan()
514
50232
                || scaled < crate::cast::i32_to_f32(i32::MIN)
515
50228
                || scaled > crate::cast::i32_to_f32(i32::MAX)
516
            {
517
15
                return Err(());
518
50220
            }
519
50220
            return Ok(GridTrackSizing::Fr(crate::cast::f32_to_i32(scaled)));
520
9
        }
521
9
        return Err(());
522
430
    }
523

            
524
430
    if input.starts_with("minmax(") && input.ends_with(')') {
525
117
        let content = &input[7..input.len() - 1];
526
117
        let parts: Vec<&str> = content.split(',').collect();
527
117
        if parts.len() == 2 {
528
112
            let min = parse_grid_track_owned(parts[0].trim())?;
529
112
            let max = parse_grid_track_owned(parts[1].trim())?;
530
112
            return Ok(GridTrackSizing::MinMax(GridMinMax::new(min, max)));
531
5
        }
532
5
        return Err(());
533
313
    }
534

            
535
313
    if input.starts_with("fit-content(") && input.ends_with(')') {
536
7
        let size_str = &input[12..input.len() - 1].trim();
537
7
        if let Ok(size) = parse_pixel_value(size_str) {
538
5
            return Ok(GridTrackSizing::FitContent(size));
539
2
        }
540
2
        return Err(());
541
306
    }
542

            
543
    // Try to parse as pixel value
544
306
    if let Ok(px) = parse_pixel_value(input) {
545
259
        return Ok(GridTrackSizing::Fixed(px));
546
47
    }
547

            
548
47
    Err(())
549
50697
}
550

            
551
#[cfg(feature = "parser")]
552
/// # Errors
553
///
554
/// Returns an error if `input` is not a valid CSS `grid-placement` value.
555
44
pub fn parse_grid_placement(input: &str) -> Result<GridPlacement, GridParseError<'_>> {
556
44
    let input = input.trim();
557

            
558
44
    if input == "auto" {
559
4
        return Ok(GridPlacement::default());
560
40
    }
561

            
562
    // Split by "/"
563
40
    let parts: Vec<&str> = input.split('/').map(str::trim).collect();
564

            
565
38
    let grid_start =
566
40
        parse_grid_line_owned(parts[0]).map_err(|()| GridParseError::InvalidValue(input))?;
567
38
    let grid_end = if parts.len() > 1 {
568
20
        parse_grid_line_owned(parts[1]).map_err(|()| GridParseError::InvalidValue(input))?
569
    } else {
570
18
        GridLine::Auto
571
    };
572

            
573
37
    Ok(GridPlacement {
574
37
        grid_start,
575
37
        grid_end,
576
37
    })
577
44
}
578

            
579
// --- grid-auto-flow ---
580

            
581
/// Represents the `grid-auto-flow` property
582
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
583
#[repr(C)]
584
#[derive(Default)]
585
pub enum LayoutGridAutoFlow {
586
    #[default]
587
    Row,
588
    Column,
589
    RowDense,
590
    ColumnDense,
591
}
592

            
593
impl PrintAsCssValue for LayoutGridAutoFlow {
594
4
    fn print_as_css_value(&self) -> String {
595
4
        match self {
596
1
            Self::Row => "row".to_string(),
597
1
            Self::Column => "column".to_string(),
598
1
            Self::RowDense => "row dense".to_string(),
599
1
            Self::ColumnDense => "column dense".to_string(),
600
        }
601
4
    }
602
}
603

            
604
#[cfg(feature = "parser")]
605
#[derive(Clone, PartialEq, Eq)]
606
pub enum GridAutoFlowParseError<'a> {
607
    InvalidValue(&'a str),
608
}
609

            
610
#[cfg(feature = "parser")]
611
impl_debug_as_display!(GridAutoFlowParseError<'a>);
612
#[cfg(feature = "parser")]
613
impl_display! { GridAutoFlowParseError<'a>, {
614
    InvalidValue(e) => format!("Invalid grid-auto-flow value: \"{}\"", e),
615
}}
616

            
617
#[cfg(feature = "parser")]
618
#[derive(Debug, Clone, PartialEq, Eq)]
619
#[repr(C, u8)]
620
pub enum GridAutoFlowParseErrorOwned {
621
    InvalidValue(AzString),
622
}
623

            
624
#[cfg(feature = "parser")]
625
impl GridAutoFlowParseError<'_> {
626
    #[must_use]
627
6
    pub fn to_contained(&self) -> GridAutoFlowParseErrorOwned {
628
6
        match self {
629
6
            GridAutoFlowParseError::InvalidValue(s) => {
630
6
                GridAutoFlowParseErrorOwned::InvalidValue((*s).to_string().into())
631
            }
632
        }
633
6
    }
634
}
635

            
636
#[cfg(feature = "parser")]
637
impl GridAutoFlowParseErrorOwned {
638
    #[must_use]
639
6
    pub fn to_shared(&self) -> GridAutoFlowParseError<'_> {
640
6
        match self {
641
6
            Self::InvalidValue(s) => GridAutoFlowParseError::InvalidValue(s.as_str()),
642
        }
643
6
    }
644
}
645

            
646
#[cfg(feature = "parser")]
647
/// # Errors
648
///
649
/// Returns an error if `input` is not a valid CSS `grid-auto-flow` value.
650
26
pub fn parse_layout_grid_auto_flow(
651
26
    input: &str,
652
26
) -> Result<LayoutGridAutoFlow, GridAutoFlowParseError<'_>> {
653
26
    match input.trim() {
654
26
        "row" => Ok(LayoutGridAutoFlow::Row),
655
23
        "column" => Ok(LayoutGridAutoFlow::Column),
656
21
        "row dense" | "dense" => Ok(LayoutGridAutoFlow::RowDense),
657
18
        "column dense" => Ok(LayoutGridAutoFlow::ColumnDense),
658
16
        _ => Err(GridAutoFlowParseError::InvalidValue(input)),
659
    }
660
26
}
661

            
662
// --- justify-self / justify-items ---
663

            
664
/// Represents `justify-self` for grid items
665
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
666
#[repr(C)]
667
#[derive(Default)]
668
pub enum LayoutJustifySelf {
669
    #[default]
670
    Auto,
671
    Start,
672
    End,
673
    Center,
674
    Stretch,
675
}
676

            
677
impl PrintAsCssValue for LayoutJustifySelf {
678
5
    fn print_as_css_value(&self) -> String {
679
5
        match self {
680
1
            Self::Auto => "auto".to_string(),
681
1
            Self::Start => "start".to_string(),
682
1
            Self::End => "end".to_string(),
683
1
            Self::Center => "center".to_string(),
684
1
            Self::Stretch => "stretch".to_string(),
685
        }
686
5
    }
687
}
688

            
689
#[cfg(feature = "parser")]
690
#[derive(Clone, PartialEq, Eq)]
691
pub enum JustifySelfParseError<'a> {
692
    InvalidValue(&'a str),
693
}
694

            
695
#[cfg(feature = "parser")]
696
#[derive(Debug, Clone, PartialEq, Eq)]
697
#[repr(C, u8)]
698
pub enum JustifySelfParseErrorOwned {
699
    InvalidValue(AzString),
700
}
701

            
702
#[cfg(feature = "parser")]
703
impl JustifySelfParseError<'_> {
704
    #[must_use]
705
5
    pub fn to_contained(&self) -> JustifySelfParseErrorOwned {
706
5
        match self {
707
5
            JustifySelfParseError::InvalidValue(s) => {
708
5
                JustifySelfParseErrorOwned::InvalidValue((*s).to_string().into())
709
            }
710
        }
711
5
    }
712
}
713

            
714
#[cfg(feature = "parser")]
715
impl JustifySelfParseErrorOwned {
716
    #[must_use]
717
5
    pub fn to_shared(&self) -> JustifySelfParseError<'_> {
718
5
        match self {
719
5
            Self::InvalidValue(s) => JustifySelfParseError::InvalidValue(s.as_str()),
720
        }
721
5
    }
722
}
723

            
724
#[cfg(feature = "parser")]
725
impl_debug_as_display!(JustifySelfParseError<'a>);
726
#[cfg(feature = "parser")]
727
impl_display! { JustifySelfParseError<'a>, {
728
    InvalidValue(e) => format!("Invalid justify-self value: \"{}\"", e),
729
}}
730

            
731
#[cfg(feature = "parser")]
732
/// # Errors
733
///
734
/// Returns an error if `input` is not a valid CSS `justify-self` value.
735
29
pub fn parse_layout_justify_self(
736
29
    input: &str,
737
29
) -> Result<LayoutJustifySelf, JustifySelfParseError<'_>> {
738
29
    match input.trim() {
739
29
        "auto" => Ok(LayoutJustifySelf::Auto),
740
26
        "start" | "flex-start" => Ok(LayoutJustifySelf::Start),
741
22
        "end" | "flex-end" => Ok(LayoutJustifySelf::End),
742
19
        "center" => Ok(LayoutJustifySelf::Center),
743
16
        "stretch" => Ok(LayoutJustifySelf::Stretch),
744
14
        _ => Err(JustifySelfParseError::InvalidValue(input)),
745
    }
746
29
}
747

            
748
/// Represents `justify-items` for grid containers
749
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
750
#[repr(C)]
751
#[derive(Default)]
752
pub enum LayoutJustifyItems {
753
    Start,
754
    End,
755
    Center,
756
    #[default]
757
    Stretch,
758
}
759

            
760
impl PrintAsCssValue for LayoutJustifyItems {
761
4
    fn print_as_css_value(&self) -> String {
762
4
        match self {
763
1
            Self::Start => "start".to_string(),
764
1
            Self::End => "end".to_string(),
765
1
            Self::Center => "center".to_string(),
766
1
            Self::Stretch => "stretch".to_string(),
767
        }
768
4
    }
769
}
770

            
771
#[cfg(feature = "parser")]
772
#[derive(Clone, PartialEq, Eq)]
773
pub enum JustifyItemsParseError<'a> {
774
    InvalidValue(&'a str),
775
}
776

            
777
#[cfg(feature = "parser")]
778
#[derive(Debug, Clone, PartialEq, Eq)]
779
#[repr(C, u8)]
780
pub enum JustifyItemsParseErrorOwned {
781
    InvalidValue(AzString),
782
}
783

            
784
#[cfg(feature = "parser")]
785
impl JustifyItemsParseError<'_> {
786
    #[must_use]
787
5
    pub fn to_contained(&self) -> JustifyItemsParseErrorOwned {
788
5
        match self {
789
5
            JustifyItemsParseError::InvalidValue(s) => {
790
5
                JustifyItemsParseErrorOwned::InvalidValue((*s).to_string().into())
791
            }
792
        }
793
5
    }
794
}
795

            
796
#[cfg(feature = "parser")]
797
impl JustifyItemsParseErrorOwned {
798
    #[must_use]
799
5
    pub fn to_shared(&self) -> JustifyItemsParseError<'_> {
800
5
        match self {
801
5
            Self::InvalidValue(s) => JustifyItemsParseError::InvalidValue(s.as_str()),
802
        }
803
5
    }
804
}
805

            
806
#[cfg(feature = "parser")]
807
impl_debug_as_display!(JustifyItemsParseError<'a>);
808
#[cfg(feature = "parser")]
809
impl_display! { JustifyItemsParseError<'a>, {
810
    InvalidValue(e) => format!("Invalid justify-items value: \"{}\"", e),
811
}}
812

            
813
#[cfg(feature = "parser")]
814
/// # Errors
815
///
816
/// Returns an error if `input` is not a valid CSS `justify-items` value.
817
18
pub fn parse_layout_justify_items(
818
18
    input: &str,
819
18
) -> Result<LayoutJustifyItems, JustifyItemsParseError<'_>> {
820
18
    match input.trim() {
821
18
        "start" => Ok(LayoutJustifyItems::Start),
822
16
        "end" => Ok(LayoutJustifyItems::End),
823
14
        "center" => Ok(LayoutJustifyItems::Center),
824
12
        "stretch" => Ok(LayoutJustifyItems::Stretch),
825
10
        _ => Err(JustifyItemsParseError::InvalidValue(input)),
826
    }
827
18
}
828

            
829
// --- gap (single value type) ---
830

            
831
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
832
#[repr(C)]
833
pub struct LayoutGap {
834
    pub inner: PixelValue,
835
}
836

            
837
impl core::fmt::Debug for LayoutGap {
838
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
839
        write!(f, "{}", self.inner)
840
    }
841
}
842

            
843
impl PrintAsCssValue for LayoutGap {
844
8
    fn print_as_css_value(&self) -> String {
845
8
        self.inner.print_as_css_value()
846
8
    }
847
}
848

            
849
// Implement FormatAsRustCode for the new types so they can be emitted by the
850
// code generator.
851
impl FormatAsRustCode for LayoutGridAutoFlow {
852
    fn format_as_rust_code(&self, _tabs: usize) -> String {
853
        format!(
854
            "LayoutGridAutoFlow::{}",
855
            match self {
856
                Self::Row => "Row",
857
                Self::Column => "Column",
858
                Self::RowDense => "RowDense",
859
                Self::ColumnDense => "ColumnDense",
860
            }
861
        )
862
    }
863
}
864

            
865
impl FormatAsRustCode for LayoutJustifySelf {
866
    fn format_as_rust_code(&self, _tabs: usize) -> String {
867
        format!(
868
            "LayoutJustifySelf::{}",
869
            match self {
870
                Self::Auto => "Auto",
871
                Self::Start => "Start",
872
                Self::End => "End",
873
                Self::Center => "Center",
874
                Self::Stretch => "Stretch",
875
            }
876
        )
877
    }
878
}
879

            
880
impl FormatAsRustCode for LayoutJustifyItems {
881
    fn format_as_rust_code(&self, _tabs: usize) -> String {
882
        format!(
883
            "LayoutJustifyItems::{}",
884
            match self {
885
                Self::Start => "Start",
886
                Self::End => "End",
887
                Self::Center => "Center",
888
                Self::Stretch => "Stretch",
889
            }
890
        )
891
    }
892
}
893

            
894
impl FormatAsRustCode for LayoutGap {
895
    fn format_as_rust_code(&self, _tabs: usize) -> String {
896
        use crate::codegen::format::format_pixel_value;
897
        format!("LayoutGap {{ inner: {} }}", format_pixel_value(&self.inner))
898
    }
899
}
900

            
901
impl FormatAsRustCode for GridTrackSizing {
902
    // `tabs` is required by the FormatAsRustCode trait signature; this variant only
903
    // threads it through to nested MinMax children, never reading it locally.
904
    #[allow(clippy::only_used_in_recursion)]
905
    fn format_as_rust_code(&self, tabs: usize) -> String {
906
        use crate::codegen::format::format_pixel_value;
907
        match self {
908
            Self::Fixed(pv) => {
909
                format!("GridTrackSizing::Fixed({})", format_pixel_value(pv))
910
            }
911
            Self::Fr(f) => format!("GridTrackSizing::Fr({f})"),
912
            Self::MinContent => "GridTrackSizing::MinContent".to_string(),
913
            Self::MaxContent => "GridTrackSizing::MaxContent".to_string(),
914
            Self::Auto => "GridTrackSizing::Auto".to_string(),
915
            Self::MinMax(minmax) => {
916
                format!(
917
                    "GridTrackSizing::MinMax(GridMinMax::new({}, {}))",
918
                    minmax.min.format_as_rust_code(tabs),
919
                    minmax.max.format_as_rust_code(tabs)
920
                )
921
            }
922
            Self::FitContent(pv) => {
923
                format!("GridTrackSizing::FitContent({})", format_pixel_value(pv))
924
            }
925
        }
926
    }
927
}
928

            
929
impl FormatAsRustCode for GridAutoTracks {
930
    fn format_as_rust_code(&self, tabs: usize) -> String {
931
        let tracks: Vec<String> = self
932
            .tracks
933
            .as_ref()
934
            .iter()
935
            .map(|t| t.format_as_rust_code(tabs))
936
            .collect();
937
        format!(
938
            "GridAutoTracks {{ tracks: GridTrackSizingVec::from_vec(vec![{}]) }}",
939
            tracks.join(", ")
940
        )
941
    }
942
}
943

            
944
impl FormatAsRustCode for GridTemplateAreas {
945
    fn format_as_rust_code(&self, _tabs: usize) -> String {
946
        format!(
947
            "GridTemplateAreas {{ areas: GridAreaDefinitionVec::from_vec(vec!{:?}) }}",
948
            self.areas.as_ref()
949
        )
950
    }
951
}
952

            
953
#[cfg(feature = "parser")]
954
/// # Errors
955
///
956
/// Returns an error if `input` is not a valid CSS `gap` value.
957
9637
pub fn parse_layout_gap(
958
9637
    input: &str,
959
9637
) -> Result<LayoutGap, crate::props::basic::pixel::CssPixelValueParseError<'_>> {
960
9637
    crate::props::basic::pixel::parse_pixel_value(input).map(|p| LayoutGap { inner: p })
961
9637
}
962

            
963
#[cfg(feature = "parser")]
964
/// # Errors
965
///
966
/// Returns an error if `input` is not a valid CSS `grid-line-owned` value.
967
520
pub fn parse_grid_line_owned(input: &str) -> Result<GridLine, ()> {
968
520
    let input = input.trim();
969

            
970
520
    if input == "auto" {
971
3
        return Ok(GridLine::Auto);
972
517
    }
973

            
974
517
    if let Some(num_str) = input.strip_prefix("span ") {
975
19
        let num_str = num_str.trim();
976
19
        if let Ok(num) = num_str.parse::<i32>() {
977
13
            return Ok(GridLine::Span(num));
978
6
        }
979
6
        return Err(());
980
498
    }
981

            
982
    // Try to parse as line number
983
498
    if let Ok(num) = input.parse::<i32>() {
984
38
        return Ok(GridLine::Line(num));
985
460
    }
986

            
987
    // Otherwise treat as named line
988
460
    Ok(GridLine::Named(NamedGridLine::create(
989
460
        input.to_string().into(),
990
460
        None,
991
460
    )))
992
520
}
993

            
994
#[cfg(all(test, feature = "parser"))]
995
mod tests {
996
    use super::*;
997

            
998
    // Grid template tests
999
    #[test]
1
    fn test_parse_grid_template_none() {
1
        let result = parse_grid_template("none").unwrap();
1
        assert_eq!(result.tracks.len(), 0);
1
    }
    #[test]
1
    fn test_parse_grid_template_single_px() {
1
        let result = parse_grid_template("100px").unwrap();
1
        assert_eq!(result.tracks.len(), 1);
1
        assert!(matches!(
1
            result.tracks.as_ref()[0],
            GridTrackSizing::Fixed(_)
        ));
1
    }
    #[test]
1
    fn test_parse_grid_template_multiple_tracks() {
1
        let result = parse_grid_template("100px 200px 1fr").unwrap();
1
        assert_eq!(result.tracks.len(), 3);
1
    }
    #[test]
1
    fn test_parse_grid_template_fr_units() {
1
        let result = parse_grid_template("1fr 2fr 1fr").unwrap();
1
        assert_eq!(result.tracks.len(), 3);
1
        assert!(matches!(
1
            result.tracks.as_ref()[0],
            GridTrackSizing::Fr(100)
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[1],
            GridTrackSizing::Fr(200)
        ));
1
    }
    #[test]
1
    fn test_parse_grid_template_fractional_fr() {
1
        let result = parse_grid_template("0.5fr 1.5fr").unwrap();
1
        assert_eq!(result.tracks.len(), 2);
1
        assert!(matches!(result.tracks.as_ref()[0], GridTrackSizing::Fr(50)));
1
        assert!(matches!(
1
            result.tracks.as_ref()[1],
            GridTrackSizing::Fr(150)
        ));
1
    }
    #[test]
1
    fn test_parse_grid_template_auto() {
1
        let result = parse_grid_template("auto 100px auto").unwrap();
1
        assert_eq!(result.tracks.len(), 3);
1
        assert!(matches!(result.tracks.as_ref()[0], GridTrackSizing::Auto));
1
        assert!(matches!(result.tracks.as_ref()[2], GridTrackSizing::Auto));
1
    }
    #[test]
1
    fn test_parse_grid_template_min_max_content() {
1
        let result = parse_grid_template("min-content max-content auto").unwrap();
1
        assert_eq!(result.tracks.len(), 3);
1
        assert!(matches!(
1
            result.tracks.as_ref()[0],
            GridTrackSizing::MinContent
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[1],
            GridTrackSizing::MaxContent
        ));
1
    }
    #[test]
1
    fn test_parse_grid_template_minmax() {
1
        let result = parse_grid_template("minmax(100px, 1fr)").unwrap();
1
        assert_eq!(result.tracks.len(), 1);
1
        assert!(matches!(
1
            result.tracks.as_ref()[0],
            GridTrackSizing::MinMax(_)
        ));
1
    }
    #[test]
1
    fn test_parse_grid_template_minmax_complex() {
1
        let result = parse_grid_template("minmax(min-content, max-content)").unwrap();
1
        assert_eq!(result.tracks.len(), 1);
1
    }
    #[test]
1
    fn test_parse_grid_template_fit_content() {
1
        let result = parse_grid_template("fit-content(200px)").unwrap();
1
        assert_eq!(result.tracks.len(), 1);
1
        assert!(matches!(
1
            result.tracks.as_ref()[0],
            GridTrackSizing::FitContent(_)
        ));
1
    }
    #[test]
1
    fn test_parse_grid_template_mixed() {
1
        let result = parse_grid_template("100px minmax(100px, 1fr) auto 2fr").unwrap();
1
        assert_eq!(result.tracks.len(), 4);
1
    }
    #[test]
1
    fn test_parse_grid_template_percent() {
1
        let result = parse_grid_template("25% 50% 25%").unwrap();
1
        assert_eq!(result.tracks.len(), 3);
1
    }
    #[test]
1
    fn test_parse_grid_template_em_units() {
1
        let result = parse_grid_template("10em 20em 1fr").unwrap();
1
        assert_eq!(result.tracks.len(), 3);
1
    }
    // Grid placement tests
    #[test]
1
    fn test_parse_grid_placement_auto() {
1
        let result = parse_grid_placement("auto").unwrap();
1
        assert!(matches!(result.grid_start, GridLine::Auto));
1
        assert!(matches!(result.grid_end, GridLine::Auto));
1
    }
    #[test]
1
    fn test_parse_grid_placement_line_number() {
1
        let result = parse_grid_placement("1").unwrap();
1
        assert!(matches!(result.grid_start, GridLine::Line(1)));
1
        assert!(matches!(result.grid_end, GridLine::Auto));
1
    }
    #[test]
1
    fn test_parse_grid_placement_negative_line() {
1
        let result = parse_grid_placement("-1").unwrap();
1
        assert!(matches!(result.grid_start, GridLine::Line(-1)));
1
    }
    #[test]
1
    fn test_parse_grid_placement_span() {
1
        let result = parse_grid_placement("span 2").unwrap();
1
        assert!(matches!(result.grid_start, GridLine::Span(2)));
1
    }
    #[test]
1
    fn test_parse_grid_placement_start_end() {
1
        let result = parse_grid_placement("1 / 3").unwrap();
1
        assert!(matches!(result.grid_start, GridLine::Line(1)));
1
        assert!(matches!(result.grid_end, GridLine::Line(3)));
1
    }
    #[test]
1
    fn test_parse_grid_placement_span_end() {
1
        let result = parse_grid_placement("1 / span 2").unwrap();
1
        assert!(matches!(result.grid_start, GridLine::Line(1)));
1
        assert!(matches!(result.grid_end, GridLine::Span(2)));
1
    }
    #[test]
1
    fn test_parse_grid_placement_named_line() {
1
        let result = parse_grid_placement("header-start").unwrap();
1
        assert!(matches!(result.grid_start, GridLine::Named(_)));
1
    }
    #[test]
1
    fn test_parse_grid_placement_named_start_end() {
1
        let result = parse_grid_placement("header-start / header-end").unwrap();
1
        assert!(matches!(result.grid_start, GridLine::Named(_)));
1
        assert!(matches!(result.grid_end, GridLine::Named(_)));
1
    }
    // Edge cases
    #[test]
1
    fn test_parse_grid_template_whitespace() {
1
        let result = parse_grid_template("  100px   200px  ").unwrap();
1
        assert_eq!(result.tracks.len(), 2);
1
    }
    #[test]
1
    fn test_parse_grid_placement_whitespace() {
1
        let result = parse_grid_placement("  1  /  3  ").unwrap();
1
        assert!(matches!(result.grid_start, GridLine::Line(1)));
1
        assert!(matches!(result.grid_end, GridLine::Line(3)));
1
    }
    #[test]
1
    fn test_parse_grid_template_zero_fr() {
1
        let result = parse_grid_template("0fr").unwrap();
1
        assert!(matches!(result.tracks.as_ref()[0], GridTrackSizing::Fr(0)));
1
    }
    #[test]
1
    fn test_parse_grid_placement_zero_line() {
1
        let result = parse_grid_placement("0").unwrap();
1
        assert!(matches!(result.grid_start, GridLine::Line(0)));
1
    }
    // repeat() tests
    #[test]
1
    fn test_parse_grid_template_repeat_fr() {
1
        let result = parse_grid_template("repeat(3, 1fr)").unwrap();
1
        assert_eq!(result.tracks.len(), 3);
1
        assert!(matches!(
1
            result.tracks.as_ref()[0],
            GridTrackSizing::Fr(100)
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[1],
            GridTrackSizing::Fr(100)
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[2],
            GridTrackSizing::Fr(100)
        ));
1
    }
    #[test]
1
    fn test_parse_grid_template_repeat_px() {
1
        let result = parse_grid_template("repeat(2, 100px)").unwrap();
1
        assert_eq!(result.tracks.len(), 2);
1
        assert!(matches!(
1
            result.tracks.as_ref()[0],
            GridTrackSizing::Fixed(_)
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[1],
            GridTrackSizing::Fixed(_)
        ));
1
    }
    #[test]
1
    fn test_parse_grid_template_repeat_multiple_tracks() {
        // repeat(2, 100px 1fr) should expand to [100px, 1fr, 100px, 1fr]
1
        let result = parse_grid_template("repeat(2, 100px 1fr)").unwrap();
1
        assert_eq!(result.tracks.len(), 4);
1
        assert!(matches!(
1
            result.tracks.as_ref()[0],
            GridTrackSizing::Fixed(_)
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[1],
            GridTrackSizing::Fr(100)
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[2],
            GridTrackSizing::Fixed(_)
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[3],
            GridTrackSizing::Fr(100)
        ));
1
    }
    #[test]
1
    fn test_parse_grid_template_repeat_with_other_tracks() {
        // "100px repeat(2, 1fr) auto" should produce [100px, 1fr, 1fr, auto]
1
        let result = parse_grid_template("100px repeat(2, 1fr) auto").unwrap();
1
        assert_eq!(result.tracks.len(), 4);
1
        assert!(matches!(
1
            result.tracks.as_ref()[0],
            GridTrackSizing::Fixed(_)
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[1],
            GridTrackSizing::Fr(100)
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[2],
            GridTrackSizing::Fr(100)
        ));
1
        assert!(matches!(result.tracks.as_ref()[3], GridTrackSizing::Auto));
1
    }
    #[test]
1
    fn test_parse_grid_template_repeat_minmax() {
1
        let result = parse_grid_template("repeat(3, minmax(100px, 1fr))").unwrap();
1
        assert_eq!(result.tracks.len(), 3);
1
        assert!(matches!(
1
            result.tracks.as_ref()[0],
            GridTrackSizing::MinMax(_)
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[1],
            GridTrackSizing::MinMax(_)
        ));
1
        assert!(matches!(
1
            result.tracks.as_ref()[2],
            GridTrackSizing::MinMax(_)
        ));
1
    }
}
// --- grid-template-areas ---
/// A single named grid area with its row/column bounds (1-based grid line numbers).
/// This matches taffy's `GridTemplateArea<String>`.
#[repr(C)]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GridAreaDefinition {
    pub name: AzString,
    pub row_start: u16,
    pub row_end: u16,
    pub column_start: u16,
    pub column_end: u16,
}
impl_option!(
    GridAreaDefinition,
    OptionGridAreaDefinition,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_vec!(
    GridAreaDefinition,
    GridAreaDefinitionVec,
    GridAreaDefinitionVecDestructor,
    GridAreaDefinitionVecDestructorType,
    GridAreaDefinitionVecSlice,
    OptionGridAreaDefinition
);
impl_vec_clone!(
    GridAreaDefinition,
    GridAreaDefinitionVec,
    GridAreaDefinitionVecDestructor
);
impl_vec_debug!(GridAreaDefinition, GridAreaDefinitionVec);
impl_vec_partialeq!(GridAreaDefinition, GridAreaDefinitionVec);
impl_vec_eq!(GridAreaDefinition, GridAreaDefinitionVec);
impl_vec_partialord!(GridAreaDefinition, GridAreaDefinitionVec);
impl_vec_ord!(GridAreaDefinition, GridAreaDefinitionVec);
impl_vec_hash!(GridAreaDefinition, GridAreaDefinitionVec);
impl_vec_mut!(GridAreaDefinition, GridAreaDefinitionVec);
/// Represents the parsed value of `grid-template-areas`.
///
/// Example CSS:
/// ```css
/// grid-template-areas:
///     "header header header"
///     "sidebar main aside"
///     "footer footer footer";
/// ```
#[repr(C)]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GridTemplateAreas {
    pub areas: GridAreaDefinitionVec,
}
impl Default for GridTemplateAreas {
9
    fn default() -> Self {
9
        Self {
9
            areas: GridAreaDefinitionVec::from_vec(Vec::new()),
9
        }
9
    }
}
impl PrintAsCssValue for GridTemplateAreas {
9
    fn print_as_css_value(&self) -> String {
9
        let areas_slice = self.areas.as_ref();
9
        if areas_slice.is_empty() {
2
            return "none".to_string();
7
        }
        // Reconstruct the row strings from the area definitions
7
        let max_row = areas_slice.iter().map(|a| a.row_end).max().unwrap_or(1);
7
        let max_col = areas_slice.iter().map(|a| a.column_end).max().unwrap_or(1);
7
        let num_rows = (max_row - 1) as usize;
7
        let num_cols = (max_col - 1) as usize;
7
        let mut grid: Vec<Vec<String>> = vec![vec![".".to_string(); num_cols]; num_rows];
18
        for area in areas_slice {
11
            let row_start = area.row_start as usize - 1;
11
            let row_end = area.row_end as usize - 1;
11
            let col_start = area.column_start as usize - 1;
11
            let col_end = area.column_end as usize - 1;
13
            for row in grid.iter_mut().take(row_end).skip(row_start) {
21
                for cell in row.iter_mut().take(col_end).skip(col_start) {
21
                    *cell = area.name.as_str().to_string();
21
                }
            }
        }
7
        grid.iter()
10
            .map(|row| format!("\"{}\"", row.join(" ")))
7
            .collect::<Vec<_>>()
7
            .join(" ")
9
    }
}
/// Parse `grid-template-areas` CSS value.
///
/// Accepts quoted row strings like:
///   `"header header header" "sidebar main aside" "footer footer footer"`
///
/// Returns a `GridTemplateAreas` with deduplicated named areas and their
/// computed row/column line boundaries (1-based, as taffy expects).
#[cfg(feature = "parser")]
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `grid-template-areas` value.
70
pub fn parse_grid_template_areas(input: &str) -> Result<GridTemplateAreas, ()> {
    use alloc::collections::BTreeMap;
70
    let input = input.trim();
70
    if input == "none" {
3
        return Ok(GridTemplateAreas::default());
67
    }
    // Extract quoted strings: each one is a row
67
    let mut rows: Vec<Vec<String>> = Vec::new();
67
    let mut i = 0;
67
    let bytes = input.as_bytes();
132300
    while i < bytes.len() {
132238
        if bytes[i] == b'"' || bytes[i] == b'\'' {
65734
            let quote = bytes[i];
65734
            i += 1;
65734
            let start = i;
273073
            while i < bytes.len() && bytes[i] != quote {
207339
                i += 1;
207339
            }
65734
            if i >= bytes.len() {
3
                return Err(());
65731
            }
65731
            let row_str = &input[start..i];
65731
            let cells: Vec<String> = row_str
65731
                .split_whitespace()
65731
                .map(std::string::ToString::to_string)
65731
                .collect();
65731
            if cells.is_empty() {
2
                return Err(());
65729
            }
65729
            rows.push(cells);
66504
        }
        // advance past the closing quote (quoted branch) or the current char (else)
132233
        i += 1;
    }
62
    if rows.is_empty() {
5
        return Err(());
57
    }
    // Validate: all rows must have the same number of columns
57
    let num_cols = rows[0].len();
65783
    for row in &rows {
65728
        if row.len() != num_cols {
2
            return Err(());
65726
        }
    }
    // Build area map: name -> (min_row, max_row, min_col, max_col) in 0-based indices
55
    let mut area_map: BTreeMap<String, (usize, usize, usize, usize)> = BTreeMap::new();
65724
    for (row_idx, row) in rows.iter().enumerate() {
135926
        for (col_idx, cell) in row.iter().enumerate() {
135926
            if cell == "." {
12
                continue; // skip null cell tokens
135914
            }
135914
            let entry = area_map
135914
                .entry(cell.clone())
135914
                .or_insert((row_idx, row_idx, col_idx, col_idx));
135914
            entry.0 = entry.0.min(row_idx);
135914
            entry.1 = entry.1.max(row_idx);
135914
            entry.2 = entry.2.min(col_idx);
135914
            entry.3 = entry.3.max(col_idx);
        }
    }
    // Convert to 1-based grid line numbers (taffy convention)
55
    let mut areas = Vec::new();
240
    for (name, (min_row, max_row, min_col, max_col)) in area_map {
185
        areas.push(GridAreaDefinition {
185
            name: name.into(),
185
            row_start: u16::try_from(min_row + 1).unwrap_or(u16::MAX),
185
            row_end: u16::try_from(max_row + 2).unwrap_or(u16::MAX), /* end line is one past the
185
                                                                      * last cell */
185
            column_start: u16::try_from(min_col + 1).unwrap_or(u16::MAX),
185
            column_end: u16::try_from(max_col + 2).unwrap_or(u16::MAX),
185
        });
185
    }
55
    Ok(GridTemplateAreas {
55
        areas: GridAreaDefinitionVec::from_vec(areas),
55
    })
70
}
#[cfg(all(test, feature = "parser"))]
mod autotest_generated {
    use super::*;
    // Every assertion below pins the *observed* behaviour of the code as it stands.
    // Where that behaviour deviates from the CSS Grid spec or loses information, the
    // test is named `..._is_lax` / `..._is_lossy` / `..._saturates` and carries a
    // BUG/DEVIATION comment. Those comments are the deliverable: they mark the places
    // where a fix would have to change the assertion, not the code under test.
    // ---------------------------------------------------------------------
    // NamedGridLine::create / NamedGridLine::span
    // ---------------------------------------------------------------------
    #[test]
    fn named_grid_line_span_roundtrips_every_nonzero_i32() {
        for span in [1_i32, -1, 7, -7, i32::MAX, i32::MIN, i32::MIN + 1] {
            let line = NamedGridLine::create("area".to_string().into(), Some(span));
            assert_eq!(line.span_count, span);
            assert_eq!(line.span(), Some(span), "span {span} must survive create()");
        }
    }
    #[test]
    fn named_grid_line_span_of_some_zero_is_lossy() {
        // BUG (encoding collision): `span_count == 0` is the sentinel for "no span",
        // so an explicitly requested `Some(0)` is indistinguishable from `None` on
        // the way out. `create(_, Some(0)).span()` should arguably be `Some(0)` or
        // `create` should reject 0; today it silently becomes `None`.
        let explicit_zero = NamedGridLine::create("a".to_string().into(), Some(0));
        let absent = NamedGridLine::create("a".to_string().into(), None);
        assert_eq!(explicit_zero.span(), None);
        assert_eq!(absent.span(), None);
        assert_eq!(
            explicit_zero, absent,
            "Some(0) and None collapse to the same value"
        );
    }
    #[test]
    fn named_grid_line_create_accepts_empty_and_unicode_names() {
        let empty = NamedGridLine::create(String::new().into(), None);
        assert_eq!(empty.grid_line_name.as_str(), "");
        assert_eq!(empty.span(), None);
        let emoji = NamedGridLine::create("\u{1F600}\u{0301}".to_string().into(), Some(3));
        assert_eq!(emoji.grid_line_name.as_str(), "\u{1F600}\u{0301}");
        assert_eq!(emoji.span(), Some(3));
    }
    #[test]
    fn named_grid_line_span_on_an_extreme_instance_does_not_panic() {
        let huge_name = "x".repeat(100_000);
        let line = NamedGridLine::create(huge_name.clone().into(), Some(i32::MIN));
        assert_eq!(line.span(), Some(i32::MIN));
        assert_eq!(line.grid_line_name.as_str().len(), huge_name.len());
    }
    // ---------------------------------------------------------------------
    // split_respecting_parens (private)
    // ---------------------------------------------------------------------
    #[test]
    fn split_respecting_parens_empty_and_whitespace_yield_ok_empty_not_err() {
        // DEVIATION: the adversarial expectation is Err/None for empty input, but this
        // helper reports "no tokens" as `Ok(vec![])`. That is what makes
        // `parse_grid_template("")` succeed (see the parse_grid_template tests below).
        assert_eq!(split_respecting_parens(""), Ok(Vec::new()));
        assert_eq!(split_respecting_parens("   "), Ok(Vec::new()));
        assert_eq!(split_respecting_parens(" \t\n "), Ok(Vec::new()));
    }
    #[test]
    fn split_respecting_parens_valid_minimal_and_nested_calls() {
        assert_eq!(
            split_respecting_parens("100px 1fr"),
            Ok(vec!["100px".to_string(), "1fr".to_string()])
        );
        // The whole point of the helper: spaces inside parens are NOT separators.
        assert_eq!(
            split_respecting_parens("repeat(2, 100px 1fr) auto"),
            Ok(vec!["repeat(2, 100px 1fr)".to_string(), "auto".to_string()])
        );
        assert_eq!(
            split_respecting_parens("a(b c)d e"),
            Ok(vec!["a(b c)d".to_string(), "e".to_string()])
        );
    }
    #[test]
    fn split_respecting_parens_rejects_unbalanced_close_paren() {
        assert_eq!(split_respecting_parens(")"), Err(()));
        assert_eq!(split_respecting_parens("a)b"), Err(()));
        assert_eq!(split_respecting_parens("(a))"), Err(()));
        assert_eq!(split_respecting_parens(")("), Err(()));
    }
    #[test]
    fn split_respecting_parens_accepts_unbalanced_open_paren_is_lax() {
        // Asymmetry: a stray ')' is an error, a stray '(' is not — the depth counter is
        // never checked at end-of-input. The malformed token is handed downstream, where
        // the track parser happens to reject it, so nothing unsound escapes.
        assert_eq!(split_respecting_parens("((("), Ok(vec!["(((".to_string()]));
        assert_eq!(
            split_respecting_parens("repeat(2, 1fr"),
            Ok(vec!["repeat(2, 1fr".to_string()])
        );
        assert!(parse_grid_template("repeat(2, 1fr").is_err());
    }
    #[test]
    fn split_respecting_parens_does_not_treat_tab_or_newline_as_a_separator() {
        // BUG (CSS whitespace): only U+0020 splits tokens. CSS treats \t, \n, \r and \f
        // as whitespace too, so a multi-line `grid-template-columns` declaration is
        // mis-tokenised into one giant token.
        assert_eq!(
            split_respecting_parens("100px\t200px"),
            Ok(vec!["100px\t200px".to_string()])
        );
        assert_eq!(
            split_respecting_parens("100px\n200px"),
            Ok(vec!["100px\n200px".to_string()])
        );
        // ...and the consequence, one layer up:
        assert!(parse_grid_template("100px\t200px").is_err());
        assert!(parse_grid_template("100px\n200px").is_err());
        // Whereas the space-separated form is fine.
        assert_eq!(parse_grid_template("100px 200px").unwrap().tracks.len(), 2);
    }
    #[test]
    fn split_respecting_parens_handles_multibyte_unicode() {
        // char-based iteration, so no byte-boundary slicing hazard.
        assert_eq!(
            split_respecting_parens("\u{1F600} e\u{0301}"),
            Ok(vec!["\u{1F600}".to_string(), "e\u{0301}".to_string()])
        );
        assert_eq!(
            split_respecting_parens("\u{1F600}(\u{4E2D} \u{6587})"),
            Ok(vec!["\u{1F600}(\u{4E2D} \u{6587})".to_string()])
        );
    }
    #[test]
    fn split_respecting_parens_survives_a_million_chars_and_deep_nesting() {
        // 1M-char single token: linear scan, must not hang.
        let long = "a".repeat(1_000_000);
        let parts = split_respecting_parens(&long).unwrap();
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0].len(), 1_000_000);
        // 50k space-separated tokens.
        let many = "1fr ".repeat(50_000);
        assert_eq!(split_respecting_parens(&many).unwrap().len(), 50_000);
        // 10k nested parens: the scanner is iterative, so no stack overflow, and the
        // balanced nest is returned as a single (garbage) token that parsing rejects.
        let nested = format!("{}{}", "(".repeat(10_000), ")".repeat(10_000));
        assert_eq!(split_respecting_parens(&nested).unwrap().len(), 1);
        assert!(parse_grid_template(&nested).is_err());
    }
    // ---------------------------------------------------------------------
    // parse_grid_track_owned (private)
    // ---------------------------------------------------------------------
    #[test]
    fn parse_grid_track_owned_empty_and_whitespace_are_err() {
        assert_eq!(parse_grid_track_owned(""), Err(()));
        assert_eq!(parse_grid_track_owned("   "), Err(()));
        assert_eq!(parse_grid_track_owned("\t\n"), Err(()));
    }
    #[test]
    fn parse_grid_track_owned_valid_minimal_keywords() {
        assert_eq!(parse_grid_track_owned("auto"), Ok(GridTrackSizing::Auto));
        assert_eq!(
            parse_grid_track_owned("min-content"),
            Ok(GridTrackSizing::MinContent)
        );
        assert_eq!(
            parse_grid_track_owned("max-content"),
            Ok(GridTrackSizing::MaxContent)
        );
        assert_eq!(
            parse_grid_track_owned("  auto  "),
            Ok(GridTrackSizing::Auto),
            "leading/trailing whitespace is trimmed"
        );
        // DEVIATION: CSS keywords are ASCII case-insensitive; this parser is not.
        assert_eq!(parse_grid_track_owned("AUTO"), Err(()));
        assert_eq!(parse_grid_track_owned("Min-Content"), Err(()));
    }
    #[test]
    fn parse_grid_track_owned_fr_is_scaled_by_100_and_truncates() {
        assert_eq!(parse_grid_track_owned("1fr"), Ok(GridTrackSizing::Fr(100)));
        assert_eq!(parse_grid_track_owned("0fr"), Ok(GridTrackSizing::Fr(0)));
        assert_eq!(parse_grid_track_owned("-0fr"), Ok(GridTrackSizing::Fr(0)));
        assert_eq!(parse_grid_track_owned("+1fr"), Ok(GridTrackSizing::Fr(100)));
        assert_eq!(parse_grid_track_owned("0.5fr"), Ok(GridTrackSizing::Fr(50)));
        // Truncation, not rounding: anything below 0.01fr collapses to 0fr, which
        // taffy reads as "take no free space at all".
        assert_eq!(
            parse_grid_track_owned("0.005fr"),
            Ok(GridTrackSizing::Fr(0))
        );
        assert_eq!(
            parse_grid_track_owned("1.999fr"),
            Ok(GridTrackSizing::Fr(199))
        );
        // DEVIATION: CSS forbids negative <flex> values; this accepts them.
        assert_eq!(
            parse_grid_track_owned("-1fr"),
            Ok(GridTrackSizing::Fr(-100))
        );
    }
    #[test]
    fn parse_grid_track_owned_fr_rejects_nan_inf_and_out_of_range() {
        // The guard in parse_grid_track_owned checks is_nan() and the i32 bounds
        // *before* casting, so none of these can produce a garbage saturated Fr.
        for bad in [
            "NaNfr",
            "nanfr",
            "inffr",
            "-inffr",
            "infinityfr",
            "1e8fr",
            "-1e8fr",
            "1e30fr",
            "-1e30fr",
            "340282350000000000000000000000000000000fr",
        ] {
            assert_eq!(
                parse_grid_track_owned(bad),
                Err(()),
                "{bad:?} must be rejected"
            );
        }
        // Largest values that still fit: 1e7fr * 100 == 1e9, exactly representable in f32.
        assert_eq!(
            parse_grid_track_owned("1e7fr"),
            Ok(GridTrackSizing::Fr(1_000_000_000))
        );
        assert_eq!(
            parse_grid_track_owned("-1e7fr"),
            Ok(GridTrackSizing::Fr(-1_000_000_000))
        );
    }
    #[test]
    fn parse_grid_track_owned_bare_fr_suffix_is_err() {
        assert_eq!(parse_grid_track_owned("fr"), Err(()));
        assert_eq!(parse_grid_track_owned("  fr"), Err(()));
        assert_eq!(parse_grid_track_owned("xfr"), Err(()));
    }
    #[test]
    fn parse_grid_track_owned_minmax_comma_split_is_paren_unaware() {
        assert_eq!(
            parse_grid_track_owned("minmax(100px, 1fr)"),
            Ok(GridTrackSizing::MinMax(GridMinMax::new(
                GridTrackSizing::Fixed(PixelValue::px(100.0)),
                GridTrackSizing::Fr(100),
            )))
        );
        // fit-content nests fine (it has no top-level comma)...
        assert!(matches!(
            parse_grid_track_owned("minmax(fit-content(10px), 2px)"),
            Ok(GridTrackSizing::MinMax(_))
        ));
        // ...but anything with an inner comma blows the `split(',')` arity check.
        // DEVIATION: `minmax(minmax(1px,2px), 3px)` is legal-ish CSS shape-wise and is
        // rejected here purely because the comma split ignores parens. It fails closed
        // (Err, not a mis-parse), and it is also what bounds recursion depth to 2.
        assert_eq!(
            parse_grid_track_owned("minmax(minmax(1px,2px), 3px)"),
            Err(())
        );
        assert_eq!(parse_grid_track_owned("minmax(1px,2px,3px)"), Err(()));
        assert_eq!(parse_grid_track_owned("minmax(1px)"), Err(()));
        assert_eq!(parse_grid_track_owned("minmax()"), Err(()));
    }
    #[test]
    fn parse_grid_track_owned_deeply_nested_minmax_cannot_stack_overflow() {
        // 10k nested minmax: rejected at the arity check on the first level, so the
        // recursive descent never actually descends. Guards against a regression that
        // makes the comma split paren-aware without adding a depth limit.
        let deep = format!("{}1px{}", "minmax(".repeat(10_000), ")".repeat(10_000));
        assert_eq!(parse_grid_track_owned(&deep), Err(()));
        let deep_fit = format!("{}1px{}", "fit-content(".repeat(10_000), ")".repeat(10_000));
        assert_eq!(parse_grid_track_owned(&deep_fit), Err(()));
    }
    #[test]
    fn parse_grid_track_owned_unclosed_and_truncated_funcs_are_err() {
        // The `&input[7..len-1]` / `&input[12..len-1]` slices are only reached when both
        // the prefix and the ')' suffix match, which makes len >= 8 / >= 13. These inputs
        // probe every shape near that boundary for an out-of-bounds slice panic.
        for bad in [
            "minmax(",
            "minmax",
            "minmax)",
            "fit-content(",
            "fit-content",
            "fit-content)",
            "repeat(",
            ")",
            "(",
            "()",
            "fit-content()",
        ] {
            assert_eq!(parse_grid_track_owned(bad), Err(()), "{bad:?}");
        }
    }
    #[test]
    fn parse_grid_track_owned_fit_content_and_pixel_fallback() {
        assert_eq!(
            parse_grid_track_owned("fit-content(200px)"),
            Ok(GridTrackSizing::FitContent(PixelValue::px(200.0)))
        );
        assert_eq!(
            parse_grid_track_owned("100px"),
            Ok(GridTrackSizing::Fixed(PixelValue::px(100.0)))
        );
        assert_eq!(
            parse_grid_track_owned("25%"),
            Ok(GridTrackSizing::Fixed(PixelValue::percent(25.0)))
        );
        // DEVIATION (inherited from parse_pixel_value): a unitless number is accepted
        // and silently means px.
        assert_eq!(
            parse_grid_track_owned("100"),
            Ok(GridTrackSizing::Fixed(PixelValue::px(100.0)))
        );
    }
    #[test]
    fn parse_grid_track_owned_pixel_fallback_swallows_nan_and_inf() {
        // BUG (inherited from parse_pixel_value + FloatValue::new): the fr path guards
        // against NaN/inf, the *pixel* path does not. "NaN" is silently coerced to 0px
        // and "inf" saturates to isize::MAX rather than being rejected.
        assert_eq!(
            parse_grid_track_owned("NaNpx"),
            Ok(GridTrackSizing::Fixed(PixelValue::px(0.0))),
            "NaN silently becomes 0px"
        );
        assert_eq!(
            parse_grid_track_owned("inf"),
            Ok(GridTrackSizing::Fixed(PixelValue::px(f32::INFINITY))),
            "inf is accepted and saturates"
        );
        assert_eq!(
            parse_grid_track_owned("1e40px"),
            Ok(GridTrackSizing::Fixed(PixelValue::px(f32::INFINITY)))
        );
    }
    #[test]
    fn parse_grid_track_owned_garbage_and_long_input_never_panic() {
        for bad in [
            "!!!",
            ";;;",
            "\u{1F600}",
            "e\u{0301}\u{0301}",
            "\0",
            "100px;garbage",
            "auto;",
            "1fr 1fr",
            "--var(x)",
            "calc(1px + 1px)",
        ] {
            assert_eq!(parse_grid_track_owned(bad), Err(()), "{bad:?}");
        }
        // 1M chars of a non-numeric token: rejected fast, no hang.
        assert_eq!(parse_grid_track_owned(&"a".repeat(1_000_000)), Err(()));
    }
    // ---------------------------------------------------------------------
    // parse_grid_track_or_repeat (private)
    // ---------------------------------------------------------------------
    #[test]
    fn parse_grid_track_or_repeat_valid_minimal() {
        let mut tracks = Vec::new();
        assert_eq!(
            parse_grid_track_or_repeat("repeat(2, 1fr)", &mut tracks),
            Ok(())
        );
        assert_eq!(
            tracks,
            vec![GridTrackSizing::Fr(100), GridTrackSizing::Fr(100)]
        );
        // Plain (non-repeat) tracks are appended to whatever is already there.
        assert_eq!(parse_grid_track_or_repeat("auto", &mut tracks), Ok(()));
        assert_eq!(tracks.len(), 3);
        assert_eq!(tracks[2], GridTrackSizing::Auto);
    }
    #[test]
    fn parse_grid_track_or_repeat_count_is_bounded_at_10_000() {
        let mut tracks = Vec::new();
        assert_eq!(
            parse_grid_track_or_repeat("repeat(10000, 1fr)", &mut tracks),
            Ok(())
        );
        assert_eq!(tracks.len(), 10_000, "the documented maximum is accepted");
        // One past the cap, zero, negative, and a count that overflows usize.
        for bad in [
            "repeat(10001, 1fr)",
            "repeat(0, 1fr)",
            "repeat(-1, 1fr)",
            "repeat(18446744073709551616, 1fr)",
            "repeat(99999999999999999999999999, 1fr)",
            "repeat(1.5, 1fr)",
            "repeat(NaN, 1fr)",
            "repeat(inf, 1fr)",
            "repeat(auto-fill, 1fr)",
        ] {
            let mut t = Vec::new();
            assert_eq!(parse_grid_track_or_repeat(bad, &mut t), Err(()), "{bad:?}");
        }
    }
    #[test]
    fn parse_grid_track_or_repeat_expansion_is_amplified_by_the_track_list_length() {
        // The 10_000 cap bounds the *count*, not the expansion: `repeat(N, <k tracks>)`
        // yields N*k tracks. 10 tracks x 10_000 => 100_000 entries from a 60-byte input.
        // Not unsound, but worth pinning — the real bound on memory is N * k, and k is
        // limited only by the length of the declaration.
        let mut tracks = Vec::new();
        let input = format!("repeat(10000, {})", "1fr ".repeat(10).trim());
        assert_eq!(parse_grid_track_or_repeat(&input, &mut tracks), Ok(()));
        assert_eq!(tracks.len(), 100_000);
        assert!(tracks.iter().all(|t| *t == GridTrackSizing::Fr(100)));
    }
    #[test]
    fn parse_grid_track_or_repeat_with_an_empty_track_list_is_lax() {
        // DEVIATION: `repeat(2, )` has nothing to repeat. It is accepted and contributes
        // zero tracks instead of being rejected.
        let mut tracks = Vec::new();
        assert_eq!(
            parse_grid_track_or_repeat("repeat(2, )", &mut tracks),
            Ok(())
        );
        assert!(tracks.is_empty());
        assert_eq!(parse_grid_template("repeat(2, )").unwrap().tracks.len(), 0);
    }
    #[test]
    fn parse_grid_track_or_repeat_rejects_nested_repeat_and_malformed_shapes() {
        for bad in [
            "repeat(2, repeat(2, 1fr))", // repeat does not recurse
            "repeat(2)",                 // no comma
            "repeat()",
            "repeat(2, 1fr", // unterminated -> falls through to the plain-track path
            "",
            "   ",
            "\u{1F600}",
            "repeat(2, garbage)",
        ] {
            let mut t = Vec::new();
            assert_eq!(parse_grid_track_or_repeat(bad, &mut t), Err(()), "{bad:?}");
        }
    }
    #[test]
    fn parse_grid_track_or_repeat_appends_nothing_when_it_fails() {
        // Atomicity invariant: on Err the caller's Vec must be left exactly as it was.
        // The repeat path validates the entire track list (collect::<Result<Vec<_>,_>>)
        // *before* it expands, and the plain path propagates with `?` before pushing —
        // so a half-expanded repeat can never leak into the caller's tracks.
        let mut tracks = vec![GridTrackSizing::Auto];
        for bad in [
            "repeat(2, 1fr garbage)",  // fails on the 2nd track of the list
            "repeat(3, 1fr) trailing", // not a single token: rejected as a plain track
            "repeat(0, 1fr)",
            "repeat(2, 1fr", // unterminated
            "garbage",
        ] {
            assert_eq!(
                parse_grid_track_or_repeat(bad, &mut tracks),
                Err(()),
                "{bad:?}"
            );
            assert_eq!(
                tracks,
                vec![GridTrackSizing::Auto],
                "{bad:?} mutated the caller's Vec despite returning Err"
            );
        }
    }
    // ---------------------------------------------------------------------
    // parse_grid_template
    // ---------------------------------------------------------------------
    #[test]
    fn parse_grid_template_empty_and_whitespace_are_ok_empty_is_lax() {
        // DEVIATION: `grid-template-columns: ;` is not valid CSS, but empty / whitespace
        // input yields `Ok` with zero tracks — silently identical to `none`.
        for input in ["", "   ", "\t\n", "  \r\n  "] {
            let parsed = parse_grid_template(input)
                .unwrap_or_else(|e| panic!("{input:?} unexpectedly failed: {e:?}"));
            assert_eq!(parsed.tracks.len(), 0, "{input:?}");
            assert_eq!(parsed, GridTemplate::default(), "{input:?}");
        }
    }
    #[test]
    fn parse_grid_template_none_is_case_sensitive() {
        assert_eq!(
            parse_grid_template("none").unwrap(),
            GridTemplate::default()
        );
        assert_eq!(
            parse_grid_template("  none  ").unwrap(),
            GridTemplate::default()
        );
        // DEVIATION: CSS keywords are ASCII case-insensitive.
        assert!(parse_grid_template("NONE").is_err());
        assert!(parse_grid_template("None").is_err());
    }
    #[test]
    fn parse_grid_template_garbage_is_err_and_reports_the_trimmed_input() {
        let err = parse_grid_template("  !!! garbage  ").unwrap_err();
        assert_eq!(
            err,
            GridParseError::InvalidValue("!!! garbage"),
            "the error borrows the trimmed input, not the raw one"
        );
        assert_eq!(format!("{err}"), "Invalid grid value: \"!!! garbage\"");
        for bad in [
            ")",
            "a)b",
            "100px;200px",
            "1 fr",
            "100px, 200px",
            "\u{1F600}",
            "100px \u{1F600}",
            "\0",
            "calc(100px)",
        ] {
            assert!(
                parse_grid_template(bad).is_err(),
                "{bad:?} must be rejected"
            );
        }
    }
    #[test]
    fn parse_grid_template_boundary_numbers_do_not_overflow() {
        // fr guards against NaN/inf/out-of-range...
        for bad in ["NaNfr", "inffr", "-inffr", "1e30fr"] {
            assert!(parse_grid_template(bad).is_err(), "{bad:?}");
        }
        // ...the pixel path saturates instead (see parse_grid_track_owned tests).
        assert_eq!(
            parse_grid_template("1e40px").unwrap().tracks.as_ref()[0],
            GridTrackSizing::Fixed(PixelValue::px(f32::INFINITY))
        );
        // i64::MAX as a bare number: parsed as an f32 px value, no integer overflow.
        assert!(parse_grid_template("9223372036854775807").is_ok());
        assert_eq!(
            parse_grid_template("0px -0px 0fr").unwrap().tracks.len(),
            3,
            "zero and negative-zero are accepted"
        );
    }
    #[test]
    fn parse_grid_template_extremely_long_input_terminates() {
        // 50k tokens.
        let many = "1fr ".repeat(50_000);
        assert_eq!(parse_grid_template(&many).unwrap().tracks.len(), 50_000);
        // 1M-char single garbage token: rejected without hanging.
        assert!(parse_grid_template(&"a".repeat(1_000_000)).is_err());
    }
    #[test]
    fn parse_grid_template_deeply_nested_parens_do_not_stack_overflow() {
        let nested = format!("{}1px{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(parse_grid_template(&nested).is_err());
        // Unbalanced in the *other* direction is caught by split_respecting_parens.
        assert!(parse_grid_template(&")".repeat(10_000)).is_err());
    }
    // ---------------------------------------------------------------------
    // parse_grid_line_owned
    // ---------------------------------------------------------------------
    #[test]
    fn parse_grid_line_owned_valid_minimal() {
        assert_eq!(parse_grid_line_owned("auto"), Ok(GridLine::Auto));
        assert_eq!(parse_grid_line_owned("1"), Ok(GridLine::Line(1)));
        assert_eq!(parse_grid_line_owned("-1"), Ok(GridLine::Line(-1)));
        assert_eq!(parse_grid_line_owned("+1"), Ok(GridLine::Line(1)));
        assert_eq!(parse_grid_line_owned("0"), Ok(GridLine::Line(0)));
        assert_eq!(parse_grid_line_owned("-0"), Ok(GridLine::Line(0)));
        assert_eq!(parse_grid_line_owned("span 2"), Ok(GridLine::Span(2)));
        assert_eq!(parse_grid_line_owned("span   2"), Ok(GridLine::Span(2)));
    }
    #[test]
    fn parse_grid_line_owned_i32_boundaries_saturate_into_a_named_line() {
        assert_eq!(
            parse_grid_line_owned("2147483647"),
            Ok(GridLine::Line(i32::MAX))
        );
        assert_eq!(
            parse_grid_line_owned("-2147483648"),
            Ok(GridLine::Line(i32::MIN))
        );
        // BUG (silent reinterpretation): one past the i32 range, the integer parse fails
        // and the input falls through to the "named line" catch-all — so `grid-row:
        // 2147483648` becomes a *named* line called "2147483648" instead of an error.
        // A typo'd or overflowing line number is silently accepted as a name.
        assert_eq!(
            parse_grid_line_owned("2147483648"),
            Ok(GridLine::Named(NamedGridLine::create(
                "2147483648".to_string().into(),
                None
            )))
        );
        assert_eq!(
            parse_grid_line_owned("-2147483649"),
            Ok(GridLine::Named(NamedGridLine::create(
                "-2147483649".to_string().into(),
                None
            )))
        );
        // The `span` path has no such fallback: it fails closed.
        assert_eq!(parse_grid_line_owned("span 2147483648"), Err(()));
        assert_eq!(parse_grid_line_owned("span -2147483649"), Err(()));
        assert_eq!(parse_grid_line_owned("span abc"), Err(()));
        // ...unless the input trims down to bare "span": the leading `trim()` eats the
        // trailing space, `strip_prefix("span ")` then misses, and `span` with no count
        // (invalid CSS) becomes a grid line *named* "span" instead of an error.
        assert_eq!(
            parse_grid_line_owned("span "),
            Ok(GridLine::Named(NamedGridLine::create(
                "span".to_string().into(),
                None
            )))
        );
    }
    #[test]
    fn parse_grid_line_owned_span_accepts_zero_and_negative_is_lax() {
        // DEVIATION: CSS requires `span <integer [1,∞]>`. Both of these are invalid CSS
        // and both are accepted here; taffy gets a nonsensical span.
        assert_eq!(parse_grid_line_owned("span 0"), Ok(GridLine::Span(0)));
        assert_eq!(parse_grid_line_owned("span -5"), Ok(GridLine::Span(-5)));
        assert_eq!(
            parse_grid_line_owned("span -2147483648"),
            Ok(GridLine::Span(i32::MIN))
        );
    }
    #[test]
    fn parse_grid_line_owned_never_errs_on_garbage_it_names_it() {
        // BUG (unbounded catch-all): every input that is not `auto` / an i32 / a bad
        // `span` becomes a named grid line. Empty string, punctuation, emoji, an entire
        // stylesheet — all `Ok`. This is why parse_grid_placement effectively cannot
        // reject anything (see below).
        for garbage in [
            "",
            "   ",
            "!!!",
            ";;;",
            "\u{1F600}",
            "\0",
            "span",
            "100px",
            "1 2",
        ] {
            let parsed = parse_grid_line_owned(garbage)
                .unwrap_or_else(|()| panic!("{garbage:?} unexpectedly errored"));
            assert!(
                matches!(parsed, GridLine::Named(_)),
                "{garbage:?} became {parsed:?}, expected a Named catch-all"
            );
        }
        assert_eq!(
            parse_grid_line_owned("   "),
            Ok(GridLine::Named(NamedGridLine::create(
                String::new().into(),
                None
            ))),
            "whitespace-only trims to an EMPTY named line"
        );
        // No panic on a huge name.
        assert!(parse_grid_line_owned(&"x".repeat(100_000)).is_ok());
    }
    // ---------------------------------------------------------------------
    // parse_grid_placement
    // ---------------------------------------------------------------------
    #[test]
    fn parse_grid_placement_valid_minimal() {
        assert_eq!(
            parse_grid_placement("auto").unwrap(),
            GridPlacement::default()
        );
        assert_eq!(
            parse_grid_placement("1 / 3").unwrap(),
            GridPlacement {
                grid_start: GridLine::Line(1),
                grid_end: GridLine::Line(3)
            }
        );
        assert_eq!(
            parse_grid_placement("1/3").unwrap(),
            GridPlacement {
                grid_start: GridLine::Line(1),
                grid_end: GridLine::Line(3)
            },
            "the slash does not need surrounding spaces"
        );
        assert_eq!(
            parse_grid_placement("  1  /  span 2  ").unwrap(),
            GridPlacement {
                grid_start: GridLine::Line(1),
                grid_end: GridLine::Span(2)
            }
        );
    }
    #[test]
    fn parse_grid_placement_extra_slash_segments_are_silently_dropped() {
        // DEVIATION: `1 / 2 / 3` is not valid CSS. Only parts[0] and parts[1] are read;
        // everything after the second slash is discarded without an error.
        assert_eq!(
            parse_grid_placement("1 / 2 / 3").unwrap(),
            GridPlacement {
                grid_start: GridLine::Line(1),
                grid_end: GridLine::Line(2)
            }
        );
        assert_eq!(
            parse_grid_placement("1 / 2 / 3 / 4 / garbage").unwrap(),
            GridPlacement {
                grid_start: GridLine::Line(1),
                grid_end: GridLine::Line(2)
            }
        );
    }
    #[test]
    fn parse_grid_placement_empty_and_garbage_are_ok_named_is_lax() {
        // BUG: consequence of the parse_grid_line_owned catch-all — `grid-row: ;` and
        // `grid-row: !!!;` both parse successfully into a named line. There is no
        // input-validation value in the Result at all except via the `span` path.
        let empty = parse_grid_placement("").unwrap();
        assert_eq!(
            empty,
            GridPlacement {
                grid_start: GridLine::Named(NamedGridLine::create(String::new().into(), None)),
                grid_end: GridLine::Auto,
            },
            "empty input should be Err, but yields a Named(\"\") start"
        );
        for garbage in ["   ", "!!!", "\u{1F600}", "/", "///", "\0"] {
            assert!(parse_grid_placement(garbage).is_ok(), "{garbage:?}");
        }
        // The ONLY rejection path: a malformed `span`.
        let err = parse_grid_placement("  span x  ").unwrap_err();
        assert_eq!(err, GridParseError::InvalidValue("span x"));
        assert_eq!(format!("{err}"), "Invalid grid value: \"span x\"");
        assert!(parse_grid_placement("1 / span x").is_err());
    }
    #[test]
    fn parse_grid_placement_long_and_nested_input_does_not_panic() {
        let long = "a".repeat(200_000);
        assert!(parse_grid_placement(&long).is_ok());
        assert!(parse_grid_placement(&format!("{long} / {long}")).is_ok());
        // No paren handling here at all, so nesting is inert (but must not panic).
        let nested = format!("{}x{}", "(".repeat(10_000), ")".repeat(10_000));
        assert!(parse_grid_placement(&nested).is_ok());
    }
    // ---------------------------------------------------------------------
    // parse_layout_grid_auto_flow
    // ---------------------------------------------------------------------
    #[test]
    fn parse_layout_grid_auto_flow_accepts_exactly_five_spellings() {
        assert_eq!(
            parse_layout_grid_auto_flow("row"),
            Ok(LayoutGridAutoFlow::Row)
        );
        assert_eq!(
            parse_layout_grid_auto_flow("column"),
            Ok(LayoutGridAutoFlow::Column)
        );
        assert_eq!(
            parse_layout_grid_auto_flow("row dense"),
            Ok(LayoutGridAutoFlow::RowDense)
        );
        assert_eq!(
            parse_layout_grid_auto_flow("dense"),
            Ok(LayoutGridAutoFlow::RowDense)
        );
        assert_eq!(
            parse_layout_grid_auto_flow("column dense"),
            Ok(LayoutGridAutoFlow::ColumnDense)
        );
        assert_eq!(
            parse_layout_grid_auto_flow("  row  "),
            Ok(LayoutGridAutoFlow::Row)
        );
    }
    #[test]
    fn parse_layout_grid_auto_flow_rejects_everything_else() {
        for bad in [
            "",
            "   ",
            "\t\n",
            "ROW", // DEVIATION: CSS keywords are case-insensitive
            "Row",
            "dense row", // DEVIATION: CSS allows either order
            "dense column",
            "row  dense", // DEVIATION: internal whitespace is not collapsed
            "row\tdense",
            "row dense extra",
            "row;",
            "\u{1F600}",
            "\0",
        ] {
            assert!(
                parse_layout_grid_auto_flow(bad).is_err(),
                "{bad:?} must be rejected"
            );
        }
        // Extremely long input: a straight match, no hang.
        assert!(parse_layout_grid_auto_flow(&"row ".repeat(250_000)).is_err());
    }
    #[test]
    fn parse_layout_grid_auto_flow_error_borrows_the_untrimmed_input() {
        // The match trims, but the error variant is built from the *raw* `input`, so the
        // rendered message keeps the caller's padding. Pinned because Display output of
        // these errors ends up in user-facing CSS diagnostics.
        let err = parse_layout_grid_auto_flow("  bogus  ").unwrap_err();
        assert_eq!(err, GridAutoFlowParseError::InvalidValue("  bogus  "));
        assert_eq!(
            format!("{err}"),
            "Invalid grid-auto-flow value: \"  bogus  \""
        );
    }
    // ---------------------------------------------------------------------
    // parse_layout_justify_self / parse_layout_justify_items
    // ---------------------------------------------------------------------
    #[test]
    fn parse_layout_justify_self_accepts_the_flex_aliases() {
        assert_eq!(
            parse_layout_justify_self("auto"),
            Ok(LayoutJustifySelf::Auto)
        );
        assert_eq!(
            parse_layout_justify_self("start"),
            Ok(LayoutJustifySelf::Start)
        );
        assert_eq!(
            parse_layout_justify_self("flex-start"),
            Ok(LayoutJustifySelf::Start)
        );
        assert_eq!(parse_layout_justify_self("end"), Ok(LayoutJustifySelf::End));
        assert_eq!(
            parse_layout_justify_self("flex-end"),
            Ok(LayoutJustifySelf::End)
        );
        assert_eq!(
            parse_layout_justify_self("center"),
            Ok(LayoutJustifySelf::Center)
        );
        assert_eq!(
            parse_layout_justify_self("stretch"),
            Ok(LayoutJustifySelf::Stretch)
        );
        assert_eq!(
            parse_layout_justify_self("  center  "),
            Ok(LayoutJustifySelf::Center)
        );
    }
    #[test]
    fn parse_layout_justify_self_rejects_everything_else() {
        for bad in [
            "",
            "   ",
            "Start",
            "START",
            "space-between",
            "normal",
            "left",
            "right",
            "\u{1F600}",
            "\0",
            "start end",
            "flex-start;",
        ] {
            assert!(parse_layout_justify_self(bad).is_err(), "{bad:?}");
        }
        let err = parse_layout_justify_self("  bogus  ").unwrap_err();
        assert_eq!(err, JustifySelfParseError::InvalidValue("  bogus  "));
        assert_eq!(
            format!("{err}"),
            "Invalid justify-self value: \"  bogus  \""
        );
        assert!(parse_layout_justify_self(&"x".repeat(1_000_000)).is_err());
    }
    #[test]
    fn parse_layout_justify_items_has_no_auto_and_no_flex_aliases() {
        assert_eq!(
            parse_layout_justify_items("start"),
            Ok(LayoutJustifyItems::Start)
        );
        assert_eq!(
            parse_layout_justify_items("end"),
            Ok(LayoutJustifyItems::End)
        );
        assert_eq!(
            parse_layout_justify_items("center"),
            Ok(LayoutJustifyItems::Center)
        );
        assert_eq!(
            parse_layout_justify_items("stretch"),
            Ok(LayoutJustifyItems::Stretch)
        );
        // Asymmetry with justify-self, pinned deliberately: `auto` and the `flex-*`
        // aliases are accepted by justify-self but rejected by justify-items. `auto` is
        // in fact valid CSS for justify-items (it means "legacy"/inherit-ish), so this
        // is a DEVIATION, and the two parsers disagree about the same input.
        assert!(parse_layout_justify_items("auto").is_err());
        assert!(parse_layout_justify_self("auto").is_ok());
        assert!(parse_layout_justify_items("flex-start").is_err());
        assert!(parse_layout_justify_self("flex-start").is_ok());
        for bad in ["", "   ", "Start", "\u{1F600}", "\0", "stretch stretch"] {
            assert!(parse_layout_justify_items(bad).is_err(), "{bad:?}");
        }
        let err = parse_layout_justify_items("  bogus  ").unwrap_err();
        assert_eq!(err, JustifyItemsParseError::InvalidValue("  bogus  "));
        assert_eq!(
            format!("{err}"),
            "Invalid justify-items value: \"  bogus  \""
        );
        assert!(parse_layout_justify_items(&"x".repeat(1_000_000)).is_err());
    }
    // ---------------------------------------------------------------------
    // parse_layout_gap
    // ---------------------------------------------------------------------
    #[test]
    fn parse_layout_gap_valid_minimal_and_units() {
        assert_eq!(
            parse_layout_gap("10px").unwrap().inner,
            PixelValue::px(10.0)
        );
        assert_eq!(
            parse_layout_gap("  10px  ").unwrap().inner,
            PixelValue::px(10.0)
        );
        assert_eq!(
            parse_layout_gap("1.5em").unwrap().inner,
            PixelValue::em(1.5)
        );
        assert_eq!(
            parse_layout_gap("50%").unwrap().inner,
            PixelValue::percent(50.0)
        );
        assert_eq!(parse_layout_gap("0").unwrap().inner, PixelValue::px(0.0));
        assert_eq!(parse_layout_gap("-0").unwrap().inner, PixelValue::px(0.0));
    }
    #[test]
    fn parse_layout_gap_empty_and_garbage_are_err() {
        assert!(matches!(
            parse_layout_gap("").unwrap_err(),
            crate::props::basic::pixel::CssPixelValueParseError::EmptyString
        ));
        assert!(matches!(
            parse_layout_gap("   ").unwrap_err(),
            crate::props::basic::pixel::CssPixelValueParseError::EmptyString
        ));
        for bad in ["px", "10pxpx", "!!!", "\u{1F600}", "\0", "auto", "normal"] {
            assert!(parse_layout_gap(bad).is_err(), "{bad:?}");
        }
    }
    #[test]
    fn parse_layout_gap_accepts_negative_unitless_and_split_units_is_lax() {
        // DEVIATION: `gap` is a <length-percentage [0,∞]> — negatives are invalid CSS,
        // and a nonzero unitless number is invalid too. Both are accepted here.
        assert_eq!(
            parse_layout_gap("-20px").unwrap().inner,
            PixelValue::px(-20.0)
        );
        assert_eq!(parse_layout_gap("10").unwrap().inner, PixelValue::px(10.0));
        // DEVIATION (inherited from parse_pixel_value_inner): the unit suffix is stripped
        // *before* the remainder is trimmed, so whitespace between the number and its
        // unit is silently tolerated. `gap: 10 px` is not valid CSS but parses as 10px.
        assert_eq!(
            parse_layout_gap("10 px").unwrap().inner,
            PixelValue::px(10.0)
        );
        assert_eq!(
            parse_layout_gap("10\tpx").unwrap().inner,
            PixelValue::px(10.0)
        );
        // Same hole in the track parser's fr path, though the tokenizer usually hides it
        // by splitting "1 fr" into two tokens first.
        assert_eq!(parse_grid_track_owned("1 fr"), Ok(GridTrackSizing::Fr(100)));
        assert!(
            parse_grid_template("1 fr").is_err(),
            "...but not via the tokenizer"
        );
    }
    #[test]
    fn parse_layout_gap_nan_and_inf_do_not_panic_but_are_swallowed() {
        // BUG (silent coercion, inherited from FloatValue::new): the f32 -> isize cast
        // saturates, so `gap: NaN` becomes 0px and `gap: inf` becomes isize::MAX/1000 px.
        // Neither is rejected, and neither panics.
        assert_eq!(
            parse_layout_gap("NaN").unwrap().inner,
            PixelValue::px(0.0),
            "NaN silently coerces to 0px"
        );
        assert_eq!(
            parse_layout_gap("inf").unwrap().inner,
            PixelValue::px(f32::INFINITY),
            "inf saturates instead of erroring"
        );
        assert_eq!(
            parse_layout_gap("-inf").unwrap().inner,
            PixelValue::px(f32::NEG_INFINITY)
        );
        assert_eq!(
            parse_layout_gap("1e40px").unwrap().inner,
            PixelValue::px(f32::INFINITY),
            "an f32 overflow saturates rather than wrapping"
        );
        // 10k-digit number: parses (to inf) without hanging.
        assert!(parse_layout_gap(&format!("{}px", "9".repeat(10_000))).is_ok());
    }
    // ---------------------------------------------------------------------
    // parse_grid_template_areas
    // ---------------------------------------------------------------------
    fn area_named<'a>(areas: &'a GridTemplateAreas, name: &str) -> &'a GridAreaDefinition {
        areas
            .areas
            .as_ref()
            .iter()
            .find(|a| a.name.as_str() == name)
            .unwrap_or_else(|| panic!("no area named {name:?}"))
    }
    #[test]
    fn parse_grid_template_areas_valid_minimal() {
        let parsed = parse_grid_template_areas("\"a\"").unwrap();
        assert_eq!(parsed.areas.len(), 1);
        assert_eq!(
            parsed.areas.as_ref()[0],
            GridAreaDefinition {
                name: "a".to_string().into(),
                row_start: 1,
                row_end: 2,
                column_start: 1,
                column_end: 2,
            },
            "1-based, end line is one past the last cell"
        );
        assert_eq!(
            parse_grid_template_areas("none").unwrap(),
            GridTemplateAreas::default()
        );
        assert_eq!(
            parse_grid_template_areas("  none  ").unwrap(),
            GridTemplateAreas::default()
        );
    }
    #[test]
    fn parse_grid_template_areas_computes_bounds_and_sorts_by_name() {
        let parsed =
            parse_grid_template_areas("\"header header\" \"sidebar main\" \"footer footer\"")
                .unwrap();
        assert_eq!(parsed.areas.len(), 4);
        // BTreeMap iteration => areas come out alphabetically, NOT in source order.
        let names: Vec<&str> = parsed
            .areas
            .as_ref()
            .iter()
            .map(|a| a.name.as_str())
            .collect();
        assert_eq!(names, vec!["footer", "header", "main", "sidebar"]);
        let header = area_named(&parsed, "header");
        assert_eq!((header.row_start, header.row_end), (1, 2));
        assert_eq!(
            (header.column_start, header.column_end),
            (1, 3),
            "spans both columns"
        );
        let sidebar = area_named(&parsed, "sidebar");
        assert_eq!((sidebar.row_start, sidebar.row_end), (2, 3));
        assert_eq!((sidebar.column_start, sidebar.column_end), (1, 2));
        let footer = area_named(&parsed, "footer");
        assert_eq!((footer.row_start, footer.row_end), (3, 4));
        assert_eq!((footer.column_start, footer.column_end), (1, 3));
    }
    #[test]
    fn parse_grid_template_areas_null_cells_are_skipped() {
        let parsed = parse_grid_template_areas("\". a\" \". a\"").unwrap();
        assert_eq!(parsed.areas.len(), 1, "'.' never becomes an area");
        let a = area_named(&parsed, "a");
        assert_eq!((a.row_start, a.row_end), (1, 3));
        assert_eq!((a.column_start, a.column_end), (2, 3));
        // An all-null grid is Ok-but-empty, indistinguishable from `none`.
        let all_null = parse_grid_template_areas("\". .\" \". .\"").unwrap();
        assert_eq!(all_null, GridTemplateAreas::default());
    }
    #[test]
    fn parse_grid_template_areas_rejects_empty_unterminated_and_ragged() {
        for bad in [
            "", // no rows
            "   ",
            "\t\n",
            "\"\"",   // empty quoted row -> zero cells
            "\"  \"", // whitespace-only row -> zero cells
            "\"abc",  // unterminated quote
            "'abc",
            "\"a\" \"b",     // second row unterminated
            "\"a b\" \"c\"", // ragged: 2 columns then 1
            "\"a\" \"b c\"",
            "abc", // no quotes at all
            "\u{1F600}",
        ] {
            assert_eq!(
                parse_grid_template_areas(bad),
                Err(()),
                "{bad:?} must be rejected"
            );
        }
    }
    #[test]
    fn parse_grid_template_areas_ignores_junk_outside_the_quotes_is_lax() {
        // DEVIATION: the scanner only looks at quoted runs; anything between them is
        // skipped without complaint. `grid-template-areas: garbage "a" ;;;` parses.
        let parsed = parse_grid_template_areas("garbage \"a\" ;;; \u{1F600}").unwrap();
        assert_eq!(parsed.areas.len(), 1);
        assert_eq!(area_named(&parsed, "a").row_start, 1);
        // Single and double quotes are interchangeable, and may be mixed.
        let mixed = parse_grid_template_areas("'a' \"b\"").unwrap();
        assert_eq!(mixed.areas.len(), 2);
        // A double quote inside a single-quoted row is just a name character.
        let weird = parse_grid_template_areas("'a\"b'").unwrap();
        assert_eq!(weird.areas.as_ref()[0].name.as_str(), "a\"b");
    }
    #[test]
    fn parse_grid_template_areas_uses_tabs_and_newlines_as_cell_separators() {
        // Contrast with split_respecting_parens: this path uses split_whitespace(), so
        // it *does* handle the whitespace CSS actually allows.
        let parsed = parse_grid_template_areas("\"a\tb\" \"c\nd\"").unwrap();
        assert_eq!(parsed.areas.len(), 4);
        for name in ["a", "b", "c", "d"] {
            assert_eq!(area_named(&parsed, name).name.as_str(), name);
        }
    }
    #[test]
    fn parse_grid_template_areas_non_rectangular_becomes_a_bounding_box() {
        // BUG (spec violation): CSS requires each named area to form a single rectangle;
        // a discontiguous name is a parse error. Here the min/max reduction just takes
        // the bounding box, so `"b a b"` yields a `b` that spans columns 1..4 and
        // *swallows* the `a` sitting between the two halves.
        let parsed = parse_grid_template_areas("\"b a b\"").unwrap();
        let b = area_named(&parsed, "b");
        let a = area_named(&parsed, "a");
        assert_eq!(
            (b.column_start, b.column_end),
            (1, 4),
            "bounding box, not a rectangle"
        );
        assert_eq!((a.column_start, a.column_end), (2, 3));
        assert!(
            a.column_start >= b.column_start && a.column_end <= b.column_end,
            "the two areas overlap, which taffy is never supposed to be handed"
        );
    }
    #[test]
    fn parse_grid_template_areas_row_bounds_saturate_past_u16_max() {
        // 65_599 rows of "a" then one row of "b". True line numbers exceed u16::MAX, and
        // `u16::try_from(..).unwrap_or(u16::MAX)` clamps rather than panicking.
        let mut input = String::with_capacity(65_600 * 4);
        for _ in 0..65_599 {
            input.push_str("\"a\" ");
        }
        input.push_str("\"b\"");
        let parsed = parse_grid_template_areas(&input).unwrap();
        assert_eq!(parsed.areas.len(), 2);
        let a = area_named(&parsed, "a");
        assert_eq!(a.row_start, 1);
        assert_eq!(
            a.row_end,
            u16::MAX,
            "true end line is 65_600; it saturates and the grid is silently truncated"
        );
        // BUG (degenerate output): "b" starts at row 65_600, so BOTH of its line numbers
        // clamp to u16::MAX — producing a zero-height area (row_start == row_end). Every
        // other area produced by this parser satisfies row_end > row_start.
        let b = area_named(&parsed, "b");
        assert_eq!(b.row_start, u16::MAX);
        assert_eq!(b.row_end, u16::MAX);
        assert_eq!(
            b.row_start, b.row_end,
            "zero-height area from double saturation"
        );
    }
    #[test]
    fn parse_grid_template_areas_column_bounds_saturate_past_u16_max() {
        let mut row = String::with_capacity(70_000 * 2 + 2);
        row.push('"');
        for _ in 0..70_000 {
            row.push_str("a ");
        }
        row.push('"');
        let parsed = parse_grid_template_areas(&row).unwrap();
        assert_eq!(parsed.areas.len(), 1);
        let a = area_named(&parsed, "a");
        assert_eq!(a.column_start, 1);
        assert_eq!(
            a.column_end,
            u16::MAX,
            "true end line is 70_001; clamped, not wrapped"
        );
        assert_eq!((a.row_start, a.row_end), (1, 2));
    }
    #[test]
    fn parse_grid_template_areas_invariant_end_line_exceeds_start_line() {
        // The invariant PrintAsCssValue relies on (it computes `max_row - 1` on u16 and
        // would underflow if any row_end were 0). Holds for every non-degenerate input;
        // the saturation test above is the one case that violates row_end > row_start.
        for input in [
            "\"a\"",
            "\"a b\" \"c d\"",
            "\"h h h\" \"s m a\" \"f f f\"",
            "\". a .\" \"b a c\"",
            "'x'",
        ] {
            let parsed = parse_grid_template_areas(input).unwrap();
            for area in parsed.areas.as_ref() {
                assert!(area.row_start >= 1, "{input:?}: row_start must be 1-based");
                assert!(
                    area.column_start >= 1,
                    "{input:?}: column_start must be 1-based"
                );
                assert!(area.row_end > area.row_start, "{input:?}: {area:?}");
                assert!(area.column_end > area.column_start, "{input:?}: {area:?}");
            }
        }
    }
    // ---------------------------------------------------------------------
    // Round-trips: print_as_css_value -> parse
    // ---------------------------------------------------------------------
    #[test]
    fn roundtrip_grid_auto_flow_all_variants() {
        for value in [
            LayoutGridAutoFlow::Row,
            LayoutGridAutoFlow::Column,
            LayoutGridAutoFlow::RowDense,
            LayoutGridAutoFlow::ColumnDense,
        ] {
            let printed = value.print_as_css_value();
            assert_eq!(
                parse_layout_grid_auto_flow(&printed),
                Ok(value),
                "{value:?} printed as {printed:?} must re-parse to itself"
            );
        }
    }
    #[test]
    fn roundtrip_justify_self_and_justify_items_all_variants() {
        for value in [
            LayoutJustifySelf::Auto,
            LayoutJustifySelf::Start,
            LayoutJustifySelf::End,
            LayoutJustifySelf::Center,
            LayoutJustifySelf::Stretch,
        ] {
            let printed = value.print_as_css_value();
            assert_eq!(parse_layout_justify_self(&printed), Ok(value), "{value:?}");
        }
        for value in [
            LayoutJustifyItems::Start,
            LayoutJustifyItems::End,
            LayoutJustifyItems::Center,
            LayoutJustifyItems::Stretch,
        ] {
            let printed = value.print_as_css_value();
            assert_eq!(parse_layout_justify_items(&printed), Ok(value), "{value:?}");
        }
    }
    #[test]
    fn roundtrip_gap_and_fixed_tracks_are_stable() {
        for input in [
            "0px", "10px", "-20px", "1.5em", "2rem", "50%", "10mm", "1in",
        ] {
            let gap = parse_layout_gap(input).unwrap();
            let printed = gap.print_as_css_value();
            assert_eq!(
                parse_layout_gap(&printed).unwrap(),
                gap,
                "gap {input:?} -> {printed:?}"
            );
        }
        for input in [
            "auto",
            "min-content",
            "max-content",
            "100px",
            "25%",
            "fit-content(2px)",
        ] {
            let track = parse_grid_track_owned(input).unwrap();
            let printed = track.print_as_css_value();
            assert_eq!(
                parse_grid_track_owned(&printed),
                Ok(track.clone()),
                "track {input:?} -> {printed:?}"
            );
        }
    }
    #[test]
    fn roundtrip_fr_track_inflates_by_100x_every_cycle() {
        // BUG (serialization): GridTrackSizing::Fr stores the value pre-multiplied by
        // FR_SCALING_FACTOR (1fr == Fr(100)), but PrintAsCssValue prints the RAW integer
        // — `format!("{f}fr")` — instead of dividing it back out. So `1fr` serializes as
        // `100fr`, and every print/parse cycle multiplies the track's flex factor by 100.
        // Any code path that round-trips a stylesheet (serialize a computed style, then
        // re-parse it) corrupts every fr track. Correct output would be "1fr".
        let once = parse_grid_track_owned("1fr").unwrap();
        assert_eq!(once, GridTrackSizing::Fr(100));
        assert_eq!(once.print_as_css_value(), "100fr", "should be \"1fr\"");
        let twice = parse_grid_track_owned(&once.print_as_css_value()).unwrap();
        assert_eq!(
            twice,
            GridTrackSizing::Fr(10_000),
            "100x inflation per cycle"
        );
        let thrice = parse_grid_track_owned(&twice.print_as_css_value()).unwrap();
        assert_eq!(thrice, GridTrackSizing::Fr(1_000_000));
        // Four cycles overflow the i32 guard and the value is dropped entirely.
        let four = parse_grid_track_owned(&thrice.print_as_css_value()).unwrap();
        assert_eq!(four, GridTrackSizing::Fr(100_000_000));
        assert_eq!(
            parse_grid_track_owned(&four.print_as_css_value()),
            Err(()),
            "the fifth cycle exceeds i32 and the declaration is discarded"
        );
        // Same bug through the minmax and template printers.
        assert_eq!(
            parse_grid_track_owned("minmax(100px, 1fr)")
                .unwrap()
                .print_as_css_value(),
            "minmax(100px, 100fr)"
        );
        assert_eq!(
            parse_grid_template("1fr 2fr").unwrap().print_as_css_value(),
            "100fr 200fr"
        );
    }
    #[test]
    fn roundtrip_grid_template_none_and_repeat_expansion() {
        assert_eq!(GridTemplate::default().print_as_css_value(), "none");
        assert_eq!(
            parse_grid_template(&GridTemplate::default().print_as_css_value()).unwrap(),
            GridTemplate::default()
        );
        // repeat() is expanded at parse time and never re-emitted as repeat().
        let expanded = parse_grid_template("repeat(3, 100px)").unwrap();
        assert_eq!(expanded.print_as_css_value(), "100px 100px 100px");
        assert_eq!(
            parse_grid_template(&expanded.print_as_css_value()).unwrap(),
            expanded
        );
    }
    #[test]
    fn roundtrip_grid_auto_tracks_empty_prints_auto_but_reparses_to_one_track() {
        // GridAutoTracks::default() is *zero* tracks yet prints as "auto"; re-parsing
        // that text yields *one* Auto track. Structurally lossy, semantically equivalent
        // (taffy treats a missing grid-auto-* as `auto`), pinned so a future change to
        // either side is a deliberate one.
        let empty = GridAutoTracks::default();
        assert_eq!(empty.tracks.len(), 0);
        assert_eq!(empty.print_as_css_value(), "auto");
        let reparsed: GridAutoTracks = parse_grid_template(&empty.print_as_css_value())
            .unwrap()
            .into();
        assert_eq!(reparsed.tracks.len(), 1);
        assert_eq!(reparsed.tracks.as_ref()[0], GridTrackSizing::Auto);
        assert_ne!(reparsed, empty);
    }
    #[test]
    fn roundtrip_grid_placement_hides_a_trailing_auto_end() {
        // `GridPlacement { start, end: Auto }` prints only the start (no " / auto"), which
        // is what CSS does too. Both directions round-trip.
        for input in [
            "auto",
            "1",
            "-1",
            "span 2",
            "1 / 3",
            "1 / span 2",
            "auto / 3",
        ] {
            let placement = parse_grid_placement(input).unwrap();
            let printed = placement.print_as_css_value();
            assert_eq!(
                parse_grid_placement(&printed).unwrap(),
                placement,
                "{input:?} printed as {printed:?}"
            );
        }
        assert_eq!(
            GridPlacement {
                grid_start: GridLine::Line(1),
                grid_end: GridLine::Auto
            }
            .print_as_css_value(),
            "1"
        );
        assert_eq!(
            GridPlacement {
                grid_start: GridLine::Auto,
                grid_end: GridLine::Line(3)
            }
            .print_as_css_value(),
            "auto / 3"
        );
    }
    #[test]
    fn roundtrip_named_grid_line_with_a_span_is_lossy() {
        // BUG (unparseable output): `GridLine::Named` with a span prints as "name N"
        // (e.g. "header 2"), but parse_grid_line_owned has no production for that shape —
        // it falls into the named catch-all and produces a line literally *named*
        // "header 2" with span 0. The span is silently lost. Nothing in this file can
        // construct a spanned Named line from CSS text, so the only way to hit this is to
        // build one via NamedGridLine::create and serialize it.
        let spanned = GridLine::Named(NamedGridLine::create("header".to_string().into(), Some(2)));
        assert_eq!(spanned.print_as_css_value(), "header 2");
        let reparsed = parse_grid_line_owned(&spanned.print_as_css_value()).unwrap();
        assert_eq!(
            reparsed,
            GridLine::Named(NamedGridLine::create("header 2".to_string().into(), None))
        );
        assert_ne!(reparsed, spanned);
        // Without a span it round-trips cleanly.
        let plain = GridLine::Named(NamedGridLine::create("header".to_string().into(), None));
        assert_eq!(plain.print_as_css_value(), "header");
        assert_eq!(
            parse_grid_line_owned(&plain.print_as_css_value()),
            Ok(plain)
        );
    }
    #[test]
    fn roundtrip_grid_template_areas_rectangular_is_stable() {
        for input in [
            "\"a\"",
            "\"a a\"",
            "\"h h\" \"s m\"",
            "\"a a\" \"a a\"",
            "\". a\" \". a\"",
        ] {
            let parsed = parse_grid_template_areas(input).unwrap();
            let printed = parsed.print_as_css_value();
            assert_eq!(
                parse_grid_template_areas(&printed).unwrap(),
                parsed,
                "{input:?} printed as {printed:?}"
            );
        }
        assert_eq!(GridTemplateAreas::default().print_as_css_value(), "none");
        assert_eq!(
            parse_grid_template_areas(&GridTemplateAreas::default().print_as_css_value()).unwrap(),
            GridTemplateAreas::default()
        );
    }
    #[test]
    fn roundtrip_grid_template_areas_non_rectangular_loses_a_whole_area() {
        // BUG (data loss), the printing half of the bounding-box bug above: areas are
        // repainted in alphabetical order, so a later name overwrites the cells of an
        // earlier one that its bounding box happens to cover. `"b a b"` -> `"b b b"`:
        // the `a` area vanishes on serialization.
        let parsed = parse_grid_template_areas("\"b a b\"").unwrap();
        assert_eq!(parsed.areas.len(), 2);
        assert_eq!(
            parsed.print_as_css_value(),
            "\"b b b\"",
            "the `a` area is erased"
        );
        let reparsed = parse_grid_template_areas(&parsed.print_as_css_value()).unwrap();
        assert_eq!(reparsed.areas.len(), 1);
        assert_ne!(reparsed, parsed);
    }
    // ---------------------------------------------------------------------
    // Error types: to_contained / to_shared
    // ---------------------------------------------------------------------
    #[test]
    fn grid_parse_error_to_contained_and_back_is_identity() {
        for payload in ["", "   ", "bogus", "\u{1F600}\u{0301}", "\0", "a\nb\tc"] {
            let shared = GridParseError::InvalidValue(payload);
            let owned = shared.to_contained();
            assert_eq!(
                owned,
                GridParseErrorOwned::InvalidValue(payload.to_string().into())
            );
            assert_eq!(
                owned.to_shared(),
                shared,
                "{payload:?} must survive the round-trip"
            );
        }
        // A 100k-char payload: no truncation, no panic.
        let huge = "x".repeat(100_000);
        let owned = GridParseError::InvalidValue(&huge).to_contained();
        assert_eq!(
            owned.to_shared(),
            GridParseError::InvalidValue(huge.as_str())
        );
    }
    #[test]
    fn grid_auto_flow_parse_error_to_contained_and_back_is_identity() {
        for payload in ["", "bogus", "\u{1F600}", "\0"] {
            let shared = GridAutoFlowParseError::InvalidValue(payload);
            let owned = shared.to_contained();
            assert_eq!(
                owned,
                GridAutoFlowParseErrorOwned::InvalidValue(payload.to_string().into())
            );
            assert_eq!(owned.to_shared(), shared);
        }
        let huge = "x".repeat(100_000);
        let owned = GridAutoFlowParseError::InvalidValue(&huge).to_contained();
        assert_eq!(
            owned.to_shared(),
            GridAutoFlowParseError::InvalidValue(huge.as_str())
        );
    }
    #[test]
    fn justify_self_parse_error_to_contained_and_back_is_identity() {
        for payload in ["", "bogus", "\u{1F600}", "\0"] {
            let shared = JustifySelfParseError::InvalidValue(payload);
            let owned = shared.to_contained();
            assert_eq!(
                owned,
                JustifySelfParseErrorOwned::InvalidValue(payload.to_string().into())
            );
            assert_eq!(owned.to_shared(), shared);
        }
        let huge = "x".repeat(100_000);
        let owned = JustifySelfParseError::InvalidValue(&huge).to_contained();
        assert_eq!(
            owned.to_shared(),
            JustifySelfParseError::InvalidValue(huge.as_str())
        );
    }
    #[test]
    fn justify_items_parse_error_to_contained_and_back_is_identity() {
        for payload in ["", "bogus", "\u{1F600}", "\0"] {
            let shared = JustifyItemsParseError::InvalidValue(payload);
            let owned = shared.to_contained();
            assert_eq!(
                owned,
                JustifyItemsParseErrorOwned::InvalidValue(payload.to_string().into())
            );
            assert_eq!(owned.to_shared(), shared);
        }
        let huge = "x".repeat(100_000);
        let owned = JustifyItemsParseError::InvalidValue(&huge).to_contained();
        assert_eq!(
            owned.to_shared(),
            JustifyItemsParseError::InvalidValue(huge.as_str())
        );
    }
    #[test]
    fn error_types_round_trip_through_a_real_parse_failure() {
        // The realistic path: borrow an error out of a parser, own it, hand it back.
        let input = String::from("  span x  ");
        let owned = parse_grid_placement(&input).unwrap_err().to_contained();
        drop(input); // the owned form must not borrow the parsed input
        assert_eq!(owned.to_shared(), GridParseError::InvalidValue("span x"));
        let flow = String::from("bogus-flow");
        let owned_flow = parse_layout_grid_auto_flow(&flow)
            .unwrap_err()
            .to_contained();
        drop(flow);
        assert_eq!(
            owned_flow.to_shared(),
            GridAutoFlowParseError::InvalidValue("bogus-flow")
        );
    }
    // ---------------------------------------------------------------------
    // Debug / display invariants
    // ---------------------------------------------------------------------
    #[test]
    fn debug_impls_match_print_as_css_value() {
        // GridTrackSizing / GridTemplate / GridPlacement all forward Debug to the CSS
        // printer, so a Debug regression is a serialization regression.
        let track = parse_grid_track_owned("minmax(100px, max-content)").unwrap();
        assert_eq!(format!("{track:?}"), track.print_as_css_value());
        let template = parse_grid_template("100px auto").unwrap();
        assert_eq!(format!("{template:?}"), template.print_as_css_value());
        let placement = parse_grid_placement("1 / span 2").unwrap();
        assert_eq!(format!("{placement:?}"), placement.print_as_css_value());
        let minmax = GridMinMax::new(
            GridTrackSizing::Fixed(PixelValue::px(1.0)),
            GridTrackSizing::Auto,
        );
        assert_eq!(format!("{minmax:?}"), "minmax(1px, auto)");
    }
}