1
//! CSS properties for 2D and 3D transformations.
2

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

            
10
#[cfg(feature = "parser")]
11
use crate::props::basic::{
12
    error::WrongComponentCountError,
13
    length::parse_float_value,
14
    parse::{parse_parentheses, ParenthesisParseError, ParenthesisParseErrorOwned},
15
};
16
use crate::{
17
    codegen::format::GetHash,
18
    corety::AzString,
19
    props::{
20
        basic::{
21
            angle::{
22
                parse_angle_value, AngleValue, CssAngleValueParseError,
23
                CssAngleValueParseErrorOwned,
24
            },
25
            length::{PercentageParseError, PercentageValue},
26
            pixel::{
27
                parse_pixel_value, CssPixelValueParseError, CssPixelValueParseErrorOwned,
28
                PixelValue,
29
            },
30
            FloatValue,
31
        },
32
        formatter::PrintAsCssValue,
33
    },
34
};
35

            
36
// -- Data Structures --
37

            
38
/// Represents a `perspective-origin` attribute
39
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
40
#[repr(C)]
41
pub struct StylePerspectiveOrigin {
42
    pub x: PixelValue,
43
    pub y: PixelValue,
44
}
45

            
46
impl StylePerspectiveOrigin {
47
    #[must_use]
48
12
    pub fn interpolate(&self, other: &Self, t: f32) -> Self {
49
12
        Self {
50
12
            x: self.x.interpolate(&other.x, t),
51
12
            y: self.y.interpolate(&other.y, t),
52
12
        }
53
12
    }
54
}
55

            
56
impl PrintAsCssValue for StylePerspectiveOrigin {
57
3
    fn print_as_css_value(&self) -> String {
58
3
        format!("{} {}", self.x, self.y)
59
3
    }
60
}
61

            
62
/// Represents a `transform-origin` attribute
63
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
64
#[repr(C)]
65
pub struct StyleTransformOrigin {
66
    pub x: PixelValue,
67
    pub y: PixelValue,
68
}
69

            
70
impl Default for StyleTransformOrigin {
71
5650
    fn default() -> Self {
72
5650
        Self {
73
5650
            x: PixelValue::const_percent(50),
74
5650
            y: PixelValue::const_percent(50),
75
5650
        }
76
5650
    }
77
}
78

            
79
impl StyleTransformOrigin {
80
    #[must_use]
81
30
    pub fn interpolate(&self, other: &Self, t: f32) -> Self {
82
30
        Self {
83
30
            x: self.x.interpolate(&other.x, t),
84
30
            y: self.y.interpolate(&other.y, t),
85
30
        }
86
30
    }
87
}
88

            
89
impl PrintAsCssValue for StyleTransformOrigin {
90
4
    fn print_as_css_value(&self) -> String {
91
4
        format!("{} {}", self.x, self.y)
92
4
    }
93
}
94

            
95
// Formatting to Rust code
96
impl crate::codegen::format::FormatAsRustCode for StylePerspectiveOrigin {
97
    fn format_as_rust_code(&self, _tabs: usize) -> String {
98
        format!(
99
            "StylePerspectiveOrigin {{ x: {}, y: {} }}",
100
            crate::codegen::format::format_pixel_value(&self.x),
101
            crate::codegen::format::format_pixel_value(&self.y)
102
        )
103
    }
104
}
105

            
106
// Formatting to Rust code for StyleTransformOrigin
107
impl crate::codegen::format::FormatAsRustCode for StyleTransformOrigin {
108
    fn format_as_rust_code(&self, _tabs: usize) -> String {
109
        format!(
110
            "StyleTransformOrigin {{ x: {}, y: {} }}",
111
            crate::codegen::format::format_pixel_value(&self.x),
112
            crate::codegen::format::format_pixel_value(&self.y)
113
        )
114
    }
115
}
116

            
117
/// Represents a `backface-visibility` attribute
118
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
119
#[repr(C)]
120
pub enum StyleBackfaceVisibility {
121
    #[default]
122
    Visible,
123
    Hidden,
124
}
125

            
126
impl PrintAsCssValue for StyleBackfaceVisibility {
127
2
    fn print_as_css_value(&self) -> String {
128
2
        String::from(match self {
129
1
            Self::Hidden => "hidden",
130
1
            Self::Visible => "visible",
131
        })
132
2
    }
133
}
134

            
135
/// Whether dragging this element moves the WINDOW — azul's `app-region`.
136
///
137
/// Modelled on Electron's `-webkit-app-region`, and accepted under both
138
/// `-azul-app-region` and `-webkit-app-region` so existing CSS ports over
139
/// unchanged.
140
///
141
/// ```css
142
/// .titlebar        { -azul-app-region: drag; }
143
/// .titlebar button { -azul-app-region: no-drag; }
144
/// ```
145
///
146
/// This is what lets an application turn window decorations off and draw its
147
/// own title bar without losing what a native one does: drag to move,
148
/// double-click to maximize.
149
///
150
/// It does NOT cascade. A drag region names the exact element that is
151
/// draggable, and inheriting it would make every button, label and icon inside
152
/// a title bar drag the window instead of doing its own job — which is the bug
153
/// `no-drag` exists to undo in Electron. Here the default simply never
154
/// propagates, so children opt IN rather than out.
155
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
156
#[repr(C)]
157
pub enum StyleAppRegion {
158
    /// Normal content: the element handles its own input.
159
    #[default]
160
    NoDrag,
161
    /// Dragging this element moves the window; double-clicking it toggles
162
    /// maximize/restore.
163
    Drag,
164
}
165

            
166
impl PrintAsCssValue for StyleAppRegion {
167
2
    fn print_as_css_value(&self) -> String {
168
2
        String::from(match self {
169
1
            Self::Drag => "drag",
170
1
            Self::NoDrag => "no-drag",
171
        })
172
2
    }
173
}
174

            
175
/// Represents one component of a `transform` attribute
176
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
177
#[repr(C, u8)]
178
pub enum StyleTransform {
179
    Matrix(StyleTransformMatrix2D),
180
    Matrix3D(StyleTransformMatrix3D),
181
    Translate(StyleTransformTranslate2D),
182
    Translate3D(StyleTransformTranslate3D),
183
    TranslateX(PixelValue),
184
    TranslateY(PixelValue),
185
    TranslateZ(PixelValue),
186
    Rotate(AngleValue),
187
    Rotate3D(StyleTransformRotate3D),
188
    RotateX(AngleValue),
189
    RotateY(AngleValue),
190
    RotateZ(AngleValue),
191
    Scale(StyleTransformScale2D),
192
    Scale3D(StyleTransformScale3D),
193
    ScaleX(PercentageValue),
194
    ScaleY(PercentageValue),
195
    ScaleZ(PercentageValue),
196
    Skew(StyleTransformSkew2D),
197
    SkewX(AngleValue),
198
    SkewY(AngleValue),
199
    Perspective(PixelValue),
200
}
201

            
202
impl_option!(
203
    StyleTransform,
204
    OptionStyleTransform,
205
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd]
206
);
207

            
208
impl_vec!(
209
    StyleTransform,
210
    StyleTransformVec,
211
    StyleTransformVecDestructor,
212
    StyleTransformVecDestructorType,
213
    StyleTransformVecSlice,
214
    OptionStyleTransform
215
);
216
impl_vec_debug!(StyleTransform, StyleTransformVec);
217
impl_vec_partialord!(StyleTransform, StyleTransformVec);
218
impl_vec_ord!(StyleTransform, StyleTransformVec);
219
impl_vec_clone!(
220
    StyleTransform,
221
    StyleTransformVec,
222
    StyleTransformVecDestructor
223
);
224
impl_vec_partialeq!(StyleTransform, StyleTransformVec);
225
impl_vec_eq!(StyleTransform, StyleTransformVec);
226
impl_vec_hash!(StyleTransform, StyleTransformVec);
227

            
228
impl PrintAsCssValue for StyleTransformVec {
229
1
    fn print_as_css_value(&self) -> String {
230
1
        self.as_ref()
231
1
            .iter()
232
1
            .map(PrintAsCssValue::print_as_css_value)
233
1
            .collect::<Vec<_>>()
234
1
            .join(" ")
235
1
    }
236
}
237

            
238
// Formatting to Rust code for StyleTransformVec
239
impl crate::codegen::format::FormatAsRustCode for StyleTransformVec {
240
    fn format_as_rust_code(&self, _tabs: usize) -> String {
241
        format!(
242
            "StyleTransformVec::from_const_slice(STYLE_TRANSFORM_{}_ITEMS)",
243
            self.get_hash()
244
        )
245
    }
246
}
247

            
248
impl PrintAsCssValue for StyleTransform {
249
39
    fn print_as_css_value(&self) -> String {
250
39
        match self {
251
2
            Self::Matrix(m) => format!(
252
2
                "matrix({}, {}, {}, {}, {}, {})",
253
                m.a, m.b, m.c, m.d, m.tx, m.ty
254
            ),
255
2
            Self::Matrix3D(m) => format!(
256
2
                "matrix3d({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})",
257
                m.m11,
258
                m.m12,
259
                m.m13,
260
                m.m14,
261
                m.m21,
262
                m.m22,
263
                m.m23,
264
                m.m24,
265
                m.m31,
266
                m.m32,
267
                m.m33,
268
                m.m34,
269
                m.m41,
270
                m.m42,
271
                m.m43,
272
                m.m44
273
            ),
274
2
            Self::Translate(t) => format!("translate({}, {})", t.x, t.y),
275
2
            Self::Translate3D(t) => format!("translate3d({}, {}, {})", t.x, t.y, t.z),
276
2
            Self::TranslateX(x) => format!("translateX({x})"),
277
2
            Self::TranslateY(y) => format!("translateY({y})"),
278
2
            Self::TranslateZ(z) => format!("translateZ({z})"),
279
2
            Self::Rotate(r) => format!("rotate({r})"),
280
2
            Self::Rotate3D(r) => {
281
2
                format!("rotate3d({}, {}, {}, {})", r.x, r.y, r.z, r.angle)
282
            }
283
2
            Self::RotateX(x) => format!("rotateX({x})"),
284
2
            Self::RotateY(y) => format!("rotateY({y})"),
285
2
            Self::RotateZ(z) => format!("rotateZ({z})"),
286
2
            Self::Scale(s) => format!("scale({}, {})", s.x, s.y),
287
2
            Self::Scale3D(s) => format!("scale3d({}, {}, {})", s.x, s.y, s.z),
288
1
            Self::ScaleX(x) => format!("scaleX({x})"),
289
1
            Self::ScaleY(y) => format!("scaleY({y})"),
290
1
            Self::ScaleZ(z) => format!("scaleZ({z})"),
291
2
            Self::Skew(sk) => format!("skew({}, {})", sk.x, sk.y),
292
2
            Self::SkewX(x) => format!("skewX({x})"),
293
2
            Self::SkewY(y) => format!("skewY({y})"),
294
2
            Self::Perspective(dist) => format!("perspective({dist})"),
295
        }
296
39
    }
297
}
298

            
299
/// Represents a CSS `matrix(a, b, c, d, tx, ty)` 2D transform function.
300
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
301
#[repr(C)]
302
pub struct StyleTransformMatrix2D {
303
    pub a: FloatValue,
304
    pub b: FloatValue,
305
    pub c: FloatValue,
306
    pub d: FloatValue,
307
    pub tx: FloatValue,
308
    pub ty: FloatValue,
309
}
310

            
311
impl Default for StyleTransformMatrix2D {
312
2
    fn default() -> Self {
313
2
        Self {
314
2
            a: FloatValue::const_new(1),
315
2
            b: FloatValue::const_new(0),
316
2
            c: FloatValue::const_new(0),
317
2
            d: FloatValue::const_new(1),
318
2
            tx: FloatValue::const_new(0),
319
2
            ty: FloatValue::const_new(0),
320
2
        }
321
2
    }
322
}
323

            
324
/// Represents a CSS `matrix3d(...)` 3D transform function (4x4 matrix).
325
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
326
#[repr(C)]
327
pub struct StyleTransformMatrix3D {
328
    pub m11: FloatValue,
329
    pub m12: FloatValue,
330
    pub m13: FloatValue,
331
    pub m14: FloatValue,
332
    pub m21: FloatValue,
333
    pub m22: FloatValue,
334
    pub m23: FloatValue,
335
    pub m24: FloatValue,
336
    pub m31: FloatValue,
337
    pub m32: FloatValue,
338
    pub m33: FloatValue,
339
    pub m34: FloatValue,
340
    pub m41: FloatValue,
341
    pub m42: FloatValue,
342
    pub m43: FloatValue,
343
    pub m44: FloatValue,
344
}
345

            
346
impl Default for StyleTransformMatrix3D {
347
3
    fn default() -> Self {
348
3
        Self {
349
3
            m11: FloatValue::const_new(1),
350
3
            m12: FloatValue::const_new(0),
351
3
            m13: FloatValue::const_new(0),
352
3
            m14: FloatValue::const_new(0),
353
3
            m21: FloatValue::const_new(0),
354
3
            m22: FloatValue::const_new(1),
355
3
            m23: FloatValue::const_new(0),
356
3
            m24: FloatValue::const_new(0),
357
3
            m31: FloatValue::const_new(0),
358
3
            m32: FloatValue::const_new(0),
359
3
            m33: FloatValue::const_new(1),
360
3
            m34: FloatValue::const_new(0),
361
3
            m41: FloatValue::const_new(0),
362
3
            m42: FloatValue::const_new(0),
363
3
            m43: FloatValue::const_new(0),
364
3
            m44: FloatValue::const_new(1),
365
3
        }
366
3
    }
367
}
368

            
369
/// Represents a CSS `translate(x, y)` 2D translation.
370
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
371
#[repr(C)]
372
pub struct StyleTransformTranslate2D {
373
    pub x: PixelValue,
374
    pub y: PixelValue,
375
}
376

            
377
/// Represents a CSS `translate3d(x, y, z)` 3D translation.
378
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
379
#[repr(C)]
380
pub struct StyleTransformTranslate3D {
381
    pub x: PixelValue,
382
    pub y: PixelValue,
383
    pub z: PixelValue,
384
}
385

            
386
/// Represents a CSS `rotate3d(x, y, z, angle)` 3D rotation.
387
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
388
#[repr(C)]
389
pub struct StyleTransformRotate3D {
390
    pub x: FloatValue,
391
    pub y: FloatValue,
392
    pub z: FloatValue,
393
    pub angle: AngleValue,
394
}
395

            
396
/// Represents a CSS `scale(x, y)` 2D scaling.
397
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
398
#[repr(C)]
399
pub struct StyleTransformScale2D {
400
    pub x: FloatValue,
401
    pub y: FloatValue,
402
}
403

            
404
/// Represents a CSS `scale3d(x, y, z)` 3D scaling.
405
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
406
#[repr(C)]
407
pub struct StyleTransformScale3D {
408
    pub x: FloatValue,
409
    pub y: FloatValue,
410
    pub z: FloatValue,
411
}
412

            
413
/// Represents a CSS `skew(x, y)` 2D skew transformation.
414
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
415
#[repr(C)]
416
pub struct StyleTransformSkew2D {
417
    pub x: AngleValue,
418
    pub y: AngleValue,
419
}
420

            
421
// -- Errors --
422

            
423
#[derive(Clone, PartialEq, Eq)]
424
pub enum CssStyleTransformParseError<'a> {
425
    InvalidTransform(&'a str),
426
    InvalidParenthesis(ParenthesisParseError<'a>),
427
    WrongNumberOfComponents {
428
        expected: usize,
429
        got: usize,
430
        input: &'a str,
431
    },
432
    NumberParseError(ParseFloatError),
433
    PixelValueParseError(CssPixelValueParseError<'a>),
434
    AngleValueParseError(CssAngleValueParseError<'a>),
435
    PercentageValueParseError(PercentageParseError),
436
}
437

            
438
impl_debug_as_display!(CssStyleTransformParseError<'a>);
439
impl_display! { CssStyleTransformParseError<'a>, {
440
    InvalidTransform(e) => format!("Invalid transform property: \"{}\"", e),
441
    InvalidParenthesis(e) => format!("Invalid transform property - parenthesis error: {}", e),
442
    WrongNumberOfComponents { expected, got, input } => format!("Invalid number of components: expected {}, got {}: \"{}\"", expected, got, input),
443
    NumberParseError(e) => format!("Could not parse number: {}", e),
444
    PixelValueParseError(e) => format!("Invalid pixel value: {}", e),
445
    AngleValueParseError(e) => format!("Invalid angle value: {}", e),
446
    PercentageValueParseError(e) => format!("Error parsing percentage: {}", e),
447
}}
448

            
449
impl_from! { ParenthesisParseError<'a>, CssStyleTransformParseError::InvalidParenthesis }
450
impl_from! { CssPixelValueParseError<'a>, CssStyleTransformParseError::PixelValueParseError }
451
impl_from! { CssAngleValueParseError<'a>, CssStyleTransformParseError::AngleValueParseError }
452
// Written out (not impl_from!): ParseFloatError carries no lifetime, so the
453
// macro's `<'a>` would be used only by the target type (single_use_lifetimes).
454
impl From<ParseFloatError> for CssStyleTransformParseError<'_> {
455
16
    fn from(e: ParseFloatError) -> Self {
456
16
        Self::NumberParseError(e)
457
16
    }
458
}
459

            
460
impl From<PercentageParseError> for CssStyleTransformParseError<'_> {
461
    fn from(p: PercentageParseError) -> Self {
462
        Self::PercentageValueParseError(p)
463
    }
464
}
465

            
466
#[derive(Debug, Clone, PartialEq, Eq)]
467
#[repr(C, u8)]
468
pub enum CssStyleTransformParseErrorOwned {
469
    InvalidTransform(AzString),
470
    InvalidParenthesis(ParenthesisParseErrorOwned),
471
    WrongNumberOfComponents(WrongComponentCountError),
472
    NumberParseError(crate::props::basic::error::ParseFloatError),
473
    PixelValueParseError(CssPixelValueParseErrorOwned),
474
    AngleValueParseError(CssAngleValueParseErrorOwned),
475
    PercentageValueParseError(PercentageParseError),
476
}
477

            
478
impl CssStyleTransformParseError<'_> {
479
    #[must_use]
480
49
    pub fn to_contained(&self) -> CssStyleTransformParseErrorOwned {
481
49
        match self {
482
6
            Self::InvalidTransform(s) => {
483
6
                CssStyleTransformParseErrorOwned::InvalidTransform((*s).to_string().into())
484
            }
485
15
            Self::InvalidParenthesis(e) => {
486
15
                CssStyleTransformParseErrorOwned::InvalidParenthesis(e.to_contained())
487
            }
488
9
            Self::WrongNumberOfComponents {
489
9
                expected,
490
9
                got,
491
9
                input,
492
9
            } => CssStyleTransformParseErrorOwned::WrongNumberOfComponents(
493
9
                WrongComponentCountError {
494
9
                    expected: *expected,
495
9
                    got: *got,
496
9
                    input: (*input).to_string().into(),
497
9
                },
498
9
            ),
499
5
            Self::NumberParseError(e) => {
500
5
                CssStyleTransformParseErrorOwned::NumberParseError(e.clone().into())
501
            }
502
5
            Self::PixelValueParseError(e) => {
503
5
                CssStyleTransformParseErrorOwned::PixelValueParseError(e.to_contained())
504
            }
505
5
            Self::AngleValueParseError(e) => {
506
5
                CssStyleTransformParseErrorOwned::AngleValueParseError(e.to_contained())
507
            }
508
4
            Self::PercentageValueParseError(e) => {
509
4
                CssStyleTransformParseErrorOwned::PercentageValueParseError(e.clone())
510
            }
511
        }
512
49
    }
513
}
514

            
515
impl CssStyleTransformParseErrorOwned {
516
    #[must_use]
517
29
    pub fn to_shared(&self) -> CssStyleTransformParseError<'_> {
518
29
        match self {
519
3
            Self::InvalidTransform(s) => CssStyleTransformParseError::InvalidTransform(s),
520
10
            Self::InvalidParenthesis(e) => {
521
10
                CssStyleTransformParseError::InvalidParenthesis(e.to_shared())
522
            }
523
5
            Self::WrongNumberOfComponents(e) => {
524
5
                CssStyleTransformParseError::WrongNumberOfComponents {
525
5
                    expected: e.expected,
526
5
                    got: e.got,
527
5
                    input: e.input.as_str(),
528
5
                }
529
            }
530
3
            Self::NumberParseError(e) => CssStyleTransformParseError::NumberParseError(e.to_std()),
531
3
            Self::PixelValueParseError(e) => {
532
3
                CssStyleTransformParseError::PixelValueParseError(e.to_shared())
533
            }
534
3
            Self::AngleValueParseError(e) => {
535
3
                CssStyleTransformParseError::AngleValueParseError(e.to_shared())
536
            }
537
2
            Self::PercentageValueParseError(e) => {
538
2
                CssStyleTransformParseError::PercentageValueParseError(e.clone())
539
            }
540
        }
541
29
    }
542
}
543

            
544
#[derive(Clone, PartialEq, Eq)]
545
pub enum CssStyleTransformOriginParseError<'a> {
546
    WrongNumberOfComponents {
547
        expected: usize,
548
        got: usize,
549
        input: &'a str,
550
    },
551
    PixelValueParseError(CssPixelValueParseError<'a>),
552
}
553

            
554
impl_debug_as_display!(CssStyleTransformOriginParseError<'a>);
555
impl_display! { CssStyleTransformOriginParseError<'a>, {
556
    WrongNumberOfComponents { expected, got, input } => format!("Invalid number of components: expected {}, got {}: \"{}\"", expected, got, input),
557
    PixelValueParseError(e) => format!("Invalid pixel value: {}", e),
558
}}
559
impl_from! { CssPixelValueParseError<'a>, CssStyleTransformOriginParseError::PixelValueParseError }
560

            
561
#[derive(Debug, Clone, PartialEq, Eq)]
562
#[repr(C, u8)]
563
pub enum CssStyleTransformOriginParseErrorOwned {
564
    WrongNumberOfComponents(WrongComponentCountError),
565
    PixelValueParseError(CssPixelValueParseErrorOwned),
566
}
567

            
568
impl CssStyleTransformOriginParseError<'_> {
569
    #[must_use]
570
5
    pub fn to_contained(&self) -> CssStyleTransformOriginParseErrorOwned {
571
5
        match self {
572
2
            Self::WrongNumberOfComponents {
573
2
                expected,
574
2
                got,
575
2
                input,
576
2
            } => CssStyleTransformOriginParseErrorOwned::WrongNumberOfComponents(
577
2
                WrongComponentCountError {
578
2
                    expected: *expected,
579
2
                    got: *got,
580
2
                    input: (*input).to_string().into(),
581
2
                },
582
2
            ),
583
3
            Self::PixelValueParseError(e) => {
584
3
                CssStyleTransformOriginParseErrorOwned::PixelValueParseError(e.to_contained())
585
            }
586
        }
587
5
    }
588
}
589

            
590
impl CssStyleTransformOriginParseErrorOwned {
591
    #[must_use]
592
5
    pub fn to_shared(&self) -> CssStyleTransformOriginParseError<'_> {
593
5
        match self {
594
2
            Self::WrongNumberOfComponents(e) => {
595
2
                CssStyleTransformOriginParseError::WrongNumberOfComponents {
596
2
                    expected: e.expected,
597
2
                    got: e.got,
598
2
                    input: e.input.as_str(),
599
2
                }
600
            }
601
3
            Self::PixelValueParseError(e) => {
602
3
                CssStyleTransformOriginParseError::PixelValueParseError(e.to_shared())
603
            }
604
        }
605
5
    }
606
}
607

            
608
#[derive(Clone, PartialEq, Eq)]
609
pub enum CssStylePerspectiveOriginParseError<'a> {
610
    WrongNumberOfComponents {
611
        expected: usize,
612
        got: usize,
613
        input: &'a str,
614
    },
615
    PixelValueParseError(CssPixelValueParseError<'a>),
616
}
617

            
618
impl_debug_as_display!(CssStylePerspectiveOriginParseError<'a>);
619
impl_display! { CssStylePerspectiveOriginParseError<'a>, {
620
    WrongNumberOfComponents { expected, got, input } => format!("Invalid number of components: expected {}, got {}: \"{}\"", expected, got, input),
621
    PixelValueParseError(e) => format!("Invalid pixel value: {}", e),
622
}}
623
impl_from! { CssPixelValueParseError<'a>, CssStylePerspectiveOriginParseError::PixelValueParseError }
624

            
625
#[derive(Debug, Clone, PartialEq, Eq)]
626
#[repr(C, u8)]
627
pub enum CssStylePerspectiveOriginParseErrorOwned {
628
    WrongNumberOfComponents(WrongComponentCountError),
629
    PixelValueParseError(CssPixelValueParseErrorOwned),
630
}
631

            
632
impl CssStylePerspectiveOriginParseError<'_> {
633
    #[must_use]
634
4
    pub fn to_contained(&self) -> CssStylePerspectiveOriginParseErrorOwned {
635
4
        match self {
636
2
            Self::WrongNumberOfComponents {
637
2
                expected,
638
2
                got,
639
2
                input,
640
2
            } => CssStylePerspectiveOriginParseErrorOwned::WrongNumberOfComponents(
641
2
                WrongComponentCountError {
642
2
                    expected: *expected,
643
2
                    got: *got,
644
2
                    input: (*input).to_string().into(),
645
2
                },
646
2
            ),
647
2
            Self::PixelValueParseError(e) => {
648
2
                CssStylePerspectiveOriginParseErrorOwned::PixelValueParseError(e.to_contained())
649
            }
650
        }
651
4
    }
652
}
653

            
654
impl CssStylePerspectiveOriginParseErrorOwned {
655
    #[must_use]
656
4
    pub fn to_shared(&self) -> CssStylePerspectiveOriginParseError<'_> {
657
4
        match self {
658
2
            Self::WrongNumberOfComponents(e) => {
659
2
                CssStylePerspectiveOriginParseError::WrongNumberOfComponents {
660
2
                    expected: e.expected,
661
2
                    got: e.got,
662
2
                    input: e.input.as_str(),
663
2
                }
664
            }
665
2
            Self::PixelValueParseError(e) => {
666
2
                CssStylePerspectiveOriginParseError::PixelValueParseError(e.to_shared())
667
            }
668
        }
669
4
    }
670
}
671

            
672
#[derive(Clone, PartialEq, Eq)]
673
pub enum CssBackfaceVisibilityParseError<'a> {
674
    InvalidValue(&'a str),
675
}
676

            
677
impl_debug_as_display!(CssBackfaceVisibilityParseError<'a>);
678
impl_display! { CssBackfaceVisibilityParseError<'a>, {
679
    InvalidValue(s) => format!("Invalid value for backface-visibility: \"{}\", expected \"visible\" or \"hidden\"", s),
680
}}
681

            
682
#[derive(Debug, Clone, PartialEq, Eq)]
683
#[repr(C, u8)]
684
pub enum CssBackfaceVisibilityParseErrorOwned {
685
    InvalidValue(AzString),
686
}
687

            
688
#[derive(Clone, PartialEq, Eq)]
689
#[repr(C, u8)]
690
pub enum CssAppRegionParseError<'a> {
691
    InvalidValue(&'a str),
692
}
693

            
694
impl_debug_as_display!(CssAppRegionParseError<'a>);
695
impl_display! { CssAppRegionParseError<'a>, {
696
    InvalidValue(s) => format!("Invalid value for app-region: \"{}\", expected \"drag\" or \"no-drag\"", s),
697
}}
698

            
699
#[derive(Debug, Clone, PartialEq, Eq)]
700
#[repr(C, u8)]
701
pub enum CssAppRegionParseErrorOwned {
702
    InvalidValue(AzString),
703
}
704

            
705
impl CssAppRegionParseError<'_> {
706
    #[must_use]
707
    pub fn to_contained(&self) -> CssAppRegionParseErrorOwned {
708
        match self {
709
            Self::InvalidValue(s) => CssAppRegionParseErrorOwned::InvalidValue((*s).into()),
710
        }
711
    }
712
}
713

            
714
impl CssAppRegionParseErrorOwned {
715
    #[must_use]
716
    pub fn to_shared(&self) -> CssAppRegionParseError<'_> {
717
        match self {
718
            Self::InvalidValue(s) => CssAppRegionParseError::InvalidValue(s.as_str()),
719
        }
720
    }
721
}
722

            
723
impl CssBackfaceVisibilityParseError<'_> {
724
    #[must_use]
725
5
    pub fn to_contained(&self) -> CssBackfaceVisibilityParseErrorOwned {
726
5
        match self {
727
5
            Self::InvalidValue(s) => {
728
5
                CssBackfaceVisibilityParseErrorOwned::InvalidValue((*s).to_string().into())
729
            }
730
        }
731
5
    }
732
}
733

            
734
impl CssBackfaceVisibilityParseErrorOwned {
735
    #[must_use]
736
5
    pub fn to_shared(&self) -> CssBackfaceVisibilityParseError<'_> {
737
5
        match self {
738
5
            Self::InvalidValue(s) => CssBackfaceVisibilityParseError::InvalidValue(s),
739
        }
740
5
    }
741
}
742

            
743
// -- Parsers --
744

            
745
#[cfg(feature = "parser")]
746
/// # Errors
747
///
748
/// Returns an error if `input` is not a valid CSS `transform-vec` value.
749
902
pub fn parse_style_transform_vec(
750
902
    input: &str,
751
902
) -> Result<StyleTransformVec, CssStyleTransformParseError<'_>> {
752
902
    crate::props::basic::parse::split_string_respect_whitespace(input)
753
902
        .iter()
754
20934
        .map(|i| parse_style_transform(i))
755
902
        .collect::<Result<Vec<_>, _>>()
756
902
        .map(Into::into)
757
902
}
758

            
759
#[cfg(feature = "parser")]
760
#[allow(clippy::too_many_lines)]
761
// large but cohesive: single-purpose CSS parser/formatter/dispatch table (one branch per
762
// property/variant)
763
/// # Errors
764
///
765
/// Returns an error if `input` is not a valid CSS `transform` value.
766
21094
pub fn parse_style_transform(
767
21094
    input: &str,
768
21094
) -> Result<StyleTransform, CssStyleTransformParseError<'_>> {
769
18
    fn get_numbers(
770
18
        input: &str,
771
18
        expected: usize,
772
18
    ) -> Result<Vec<f32>, CssStyleTransformParseError<'_>> {
773
18
        let numbers: Vec<_> = input
774
18
            .split(',')
775
99
            .map(|s| s.trim().parse::<f32>())
776
18
            .collect::<Result<_, _>>()?;
777
12
        if numbers.len() == expected {
778
7
            Ok(numbers)
779
        } else {
780
5
            Err(CssStyleTransformParseError::WrongNumberOfComponents {
781
5
                expected,
782
5
                got: numbers.len(),
783
5
                input,
784
5
            })
785
        }
786
18
    }
787

            
788
21094
    let (transform_type, transform_values) = parse_parentheses(
789
21094
        input,
790
21094
        &[
791
21094
            "matrix",
792
21094
            "matrix3d",
793
21094
            "translate",
794
21094
            "translate3d",
795
21094
            "translateX",
796
21094
            "translateY",
797
21094
            "translateZ",
798
21094
            "rotate",
799
21094
            "rotate3d",
800
21094
            "rotateX",
801
21094
            "rotateY",
802
21094
            "rotateZ",
803
21094
            "scale",
804
21094
            "scale3d",
805
21094
            "scaleX",
806
21094
            "scaleY",
807
21094
            "scaleZ",
808
21094
            "skew",
809
21094
            "skewX",
810
21094
            "skewY",
811
21094
            "perspective",
812
21094
        ],
813
47
    )?;
814

            
815
21047
    match transform_type {
816
21047
        "matrix" => {
817
9
            let nums = get_numbers(transform_values, 6)?;
818
3
            Ok(StyleTransform::Matrix(StyleTransformMatrix2D {
819
3
                a: FloatValue::new(nums[0]),
820
3
                b: FloatValue::new(nums[1]),
821
3
                c: FloatValue::new(nums[2]),
822
3
                d: FloatValue::new(nums[3]),
823
3
                tx: FloatValue::new(nums[4]),
824
3
                ty: FloatValue::new(nums[5]),
825
3
            }))
826
        }
827
21038
        "matrix3d" => {
828
5
            let nums = get_numbers(transform_values, 16)?;
829
2
            Ok(StyleTransform::Matrix3D(StyleTransformMatrix3D {
830
2
                m11: FloatValue::new(nums[0]),
831
2
                m12: FloatValue::new(nums[1]),
832
2
                m13: FloatValue::new(nums[2]),
833
2
                m14: FloatValue::new(nums[3]),
834
2
                m21: FloatValue::new(nums[4]),
835
2
                m22: FloatValue::new(nums[5]),
836
2
                m23: FloatValue::new(nums[6]),
837
2
                m24: FloatValue::new(nums[7]),
838
2
                m31: FloatValue::new(nums[8]),
839
2
                m32: FloatValue::new(nums[9]),
840
2
                m33: FloatValue::new(nums[10]),
841
2
                m34: FloatValue::new(nums[11]),
842
2
                m41: FloatValue::new(nums[12]),
843
2
                m42: FloatValue::new(nums[13]),
844
2
                m43: FloatValue::new(nums[14]),
845
2
                m44: FloatValue::new(nums[15]),
846
2
            }))
847
        }
848
21033
        "translate" => {
849
42
            let components: Vec<_> = transform_values.split(',').collect();
850

            
851
            // translate() takes exactly 1 or 2 parameters (x, or x and y)
852
42
            if components.len() > 2 {
853
2
                return Err(CssStyleTransformParseError::WrongNumberOfComponents {
854
2
                    expected: 2,
855
2
                    got: components.len(),
856
2
                    input: transform_values,
857
2
                });
858
40
            }
859

            
860
40
            let x = parse_pixel_value(
861
40
                components
862
40
                    .first()
863
40
                    .ok_or(CssStyleTransformParseError::WrongNumberOfComponents {
864
40
                        expected: 2,
865
40
                        got: 0,
866
40
                        input: transform_values,
867
40
                    })?
868
40
                    .trim(),
869
2
            )?;
870
38
            let y = match components.get(1) {
871
37
                Some(c) => parse_pixel_value(c.trim())?,
872
1
                None => PixelValue::px(0.0),
873
            };
874
37
            Ok(StyleTransform::Translate(StyleTransformTranslate2D {
875
37
                x,
876
37
                y,
877
37
            }))
878
        }
879
20991
        "translate3d" => {
880
7
            let components: Vec<_> = transform_values.split(',').collect();
881
7
            let x = parse_pixel_value(
882
7
                components
883
7
                    .first()
884
7
                    .ok_or(CssStyleTransformParseError::WrongNumberOfComponents {
885
7
                        expected: 3,
886
7
                        got: 0,
887
7
                        input: transform_values,
888
7
                    })?
889
7
                    .trim(),
890
1
            )?;
891
6
            let y = parse_pixel_value(
892
6
                components
893
6
                    .get(1)
894
6
                    .ok_or(CssStyleTransformParseError::WrongNumberOfComponents {
895
6
                        expected: 3,
896
6
                        got: 1,
897
6
                        input: transform_values,
898
6
                    })?
899
6
                    .trim(),
900
            )?;
901
4
            let z = parse_pixel_value(
902
6
                components
903
6
                    .get(2)
904
6
                    .ok_or(CssStyleTransformParseError::WrongNumberOfComponents {
905
6
                        expected: 3,
906
6
                        got: 2,
907
6
                        input: transform_values,
908
6
                    })?
909
4
                    .trim(),
910
1
            )?;
911
3
            Ok(StyleTransform::Translate3D(StyleTransformTranslate3D {
912
3
                x,
913
3
                y,
914
3
                z,
915
3
            }))
916
        }
917
20984
        "translateX" => Ok(StyleTransform::TranslateX(parse_pixel_value(
918
20797
            transform_values,
919
9
        )?)),
920
187
        "translateY" => Ok(StyleTransform::TranslateY(parse_pixel_value(
921
3
            transform_values,
922
1
        )?)),
923
184
        "translateZ" => Ok(StyleTransform::TranslateZ(parse_pixel_value(
924
3
            transform_values,
925
1
        )?)),
926
181
        "rotate" => Ok(StyleTransform::Rotate(parse_angle_value(transform_values)?)),
927
68
        "rotate3d" => {
928
6
            let parts: Vec<_> = transform_values.splitn(4, ',').collect();
929
6
            if parts.len() != 4 {
930
2
                return Err(CssStyleTransformParseError::WrongNumberOfComponents {
931
2
                    expected: 4,
932
2
                    got: parts.len(),
933
2
                    input: transform_values,
934
2
                });
935
4
            }
936
4
            let x = parts[0].trim().parse::<f32>()?;
937
4
            let y = parts[1].trim().parse::<f32>()?;
938
4
            let z = parts[2].trim().parse::<f32>()?;
939
4
            let angle = parse_angle_value(parts[3].trim())?;
940
3
            Ok(StyleTransform::Rotate3D(StyleTransformRotate3D {
941
3
                x: FloatValue::new(x),
942
3
                y: FloatValue::new(y),
943
3
                z: FloatValue::new(z),
944
3
                angle,
945
3
            }))
946
        }
947
62
        "rotateX" => Ok(StyleTransform::RotateX(parse_angle_value(
948
4
            transform_values,
949
2
        )?)),
950
58
        "rotateY" => Ok(StyleTransform::RotateY(parse_angle_value(
951
3
            transform_values,
952
1
        )?)),
953
55
        "rotateZ" => Ok(StyleTransform::RotateZ(parse_angle_value(
954
3
            transform_values,
955
1
        )?)),
956
52
        "scale" => {
957
16
            let parts: Vec<_> = transform_values.split(',').collect();
958
16
            if parts.is_empty() || parts.len() > 2 {
959
1
                return Err(CssStyleTransformParseError::WrongNumberOfComponents {
960
1
                    expected: 2,
961
1
                    got: parts.len(),
962
1
                    input: transform_values,
963
1
                });
964
15
            }
965
15
            let x = parts[0].trim().parse::<f32>()?;
966
14
            let y = if parts.len() == 2 {
967
6
                parts[1].trim().parse::<f32>()?
968
            } else {
969
8
                x
970
            };
971
13
            Ok(StyleTransform::Scale(StyleTransformScale2D {
972
13
                x: FloatValue::new(x),
973
13
                y: FloatValue::new(y),
974
13
            }))
975
        }
976
36
        "scale3d" => {
977
4
            let nums = get_numbers(transform_values, 3)?;
978
2
            Ok(StyleTransform::Scale3D(StyleTransformScale3D {
979
2
                x: FloatValue::new(nums[0]),
980
2
                y: FloatValue::new(nums[1]),
981
2
                z: FloatValue::new(nums[2]),
982
2
            }))
983
        }
984
32
        "scaleX" => Ok(StyleTransform::ScaleX(PercentageValue::new(
985
8
            transform_values.trim().parse::<f32>()? * 100.0,
986
        ))),
987
24
        "scaleY" => Ok(StyleTransform::ScaleY(PercentageValue::new(
988
3
            transform_values.trim().parse::<f32>()? * 100.0,
989
        ))),
990
21
        "scaleZ" => Ok(StyleTransform::ScaleZ(PercentageValue::new(
991
2
            transform_values.trim().parse::<f32>()? * 100.0,
992
        ))),
993
19
        "skew" => {
994
7
            let components: Vec<_> = transform_values.split(',').collect();
995
7
            if components.is_empty() || components.len() > 2 {
996
1
                return Err(CssStyleTransformParseError::WrongNumberOfComponents {
997
1
                    expected: 2,
998
1
                    got: components.len(),
999
1
                    input: transform_values,
1
                });
6
            }
6
            let x = parse_angle_value(components[0].trim())?;
5
            let y = match components.get(1) {
4
                Some(c) => parse_angle_value(c.trim())?,
1
                None => AngleValue::deg(0.0),
            };
4
            Ok(StyleTransform::Skew(StyleTransformSkew2D { x, y }))
        }
12
        "skewX" => Ok(StyleTransform::SkewX(parse_angle_value(transform_values)?)),
8
        "skewY" => Ok(StyleTransform::SkewY(parse_angle_value(transform_values)?)),
4
        "perspective" => Ok(StyleTransform::Perspective(parse_pixel_value(
4
            transform_values,
2
        )?)),
        _ => unreachable!(),
    }
21094
}
#[cfg(feature = "parser")]
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `transform-origin` value.
34
pub fn parse_style_transform_origin(
34
    input: &str,
34
) -> Result<StyleTransformOrigin, CssStyleTransformOriginParseError<'_>> {
    // Helper to parse position keywords or pixel values
46
    fn parse_position_component(
46
        s: &str,
46
        is_horizontal: bool,
46
    ) -> Result<PixelValue, CssPixelValueParseError<'_>> {
46
        match s.trim() {
46
            "left" if is_horizontal => Ok(PixelValue::percent(0.0)),
41
            "center" => Ok(PixelValue::percent(50.0)),
39
            "right" if is_horizontal => Ok(PixelValue::percent(100.0)),
38
            "top" if !is_horizontal => Ok(PixelValue::percent(0.0)),
33
            "bottom" if !is_horizontal => Ok(PixelValue::percent(100.0)),
35
            _ => parse_pixel_value(s),
        }
46
    }
34
    let components: Vec<_> = input.split_whitespace().collect();
34
    if components.len() != 2 {
7
        return Err(CssStyleTransformOriginParseError::WrongNumberOfComponents {
7
            expected: 2,
7
            got: components.len(),
7
            input,
7
        });
27
    }
27
    let x = parse_position_component(components[0], true)?;
19
    let y = parse_position_component(components[1], false)?;
17
    Ok(StyleTransformOrigin { x, y })
34
}
#[cfg(feature = "parser")]
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `perspective-origin` value.
17
pub fn parse_style_perspective_origin(
17
    input: &str,
17
) -> Result<StylePerspectiveOrigin, CssStylePerspectiveOriginParseError<'_>> {
17
    let components: Vec<_> = input.split_whitespace().collect();
17
    if components.len() != 2 {
3
        return Err(
3
            CssStylePerspectiveOriginParseError::WrongNumberOfComponents {
3
                expected: 2,
3
                got: components.len(),
3
                input,
3
            },
3
        );
14
    }
14
    let x = parse_pixel_value(components[0])?;
6
    let y = parse_pixel_value(components[1])?;
6
    Ok(StylePerspectiveOrigin { x, y })
17
}
#[cfg(feature = "parser")]
/// # Errors
///
/// Returns an error if `input` is not `drag` or `no-drag`.
///
/// Electron writes `-webkit-app-region: drag`; both spellings map here, so CSS
/// written for Electron works unchanged.
1369
pub fn parse_style_app_region(input: &str) -> Result<StyleAppRegion, CssAppRegionParseError<'_>> {
1369
    match input.trim() {
1369
        "drag" => Ok(StyleAppRegion::Drag),
3
        "no-drag" | "none" => Ok(StyleAppRegion::NoDrag),
1
        _ => Err(CssAppRegionParseError::InvalidValue(input)),
    }
1369
}
#[cfg(feature = "parser")]
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `backface-visibility` value.
24
pub fn parse_style_backface_visibility(
24
    input: &str,
24
) -> Result<StyleBackfaceVisibility, CssBackfaceVisibilityParseError<'_>> {
24
    match input.trim() {
24
        "visible" => Ok(StyleBackfaceVisibility::Visible),
20
        "hidden" => Ok(StyleBackfaceVisibility::Hidden),
17
        _ => Err(CssBackfaceVisibilityParseError::InvalidValue(input)),
    }
24
}
#[cfg(all(test, feature = "parser"))]
mod tests {
    // Tests assert that parsed values equal the exact source literals.
    #![allow(clippy::float_cmp)]
    use super::*;
    #[test]
1
    fn test_parse_transform_vec() {
1
        let result =
1
            parse_style_transform_vec("translateX(10px) rotate(90deg) scale(0.5, 0.5)").unwrap();
1
        assert_eq!(result.len(), 3);
1
        assert!(matches!(
1
            result.as_slice()[0],
            StyleTransform::TranslateX(_)
        ));
1
        assert!(matches!(result.as_slice()[1], StyleTransform::Rotate(_)));
1
        assert!(matches!(result.as_slice()[2], StyleTransform::Scale(_)));
1
    }
    #[test]
1
    fn test_parse_transform_functions() {
        // Translate
1
        assert_eq!(
1
            parse_style_transform("translateX(50%)").unwrap(),
1
            StyleTransform::TranslateX(PixelValue::percent(50.0))
        );
1
        let translate = parse_style_transform("translate(10px, -20px)").unwrap();
1
        if let StyleTransform::Translate(t) = translate {
1
            assert_eq!(t.x, PixelValue::px(10.0));
1
            assert_eq!(t.y, PixelValue::px(-20.0));
        } else {
            panic!("Expected Translate");
        }
        // Scale
1
        assert_eq!(
1
            parse_style_transform("scaleY(1.2)").unwrap(),
1
            StyleTransform::ScaleY(PercentageValue::new(120.0))
        );
1
        let scale = parse_style_transform("scale(2, 0.5)").unwrap();
1
        if let StyleTransform::Scale(s) = scale {
1
            assert_eq!(s.x.get(), 2.0);
1
            assert_eq!(s.y.get(), 0.5);
        } else {
            panic!("Expected Scale");
        }
        // Rotate
1
        assert_eq!(
1
            parse_style_transform("rotate(0.25turn)").unwrap(),
1
            StyleTransform::Rotate(AngleValue::turn(0.25))
        );
        // Skew
1
        assert_eq!(
1
            parse_style_transform("skewX(-10deg)").unwrap(),
1
            StyleTransform::SkewX(AngleValue::deg(-10.0))
        );
1
        let skew = parse_style_transform("skew(20deg, 30deg)").unwrap();
1
        if let StyleTransform::Skew(s) = skew {
1
            assert_eq!(s.x, AngleValue::deg(20.0));
1
            assert_eq!(s.y, AngleValue::deg(30.0));
        } else {
            panic!("Expected Skew");
        }
1
    }
    #[test]
1
    fn test_parse_transform_origin() {
1
        let result = parse_style_transform_origin("50% 50%").unwrap();
1
        assert_eq!(result.x, PixelValue::percent(50.0));
1
        assert_eq!(result.y, PixelValue::percent(50.0));
1
        let result = parse_style_transform_origin("left top").unwrap();
1
        assert_eq!(result.x, PixelValue::percent(0.0));
1
        assert_eq!(result.y, PixelValue::percent(0.0));
1
        let result = parse_style_transform_origin("20px bottom").unwrap();
1
        assert_eq!(result.x, PixelValue::px(20.0));
1
        assert_eq!(result.y, PixelValue::percent(100.0));
1
    }
    #[test]
1
    fn test_parse_backface_visibility() {
1
        assert_eq!(
1
            parse_style_backface_visibility("visible").unwrap(),
            StyleBackfaceVisibility::Visible
        );
1
        assert_eq!(
1
            parse_style_backface_visibility("hidden").unwrap(),
            StyleBackfaceVisibility::Hidden
        );
1
        assert!(parse_style_backface_visibility("none").is_err());
1
    }
    #[test]
1
    fn test_parse_transform_errors() {
        // Wrong function name
1
        assert!(parse_style_transform("translatex(10px)").is_err());
        // Wrong number of args
1
        assert!(parse_style_transform("translate(1, 2, 3)").is_err());
        // Single-arg forms (CSS spec compliant)
1
        let scale1 = parse_style_transform("scale(2)").unwrap();
1
        if let StyleTransform::Scale(s) = scale1 {
1
            assert_eq!(s.x.get(), 2.0);
1
            assert_eq!(s.y.get(), 2.0);
        } else {
            panic!("Expected Scale");
        }
1
        let translate1 = parse_style_transform("translate(10px)").unwrap();
1
        if let StyleTransform::Translate(t) = translate1 {
1
            assert_eq!(t.x, PixelValue::px(10.0));
1
            assert_eq!(t.y, PixelValue::px(0.0));
        } else {
            panic!("Expected Translate");
        }
1
        let skew1 = parse_style_transform("skew(20deg)").unwrap();
1
        if let StyleTransform::Skew(s) = skew1 {
1
            assert_eq!(s.x, AngleValue::deg(20.0));
1
            assert_eq!(s.y, AngleValue::deg(0.0));
        } else {
            panic!("Expected Skew");
        }
        // rotate3d with angle unit
1
        let rot3d = parse_style_transform("rotate3d(1, 0, 0, 45deg)").unwrap();
1
        if let StyleTransform::Rotate3D(r) = rot3d {
1
            assert_eq!(r.x.get(), 1.0);
1
            assert_eq!(r.angle, AngleValue::deg(45.0));
        } else {
            panic!("Expected Rotate3D");
        }
        // Invalid value
1
        assert!(parse_style_transform("rotate(10px)").is_err());
1
        assert!(parse_style_transform("translateX(auto)").is_err());
1
    }
}
#[cfg(all(test, feature = "parser"))]
#[allow(clippy::too_many_lines, clippy::float_cmp)]
mod autotest_generated {
    // Tests compare parsed values against exact source literals, and deliberately
    // feed NaN/inf through the numeric encoders.
    use super::*;
    use crate::props::basic::length::SizeMetric;
    // ---------------------------------------------------------------------
    // helpers
    // ---------------------------------------------------------------------
    /// Every `FloatValue` is stored as an `isize`, so `get()` can never be
    /// NaN/inf no matter what went in. Used as a blanket invariant below.
    fn assert_encodable(pv: PixelValue) {
        assert!(pv.number.get().is_finite());
    }
    fn all_roundtrippable_transforms() -> Vec<StyleTransform> {
        vec![
            StyleTransform::Matrix(StyleTransformMatrix2D::default()),
            StyleTransform::Matrix3D(StyleTransformMatrix3D::default()),
            StyleTransform::Translate(StyleTransformTranslate2D {
                x: PixelValue::px(10.0),
                y: PixelValue::px(-20.0),
            }),
            StyleTransform::Translate3D(StyleTransformTranslate3D {
                x: PixelValue::px(1.0),
                y: PixelValue::em(2.0),
                z: PixelValue::pt(-3.5),
            }),
            StyleTransform::TranslateX(PixelValue::percent(50.0)),
            StyleTransform::TranslateY(PixelValue::px(0.0)),
            StyleTransform::TranslateZ(PixelValue::rem(1.25)),
            StyleTransform::Rotate(AngleValue::deg(90.0)),
            StyleTransform::Rotate3D(StyleTransformRotate3D {
                x: FloatValue::new(1.0),
                y: FloatValue::new(0.0),
                z: FloatValue::new(0.0),
                angle: AngleValue::turn(0.25),
            }),
            StyleTransform::RotateX(AngleValue::rad(1.5)),
            StyleTransform::RotateY(AngleValue::grad(100.0)),
            StyleTransform::RotateZ(AngleValue::deg(-45.0)),
            StyleTransform::Scale(StyleTransformScale2D {
                x: FloatValue::new(2.0),
                y: FloatValue::new(0.5),
            }),
            StyleTransform::Scale3D(StyleTransformScale3D {
                x: FloatValue::new(1.0),
                y: FloatValue::new(-1.0),
                z: FloatValue::new(0.25),
            }),
            StyleTransform::Skew(StyleTransformSkew2D {
                x: AngleValue::deg(20.0),
                y: AngleValue::deg(30.0),
            }),
            StyleTransform::SkewX(AngleValue::deg(-10.0)),
            StyleTransform::SkewY(AngleValue::deg(10.0)),
            StyleTransform::Perspective(PixelValue::px(500.0)),
        ]
    }
    // =====================================================================
    // parse_style_transform  --  malformed / boundary / unicode
    // =====================================================================
    #[test]
    fn transform_rejects_empty_and_whitespace_only_input() {
        for input in ["", "   ", "\t\n", "\r\n\t "] {
            let err = parse_style_transform(input).unwrap_err();
            assert!(
                matches!(
                    err,
                    CssStyleTransformParseError::InvalidParenthesis(
                        ParenthesisParseError::EmptyInput
                    )
                ),
                "expected EmptyInput for {input:?}, got {err}"
            );
        }
    }
    #[test]
    fn transform_rejects_garbage_without_panicking() {
        // No opening brace at all.
        assert!(matches!(
            parse_style_transform("garbage").unwrap_err(),
            CssStyleTransformParseError::InvalidParenthesis(
                ParenthesisParseError::NoOpeningBraceFound
            )
        ));
        // Opening brace, no closing brace.
        assert!(matches!(
            parse_style_transform("rotate(90deg").unwrap_err(),
            CssStyleTransformParseError::InvalidParenthesis(
                ParenthesisParseError::NoClosingBraceFound
            )
        ));
        // Known-but-miscased function name is NOT accepted (CSS is case-insensitive
        // for function names; azul's stopword table is case-sensitive).
        assert!(matches!(
            parse_style_transform("translatex(10px)").unwrap_err(),
            CssStyleTransformParseError::InvalidParenthesis(
                ParenthesisParseError::StopWordNotFound("translatex")
            )
        ));
        assert!(matches!(
            parse_style_transform("ROTATE(90deg)").unwrap_err(),
            CssStyleTransformParseError::InvalidParenthesis(
                ParenthesisParseError::StopWordNotFound("ROTATE")
            )
        ));
        // Random byte soup, none of which forms a grammar.
        for input in [
            "((((",
            ")",
            "()",
            "(rotate)",
            "rotate",
            ";;;",
            "\0(\0)",
            "-1",
            "rotate(,,,,)",
            "matrix(,)",
        ] {
            assert!(
                parse_style_transform(input).is_err(),
                "expected Err for {input:?}"
            );
        }
    }
    #[test]
    fn transform_never_hits_the_unreachable_arm_for_near_miss_stopwords() {
        // parse_style_transform ends in `_ => unreachable!()`; it is only sound as
        // long as parse_parentheses can never hand back a non-listed stopword.
        // Probe names that are prefixes/suffixes/case-variants of real ones.
        for name in [
            "translat",
            "translateXX",
            "xtranslateX",
            "rotate3",
            "rotate3D",
            "scale4d",
            "skewZ",
            "perspectives",
            "matrix2d",
            "MATRIX",
            "",
            " rotate",
        ] {
            let input = alloc::format!("{name}(1)");
            let res = parse_style_transform(&input);
            // Either a clean parse error or (for " rotate", which trims to "rotate")
            // a normal result - but never a panic.
            let _ = res;
        }
        // " rotate(1)" trims down to a valid rotate with a bare-number degree.
        assert_eq!(
            parse_style_transform("  rotate(1)  ").unwrap(),
            StyleTransform::Rotate(AngleValue::deg(1.0))
        );
    }
    #[test]
    fn transform_handles_non_ascii_and_multibyte_input() {
        // parse_parentheses slices `input[..first_open_brace]`; a multibyte char
        // right before the '(' must not split a UTF-8 boundary.
        for input in [
            "\u{1F600}",
            "\u{1F600}(1)",
            "rotate(\u{1F600})",
            "rotate\u{0301}(1deg)",
            "\u{1F600}rotate(1deg)",
            "translateX(\u{1F600}px)",
            "translate(\u{1F600}, \u{1F600})",
            "matrix3d(\u{4F60}\u{597D})",
            "sk\u{0435}wX(10deg)", // cyrillic 'е' homoglyph
        ] {
            assert!(
                parse_style_transform(input).is_err(),
                "expected Err for {input:?}"
            );
        }
        assert!(matches!(
            parse_style_transform("rotate(\u{1F600})").unwrap_err(),
            CssStyleTransformParseError::AngleValueParseError(
                CssAngleValueParseError::InvalidAngle("\u{1F600}")
            )
        ));
    }
    #[test]
    fn transform_boundary_numbers_saturate_instead_of_panicking() {
        // -0 collapses to +0 in the isize-backed encoding.
        assert_eq!(
            parse_style_transform("translateX(-0)").unwrap(),
            StyleTransform::TranslateX(PixelValue::px(0.0))
        );
        assert_eq!(
            parse_style_transform("translateX(0)").unwrap(),
            StyleTransform::TranslateX(PixelValue::px(0.0))
        );
        // NaN parses as a float (Rust accepts "NaN"), and the f32 -> isize cast
        // maps NaN to 0. So `translateX(NaN)` silently becomes `0px`.
        let StyleTransform::TranslateX(nan_px) = parse_style_transform("translateX(NaN)").unwrap()
        else {
            panic!("expected TranslateX");
        };
        assert_eq!(nan_px.number.number(), 0);
        assert_encodable(nan_px);
        // Infinities (literal, and via decimal overflow) saturate to isize::MAX/MIN.
        for input in [
            "translateX(inf)",
            "translateX(1e400)",
            "translateX(1e400px)",
        ] {
            let StyleTransform::TranslateX(px) = parse_style_transform(input).unwrap() else {
                panic!("expected TranslateX for {input}");
            };
            assert_eq!(px.number.number(), isize::MAX, "{input}");
            assert_encodable(px);
        }
        let StyleTransform::TranslateX(neg) = parse_style_transform("translateX(-inf)").unwrap()
        else {
            panic!("expected TranslateX");
        };
        assert_eq!(neg.number.number(), isize::MIN);
        assert_encodable(neg);
        // i64::MAX / f64-scale magnitudes: fine, just saturated.
        for input in [
            "translateX(9223372036854775807px)",
            "translateX(-9223372036854775808px)",
            "translateX(1e-400px)",
            "translateX(0.0000000000001px)",
        ] {
            assert!(parse_style_transform(input).is_ok(), "{input}");
        }
        // Angles take the same path: NaN -> 0deg, inf -> saturated.
        assert_eq!(
            parse_style_transform("rotate(NaN)").unwrap(),
            StyleTransform::Rotate(AngleValue::deg(0.0))
        );
        let StyleTransform::Rotate(a) = parse_style_transform("rotate(infdeg)").unwrap() else {
            panic!("expected Rotate");
        };
        assert_eq!(a.number.number(), isize::MAX);
        // scaleX multiplies by 100 before encoding - inf * 100 must not trap.
        let StyleTransform::ScaleX(p) = parse_style_transform("scaleX(NaN)").unwrap() else {
            panic!("expected ScaleX");
        };
        assert_eq!(p, PercentageValue::new(0.0));
        assert!(parse_style_transform("scaleX(inf)").is_ok());
        assert!(parse_style_transform("scaleX(1e40)").is_ok());
    }
    #[test]
    fn transform_component_counts_are_enforced() {
        // matrix wants exactly 6.
        assert!(matches!(
            parse_style_transform("matrix(1,2,3,4,5)").unwrap_err(),
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: 6,
                got: 5,
                ..
            }
        ));
        assert!(matches!(
            parse_style_transform("matrix(1,2,3,4,5,6,7)").unwrap_err(),
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: 6,
                got: 7,
                ..
            }
        ));
        // matrix3d wants exactly 16.
        assert!(matches!(
            parse_style_transform("matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0)").unwrap_err(),
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: 16,
                got: 15,
                ..
            }
        ));
        // translate takes at most 2.
        assert!(matches!(
            parse_style_transform("translate(1px, 2px, 3px)").unwrap_err(),
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: 2,
                got: 3,
                ..
            }
        ));
        // scale takes at most 2.
        assert!(matches!(
            parse_style_transform("scale(1, 2, 3)").unwrap_err(),
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: 2,
                got: 3,
                ..
            }
        ));
        // skew takes at most 2.
        assert!(matches!(
            parse_style_transform("skew(1deg, 2deg, 3deg)").unwrap_err(),
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: 2,
                got: 3,
                ..
            }
        ));
        // rotate3d wants exactly 4 (splitn(4) makes >4 fold into the angle, which
        // then fails to parse as an angle).
        assert!(matches!(
            parse_style_transform("rotate3d(1, 0, 0)").unwrap_err(),
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: 4,
                got: 3,
                ..
            }
        ));
        assert!(parse_style_transform("rotate3d(1, 0, 0, 45deg, 99)").is_err());
        // translate3d wants exactly 3 when short...
        assert!(matches!(
            parse_style_transform("translate3d(1px, 2px)").unwrap_err(),
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: 3,
                got: 2,
                ..
            }
        ));
        // scale3d wants exactly 3.
        assert!(matches!(
            parse_style_transform("scale3d(1, 2)").unwrap_err(),
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: 3,
                got: 2,
                ..
            }
        ));
    }
    #[test]
    fn transform_translate3d_silently_ignores_extra_components() {
        // BUG (leniency): unlike matrix/scale3d (which go through get_numbers and
        // check the count), translate3d only indexes [0], [1], [2] and never
        // rejects a 4th+ component. Per CSS this must be a parse error.
        // Pinned as current behaviour so a future fix shows up as a diff here.
        let parsed = parse_style_transform("translate3d(1px, 2px, 3px, 4px, 5px)").unwrap();
        assert_eq!(
            parsed,
            StyleTransform::Translate3D(StyleTransformTranslate3D {
                x: PixelValue::px(1.0),
                y: PixelValue::px(2.0),
                z: PixelValue::px(3.0),
            })
        );
    }
    #[test]
    fn transform_ignores_junk_after_the_closing_paren() {
        // BUG (leniency): parse_parentheses uses find('(') .. rfind(')'), so any
        // trailing junk that contains no ')' is silently dropped. Per CSS,
        // "rotate(90deg)garbage" is invalid. Pinned as current behaviour.
        assert_eq!(
            parse_style_transform("rotate(90deg)garbage").unwrap(),
            StyleTransform::Rotate(AngleValue::deg(90.0))
        );
        assert_eq!(
            parse_style_transform("rotate(90deg) ;drop table").unwrap(),
            StyleTransform::Rotate(AngleValue::deg(90.0))
        );
        // ...but junk containing a ')' gets swallowed INTO the argument, which then
        // fails - so the leniency is content-dependent, not a clean "trim" rule.
        assert!(parse_style_transform("rotate(90deg))").is_err());
        assert!(parse_style_transform("rotate(90deg) rotate(1deg)").is_err());
    }
    #[test]
    fn transform_empty_argument_lists_are_rejected() {
        for input in [
            "matrix()",
            "matrix3d()",
            "translate()",
            "translate3d()",
            "translateX()",
            "translateY()",
            "translateZ()",
            "rotate()",
            "rotate3d()",
            "rotateX()",
            "rotateY()",
            "rotateZ()",
            "scale()",
            "scale3d()",
            "scaleX()",
            "scaleY()",
            "scaleZ()",
            "skew()",
            "skewX()",
            "skewY()",
            "perspective()",
        ] {
            assert!(
                parse_style_transform(input).is_err(),
                "expected Err for {input:?}"
            );
        }
        // Trailing-comma forms, too.
        for input in [
            "translate(10px,)",
            "translate3d(1px,2px,)",
            "scale(2,)",
            "skew(10deg,)",
            "matrix(1,2,3,4,5,)",
        ] {
            assert!(
                parse_style_transform(input).is_err(),
                "expected Err for {input:?}"
            );
        }
    }
    #[test]
    fn transform_wrong_unit_kinds_are_rejected() {
        // A length where an angle is expected, and vice versa.
        assert!(parse_style_transform("rotate(10px)").is_err());
        assert!(parse_style_transform("rotateX(10px)").is_err());
        assert!(parse_style_transform("skewY(10px)").is_err());
        assert!(parse_style_transform("translateX(10deg)").is_err());
        assert!(parse_style_transform("perspective(10deg)").is_err());
        // Keywords are not lengths.
        assert!(parse_style_transform("translateX(auto)").is_err());
        assert!(parse_style_transform("translateX(none)").is_err());
        // scaleX takes a bare number, NOT a percentage (see the round-trip test).
        assert!(parse_style_transform("scaleX(120%)").is_err());
    }
    #[test]
    fn transform_extremely_long_input_does_not_hang_or_panic() {
        // ~100k-digit number: must scan in linear time and saturate, not panic.
        let huge = alloc::format!("translateX({}px)", "9".repeat(100_000));
        let StyleTransform::TranslateX(px) = parse_style_transform(&huge).unwrap() else {
            panic!("expected TranslateX");
        };
        assert_eq!(px.number.number(), isize::MAX);
        // Long garbage of the same size must simply be an error.
        let junk = alloc::format!("translateX({})", "a".repeat(100_000));
        assert!(parse_style_transform(&junk).is_err());
        // Long stopword: no quadratic blowup in the stopword scan.
        let long_name = alloc::format!("{}(1px)", "x".repeat(100_000));
        assert!(parse_style_transform(&long_name).is_err());
    }
    #[test]
    fn transform_deeply_nested_parens_do_not_stack_overflow() {
        // parse_parentheses is iterative; prove there is no recursion by feeding it
        // 10k levels of nesting.
        let open_only = "rotate(".repeat(10_000);
        assert!(matches!(
            parse_style_transform(&open_only).unwrap_err(),
            CssStyleTransformParseError::InvalidParenthesis(
                ParenthesisParseError::NoClosingBraceFound
            )
        ));
        let braces = "(".repeat(10_000);
        assert!(matches!(
            parse_style_transform(&braces).unwrap_err(),
            CssStyleTransformParseError::InvalidParenthesis(
                ParenthesisParseError::StopWordNotFound("")
            )
        ));
        let balanced = alloc::format!(
            "translateX({}1px{})",
            "translateX(".repeat(1_000),
            ")".repeat(1_000)
        );
        assert!(parse_style_transform(&balanced).is_err());
        let closers = ")".repeat(10_000);
        assert!(parse_style_transform(&closers).is_err());
    }
    #[test]
    fn transform_valid_minimal_positive_control() {
        assert_eq!(
            parse_style_transform("rotate(0deg)").unwrap(),
            StyleTransform::Rotate(AngleValue::deg(0.0))
        );
    }
    // =====================================================================
    // parse_style_transform_vec
    // =====================================================================
    #[test]
    fn transform_vec_accepts_empty_and_whitespace_only_input_as_an_empty_list() {
        // NOTE: "" is NOT an error - split_string_respect_whitespace yields zero
        // tokens and the collect() succeeds with an empty Vec. Callers relying on
        // `parse_style_transform_vec("").is_err()` to reject an empty declaration
        // will not get one. Pinned as current behaviour.
        for input in ["", "   ", "\t\n", "\r \n \t"] {
            let v = parse_style_transform_vec(input).unwrap();
            assert_eq!(v.len(), 0, "{input:?}");
        }
    }
    #[test]
    fn transform_vec_propagates_the_first_error() {
        assert!(parse_style_transform_vec("translateX(10px) garbage").is_err());
        assert!(parse_style_transform_vec("garbage translateX(10px)").is_err());
        assert!(parse_style_transform_vec("translateX(10px) rotate(10px)").is_err());
        assert!(parse_style_transform_vec("\u{1F600}").is_err());
    }
    #[test]
    fn transform_vec_keeps_whitespace_inside_parens_together() {
        // "scale(2, 0.5)" contains a space at depth 1 - it must stay one token.
        let v = parse_style_transform_vec("scale(2, 0.5) matrix(1, 0, 0, 1, 0, 0)").unwrap();
        assert_eq!(v.len(), 2);
        assert!(matches!(v.as_slice()[0], StyleTransform::Scale(_)));
        assert!(matches!(v.as_slice()[1], StyleTransform::Matrix(_)));
        // Repeated / redundant whitespace collapses.
        let v = parse_style_transform_vec("  translateX(1px)\t\trotate(2deg)\n ").unwrap();
        assert_eq!(v.len(), 2);
    }
    #[test]
    fn transform_vec_extremely_long_list_does_not_hang() {
        let long = "translateX(1px) ".repeat(20_000);
        let v = parse_style_transform_vec(&long).unwrap();
        assert_eq!(v.len(), 20_000);
        for t in v.as_slice() {
            assert_eq!(*t, StyleTransform::TranslateX(PixelValue::px(1.0)));
        }
    }
    #[test]
    fn transform_vec_unbalanced_parens_do_not_underflow_the_depth_counter() {
        // split_string_respect_whitespace does `depth -= 1` on every ')' with no
        // floor; a run of closers drives it negative. Must not panic in debug.
        let closers = ")".repeat(10_000);
        assert!(parse_style_transform_vec(&closers).is_err());
        let mixed = alloc::format!("{} {}", ")".repeat(5_000), "(".repeat(5_000));
        assert!(parse_style_transform_vec(&mixed).is_err());
    }
    // =====================================================================
    // parse_style_transform_origin
    // =====================================================================
    #[test]
    fn transform_origin_requires_exactly_two_components() {
        for (input, got) in [("", 0), ("50%", 1), ("left", 1), ("50% 50% 50%", 3)] {
            let err = parse_style_transform_origin(input).unwrap_err();
            assert!(
                matches!(
                    err,
                    CssStyleTransformOriginParseError::WrongNumberOfComponents {
                        expected: 2,
                        got: g,
                        ..
                    } if g == got
                ),
                "{input:?} -> {err}"
            );
        }
        // Whitespace-only collapses to zero components.
        assert!(matches!(
            parse_style_transform_origin("   \t\n ").unwrap_err(),
            CssStyleTransformOriginParseError::WrongNumberOfComponents { got: 0, .. }
        ));
    }
    #[test]
    fn transform_origin_keywords_are_position_sensitive() {
        assert_eq!(
            parse_style_transform_origin("left top").unwrap(),
            StyleTransformOrigin {
                x: PixelValue::percent(0.0),
                y: PixelValue::percent(0.0),
            }
        );
        assert_eq!(
            parse_style_transform_origin("right bottom").unwrap(),
            StyleTransformOrigin {
                x: PixelValue::percent(100.0),
                y: PixelValue::percent(100.0),
            }
        );
        assert_eq!(
            parse_style_transform_origin("center center").unwrap(),
            StyleTransformOrigin::default()
        );
        // BUG (spec deviation): CSS allows the keywords in either order
        // ("top left" == "left top"). Here the horizontal slot rejects
        // "top"/"bottom" and the vertical slot rejects "left"/"right", so the
        // swapped form is an error. Pinned as current behaviour.
        assert!(parse_style_transform_origin("top left").is_err());
        assert!(parse_style_transform_origin("bottom right").is_err());
        assert!(parse_style_transform_origin("left left").is_err());
        assert!(parse_style_transform_origin("top top").is_err());
    }
    #[test]
    fn transform_origin_garbage_and_unicode_do_not_panic() {
        for input in [
            "\u{1F600} \u{1F600}",
            "left \u{1F600}",
            "NaN NaN",
            "auto auto",
            "-- --",
            "10 20",   // bare numbers -> px, actually valid
            "1px;2px", // no whitespace -> 1 component
        ] {
            let _ = parse_style_transform_origin(input);
        }
        // Bare numbers fall through to parse_pixel_value's px default.
        assert_eq!(
            parse_style_transform_origin("10 20").unwrap(),
            StyleTransformOrigin {
                x: PixelValue::px(10.0),
                y: PixelValue::px(20.0),
            }
        );
        assert!(matches!(
            parse_style_transform_origin("\u{1F600} \u{1F600}").unwrap_err(),
            CssStyleTransformOriginParseError::PixelValueParseError(_)
        ));
    }
    #[test]
    fn transform_origin_boundary_numbers_saturate() {
        let o = parse_style_transform_origin("inf% -inf%").unwrap();
        assert_eq!(o.x.number.number(), isize::MAX);
        assert_eq!(o.y.number.number(), isize::MIN);
        assert_encodable(o.x);
        assert_encodable(o.y);
        // NaN -> 0, keeping the metric.
        let o = parse_style_transform_origin("NaNpx NaN%").unwrap();
        assert_eq!(o.x, PixelValue::px(0.0));
        assert_eq!(o.y, PixelValue::percent(0.0));
        let o = parse_style_transform_origin("-0px 1e400px").unwrap();
        assert_eq!(o.x.number.number(), 0);
        assert_eq!(o.y.number.number(), isize::MAX);
    }
    #[test]
    fn transform_origin_extremely_long_input_does_not_hang() {
        let many = "50% ".repeat(20_000);
        assert!(matches!(
            parse_style_transform_origin(&many).unwrap_err(),
            CssStyleTransformOriginParseError::WrongNumberOfComponents { got: 20_000, .. }
        ));
        let huge = alloc::format!("{}px 0px", "9".repeat(100_000));
        assert!(parse_style_transform_origin(&huge).is_ok());
    }
    #[test]
    fn transform_origin_round_trips_through_its_css_repr() {
        for origin in [
            StyleTransformOrigin::default(),
            StyleTransformOrigin {
                x: PixelValue::px(20.0),
                y: PixelValue::percent(100.0),
            },
            StyleTransformOrigin {
                x: PixelValue::em(-1.5),
                y: PixelValue::rem(2.25),
            },
            StyleTransformOrigin {
                x: PixelValue::px(0.0),
                y: PixelValue::px(0.0),
            },
        ] {
            let css = origin.print_as_css_value();
            let reparsed = parse_style_transform_origin(&css)
                .unwrap_or_else(|e| panic!("{css:?} did not re-parse: {e}"));
            assert_eq!(reparsed, origin, "round-trip failed for {css:?}");
        }
    }
    // =====================================================================
    // parse_style_perspective_origin
    // =====================================================================
    #[test]
    fn perspective_origin_requires_exactly_two_components() {
        for (input, got) in [("", 0), ("50%", 1), ("1px 2px 3px", 3)] {
            let err = parse_style_perspective_origin(input).unwrap_err();
            assert!(
                matches!(
                    err,
                    CssStylePerspectiveOriginParseError::WrongNumberOfComponents {
                        expected: 2,
                        got: g,
                        ..
                    } if g == got
                ),
                "{input:?} -> {err}"
            );
        }
    }
    #[test]
    fn perspective_origin_does_not_accept_position_keywords() {
        // BUG (spec deviation): CSS `perspective-origin` accepts the same
        // left/center/right/top/bottom keywords as `transform-origin`, but this
        // parser only takes pixel values. Pinned as current behaviour.
        assert!(parse_style_perspective_origin("left top").is_err());
        assert!(parse_style_perspective_origin("center center").is_err());
        assert!(matches!(
            parse_style_perspective_origin("center center").unwrap_err(),
            CssStylePerspectiveOriginParseError::PixelValueParseError(_)
        ));
    }
    #[test]
    fn perspective_origin_garbage_boundary_and_unicode() {
        for input in ["\u{1F600} \u{1F600}", "auto auto", "-- --", "px px"] {
            assert!(
                parse_style_perspective_origin(input).is_err(),
                "expected Err for {input:?}"
            );
        }
        let o = parse_style_perspective_origin("inf -inf").unwrap();
        assert_eq!(o.x.number.number(), isize::MAX);
        assert_eq!(o.y.number.number(), isize::MIN);
        assert_encodable(o.x);
        assert_encodable(o.y);
        let o = parse_style_perspective_origin("NaN -0").unwrap();
        assert_eq!(o.x, PixelValue::px(0.0));
        assert_eq!(o.y, PixelValue::px(0.0));
        let huge = alloc::format!("{}px 0px", "9".repeat(100_000));
        assert!(parse_style_perspective_origin(&huge).is_ok());
    }
    #[test]
    fn perspective_origin_round_trips_through_its_css_repr() {
        for origin in [
            StylePerspectiveOrigin::default(),
            StylePerspectiveOrigin {
                x: PixelValue::px(100.0),
                y: PixelValue::percent(50.0),
            },
            StylePerspectiveOrigin {
                x: PixelValue::pt(-3.5),
                y: PixelValue::cm(1.0),
            },
        ] {
            let css = origin.print_as_css_value();
            let reparsed = parse_style_perspective_origin(&css)
                .unwrap_or_else(|e| panic!("{css:?} did not re-parse: {e}"));
            assert_eq!(reparsed, origin, "round-trip failed for {css:?}");
        }
    }
    // =====================================================================
    // parse_style_backface_visibility
    // =====================================================================
    #[test]
    fn backface_visibility_accepts_only_the_two_keywords() {
        assert_eq!(
            parse_style_backface_visibility("visible").unwrap(),
            StyleBackfaceVisibility::Visible
        );
        assert_eq!(
            parse_style_backface_visibility("hidden").unwrap(),
            StyleBackfaceVisibility::Hidden
        );
        // Surrounding whitespace is trimmed.
        assert_eq!(
            parse_style_backface_visibility("  \t visible \n ").unwrap(),
            StyleBackfaceVisibility::Visible
        );
        // Everything else is rejected - including case variants, substrings,
        // both keywords at once and zero-width joiners.
        for input in [
            "",
            "   ",
            "Visible",
            "HIDDEN",
            "visible hidden",
            "vis",
            "visiblee",
            "none",
            "0",
            "NaN",
            "\u{1F600}",
            "visible\u{200B}",
            "hidden;",
        ] {
            assert!(
                parse_style_backface_visibility(input).is_err(),
                "expected Err for {input:?}"
            );
        }
    }
    #[test]
    fn backface_visibility_error_carries_the_untrimmed_input() {
        // The match is on `input.trim()` but the error is built from `input`,
        // so the original (untrimmed) slice is what shows up in the message.
        let err = parse_style_backface_visibility("  bogus  ").unwrap_err();
        assert_eq!(
            err,
            CssBackfaceVisibilityParseError::InvalidValue("  bogus  ")
        );
        assert!(alloc::format!("{err}").contains("  bogus  "));
    }
    #[test]
    fn backface_visibility_extremely_long_input_does_not_hang() {
        let huge = "visible".repeat(100_000);
        assert!(parse_style_backface_visibility(&huge).is_err());
    }
    #[test]
    fn backface_visibility_round_trips_through_its_css_repr() {
        for v in [
            StyleBackfaceVisibility::Visible,
            StyleBackfaceVisibility::Hidden,
        ] {
            let css = v.print_as_css_value();
            assert_eq!(parse_style_backface_visibility(&css).unwrap(), v);
        }
        assert_eq!(
            StyleBackfaceVisibility::default(),
            StyleBackfaceVisibility::Visible
        );
    }
    // =====================================================================
    // StyleTransform / StyleTransformVec round-trips (encode == decode)
    // =====================================================================
    #[test]
    fn transform_print_parse_round_trip() {
        for t in all_roundtrippable_transforms() {
            let css = t.print_as_css_value();
            let reparsed = parse_style_transform(&css)
                .unwrap_or_else(|e| panic!("{css:?} did not re-parse: {e}"));
            assert_eq!(reparsed, t, "round-trip failed for {css:?}");
        }
    }
    #[test]
    fn transform_vec_print_parse_round_trip() {
        let v: StyleTransformVec = all_roundtrippable_transforms().into();
        let css = v.print_as_css_value();
        let reparsed = parse_style_transform_vec(&css)
            .unwrap_or_else(|e| panic!("{css:?} did not re-parse: {e}"));
        assert_eq!(reparsed.len(), v.len());
        assert_eq!(reparsed.as_slice(), v.as_slice());
    }
    #[test]
    fn scale_axis_print_does_not_round_trip() {
        // BUG: `StyleTransform::ScaleX/Y/Z` hold a `PercentageValue`, whose Display
        // appends a '%' ("scaleX(120%)"), but the parser reads the argument with a
        // bare `parse::<f32>()` and multiplies by 100. So print -> parse fails for
        // every ScaleX/ScaleY/ScaleZ, and the printed CSS is invalid per spec
        // (`scaleX()` takes a <number>, not a <percentage>).
        // Pinned as current behaviour; the fix is to print the raw number.
        for t in [
            StyleTransform::ScaleX(PercentageValue::new(120.0)),
            StyleTransform::ScaleY(PercentageValue::new(120.0)),
            StyleTransform::ScaleZ(PercentageValue::new(120.0)),
        ] {
            let css = t.print_as_css_value();
            assert!(css.contains('%'), "{css:?}");
            assert!(
                parse_style_transform(&css).is_err(),
                "{css:?} unexpectedly re-parsed - the ScaleX round-trip bug may be fixed"
            );
        }
        // The parser's own accepted form (a bare number) does work.
        assert_eq!(
            parse_style_transform("scaleX(1.2)").unwrap(),
            StyleTransform::ScaleX(PercentageValue::new(120.0))
        );
    }
    // =====================================================================
    // StyleTransformOrigin::interpolate / StylePerspectiveOrigin::interpolate
    // =====================================================================
    #[test]
    fn transform_origin_interpolate_endpoints_are_exact() {
        let a = StyleTransformOrigin {
            x: PixelValue::px(10.0),
            y: PixelValue::percent(0.0),
        };
        let b = StyleTransformOrigin {
            x: PixelValue::px(30.0),
            y: PixelValue::percent(100.0),
        };
        assert_eq!(a.interpolate(&b, 0.0), a);
        assert_eq!(a.interpolate(&b, 1.0), b);
        assert_eq!(
            a.interpolate(&b, 0.5),
            StyleTransformOrigin {
                x: PixelValue::px(20.0),
                y: PixelValue::percent(50.0),
            }
        );
        // Interpolating a value with itself is the identity for every finite t.
        for t in [-1.0, 0.0, 0.25, 1.0, 2.0, 1e30] {
            assert_eq!(a.interpolate(&a, t), a, "t = {t}");
        }
    }
    #[test]
    fn transform_origin_interpolate_extrapolates_outside_zero_one() {
        let a = StyleTransformOrigin {
            x: PixelValue::px(10.0),
            y: PixelValue::px(10.0),
        };
        let b = StyleTransformOrigin {
            x: PixelValue::px(30.0),
            y: PixelValue::px(30.0),
        };
        // t is NOT clamped.
        assert_eq!(a.interpolate(&b, -1.0).x, PixelValue::px(-10.0));
        assert_eq!(a.interpolate(&b, 2.0).x, PixelValue::px(50.0));
    }
    #[test]
    fn transform_origin_interpolate_with_nan_or_infinite_t_stays_defined() {
        let a = StyleTransformOrigin {
            x: PixelValue::px(10.0),
            y: PixelValue::percent(10.0),
        };
        let b = StyleTransformOrigin {
            x: PixelValue::px(30.0),
            y: PixelValue::percent(30.0),
        };
        // NaN t -> NaN value -> the f32->isize cast maps NaN to 0.
        let nan = a.interpolate(&b, f32::NAN);
        assert_eq!(nan.x.number.number(), 0);
        assert_eq!(nan.y.number.number(), 0);
        assert_eq!(nan.x.metric, SizeMetric::Px);
        assert_eq!(nan.y.metric, SizeMetric::Percent);
        assert_encodable(nan.x);
        assert_encodable(nan.y);
        // +inf t on an increasing range saturates to isize::MAX, -inf to isize::MIN.
        let pos = a.interpolate(&b, f32::INFINITY);
        assert_eq!(pos.x.number.number(), isize::MAX);
        assert_encodable(pos.x);
        let neg = a.interpolate(&b, f32::NEG_INFINITY);
        assert_eq!(neg.x.number.number(), isize::MIN);
        assert_encodable(neg.x);
        // inf * 0 (identical endpoints) is NaN, which collapses to 0.
        let degenerate = a.interpolate(&a, f32::INFINITY);
        assert_eq!(degenerate.x.number.number(), 0);
        assert_encodable(degenerate.x);
    }
    #[test]
    fn transform_origin_interpolate_between_saturated_extremes_does_not_panic() {
        let a = StyleTransformOrigin {
            x: PixelValue::px(f32::MAX),
            y: PixelValue::px(f32::MIN),
        };
        let b = StyleTransformOrigin {
            x: PixelValue::px(f32::MIN),
            y: PixelValue::px(f32::MAX),
        };
        // Both endpoints are already clamped to isize::MAX / isize::MIN.
        assert_eq!(a.x.number.number(), isize::MAX);
        assert_eq!(a.y.number.number(), isize::MIN);
        for t in [
            -1e30,
            -1.0,
            0.0,
            0.5,
            1.0,
            1e30,
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
        ] {
            let out = a.interpolate(&b, t);
            assert_encodable(out.x);
            assert_encodable(out.y);
        }
    }
    #[test]
    fn transform_origin_interpolate_across_metrics_falls_back_to_px() {
        let a = StyleTransformOrigin {
            x: PixelValue::px(0.0),
            y: PixelValue::px(0.0),
        };
        let b = StyleTransformOrigin {
            x: PixelValue::percent(100.0),
            y: PixelValue::em(2.0),
        };
        for t in [0.0, 0.5, 1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            let out = a.interpolate(&b, t);
            assert_eq!(out.x.metric, SizeMetric::Px, "t = {t}");
            assert_eq!(out.y.metric, SizeMetric::Px, "t = {t}");
            assert_encodable(out.x);
            assert_encodable(out.y);
        }
    }
    #[test]
    fn perspective_origin_interpolate_matches_transform_origin_semantics() {
        let a = StylePerspectiveOrigin {
            x: PixelValue::px(10.0),
            y: PixelValue::percent(0.0),
        };
        let b = StylePerspectiveOrigin {
            x: PixelValue::px(30.0),
            y: PixelValue::percent(100.0),
        };
        assert_eq!(a.interpolate(&b, 0.0), a);
        assert_eq!(a.interpolate(&b, 1.0), b);
        assert_eq!(
            a.interpolate(&b, 0.5),
            StylePerspectiveOrigin {
                x: PixelValue::px(20.0),
                y: PixelValue::percent(50.0),
            }
        );
        // Default is 0px 0px, and interpolating it with itself is stable.
        let d = StylePerspectiveOrigin::default();
        assert_eq!(d.interpolate(&d, 0.5), d);
        // NaN / inf are defined, not panics.
        let nan = a.interpolate(&b, f32::NAN);
        assert_eq!(nan.x.number.number(), 0);
        assert_encodable(nan.x);
        let inf = a.interpolate(&b, f32::INFINITY);
        assert_eq!(inf.x.number.number(), isize::MAX);
        assert_encodable(inf.x);
        // Saturated extremes.
        let lo = StylePerspectiveOrigin {
            x: PixelValue::px(f32::MIN),
            y: PixelValue::px(f32::MIN),
        };
        let hi = StylePerspectiveOrigin {
            x: PixelValue::px(f32::MAX),
            y: PixelValue::px(f32::MAX),
        };
        for t in [0.0, 0.5, 1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            let out = lo.interpolate(&hi, t);
            assert_encodable(out.x);
            assert_encodable(out.y);
        }
    }
    // =====================================================================
    // Error types: to_contained / to_shared round-trips + Display invariants
    // =====================================================================
    fn transform_errors() -> Vec<CssStyleTransformParseError<'static>> {
        vec![
            CssStyleTransformParseError::InvalidTransform("rotate"),
            // Edge: empty payload.
            CssStyleTransformParseError::InvalidTransform(""),
            CssStyleTransformParseError::InvalidTransform("\u{1F600}"),
            CssStyleTransformParseError::InvalidParenthesis(ParenthesisParseError::EmptyInput),
            CssStyleTransformParseError::InvalidParenthesis(ParenthesisParseError::UnclosedBraces),
            CssStyleTransformParseError::InvalidParenthesis(
                ParenthesisParseError::NoOpeningBraceFound,
            ),
            CssStyleTransformParseError::InvalidParenthesis(
                ParenthesisParseError::NoClosingBraceFound,
            ),
            CssStyleTransformParseError::InvalidParenthesis(
                ParenthesisParseError::StopWordNotFound("nope"),
            ),
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: 6,
                got: 5,
                input: "1,2,3,4,5",
            },
            // Edge: extreme counts + empty input.
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: usize::MAX,
                got: usize::MAX,
                input: "",
            },
            CssStyleTransformParseError::WrongNumberOfComponents {
                expected: 0,
                got: 0,
                input: "",
            },
            CssStyleTransformParseError::NumberParseError("x".parse::<f32>().unwrap_err()),
            CssStyleTransformParseError::NumberParseError("".parse::<f32>().unwrap_err()),
            CssStyleTransformParseError::PixelValueParseError(CssPixelValueParseError::EmptyString),
            CssStyleTransformParseError::PixelValueParseError(
                CssPixelValueParseError::InvalidPixelValue("auto"),
            ),
            CssStyleTransformParseError::AngleValueParseError(CssAngleValueParseError::EmptyString),
            CssStyleTransformParseError::AngleValueParseError(
                CssAngleValueParseError::InvalidAngle(""),
            ),
            CssStyleTransformParseError::PercentageValueParseError(
                PercentageParseError::NoPercentSign,
            ),
            CssStyleTransformParseError::PercentageValueParseError(
                PercentageParseError::InvalidUnit(AzString::from("")),
            ),
        ]
    }
    #[test]
    fn transform_parse_error_round_trips_through_owned() {
        for err in transform_errors() {
            let owned = err.to_contained();
            let shared = owned.to_shared();
            assert_eq!(shared, err, "round-trip failed for {err}");
            // Re-owning the shared copy must be stable.
            assert_eq!(shared.to_contained(), owned);
        }
    }
    #[test]
    fn transform_parse_error_round_trips_errors_from_the_real_parsers() {
        // Errors that actually come out of the parsers (rather than hand-built).
        for input in [
            "",
            "garbage",
            "translatex(1px)",
            "matrix(1,2,3)",
            "rotate(10px)",
            "translateX(auto)",
            "scaleX(abc)",
            "translate3d(1px,2px)",
        ] {
            let err = parse_style_transform(input).unwrap_err();
            assert_eq!(err.to_contained().to_shared(), err, "for {input:?}");
            assert!(!alloc::format!("{err}").is_empty());
            // Debug is implemented as Display (impl_debug_as_display!).
            assert_eq!(alloc::format!("{err:?}"), alloc::format!("{err}"));
        }
    }
    #[test]
    fn transform_origin_parse_error_round_trips_through_owned() {
        let errs = [
            CssStyleTransformOriginParseError::WrongNumberOfComponents {
                expected: 2,
                got: 0,
                input: "",
            },
            CssStyleTransformOriginParseError::WrongNumberOfComponents {
                expected: usize::MAX,
                got: usize::MAX,
                input: "\u{1F600}",
            },
            CssStyleTransformOriginParseError::PixelValueParseError(
                CssPixelValueParseError::EmptyString,
            ),
            CssStyleTransformOriginParseError::PixelValueParseError(
                CssPixelValueParseError::InvalidPixelValue(""),
            ),
        ];
        for err in errs {
            let owned = err.to_contained();
            assert_eq!(owned.to_shared(), err, "round-trip failed for {err}");
            assert!(!alloc::format!("{err}").is_empty());
        }
        // ...and one straight out of the parser.
        let err = parse_style_transform_origin("top left").unwrap_err();
        assert_eq!(err.to_contained().to_shared(), err);
    }
    #[test]
    fn perspective_origin_parse_error_round_trips_through_owned() {
        let errs = [
            CssStylePerspectiveOriginParseError::WrongNumberOfComponents {
                expected: 2,
                got: 0,
                input: "",
            },
            CssStylePerspectiveOriginParseError::WrongNumberOfComponents {
                expected: 0,
                got: usize::MAX,
                input: "\u{1F600}\u{0301}",
            },
            CssStylePerspectiveOriginParseError::PixelValueParseError(
                CssPixelValueParseError::EmptyString,
            ),
        ];
        for err in errs {
            let owned = err.to_contained();
            assert_eq!(owned.to_shared(), err, "round-trip failed for {err}");
            assert!(!alloc::format!("{err}").is_empty());
        }
        let err = parse_style_perspective_origin("center center").unwrap_err();
        assert_eq!(err.to_contained().to_shared(), err);
    }
    #[test]
    fn backface_visibility_parse_error_round_trips_through_owned() {
        for payload in ["", "none", "\u{1F600}", "  bogus  "] {
            let err = CssBackfaceVisibilityParseError::InvalidValue(payload);
            let owned = err.to_contained();
            assert_eq!(owned.to_shared(), err, "round-trip failed for {payload:?}");
            assert!(alloc::format!("{err}").contains(payload) || payload.is_empty());
        }
        let err = parse_style_backface_visibility("nope").unwrap_err();
        assert_eq!(err.to_contained().to_shared(), err);
    }
    #[test]
    fn owned_errors_borrow_from_themselves_not_from_the_original_input() {
        // to_contained() must deep-copy the &str payload: the owned error has to
        // outlive the input it was parsed from.
        let owned = {
            let input = String::from("translatex(1px)");
            parse_style_transform(&input).unwrap_err().to_contained()
        };
        assert_eq!(
            owned,
            CssStyleTransformParseErrorOwned::InvalidParenthesis(
                ParenthesisParseErrorOwned::StopWordNotFound(AzString::from("translatex"))
            )
        );
        // And the re-shared borrow points at the owned buffer.
        assert!(matches!(
            owned.to_shared(),
            CssStyleTransformParseError::InvalidParenthesis(
                ParenthesisParseError::StopWordNotFound("translatex")
            )
        ));
    }
    #[test]
    fn wrong_number_of_components_preserves_counts_across_the_owned_conversion() {
        let err = CssStyleTransformParseError::WrongNumberOfComponents {
            expected: usize::MAX,
            got: 0,
            input: "\u{1F600}",
        };
        let CssStyleTransformParseErrorOwned::WrongNumberOfComponents(WrongComponentCountError {
            expected,
            got,
            input,
        }) = err.to_contained()
        else {
            panic!("expected WrongNumberOfComponents");
        };
        assert_eq!(expected, usize::MAX);
        assert_eq!(got, 0);
        assert_eq!(input.as_str(), "\u{1F600}");
    }
    // =====================================================================
    // parse_float_value (re-exported into this module's parse path)
    // =====================================================================
    #[test]
    fn float_value_parse_helper_saturates_and_rejects_garbage() {
        assert_eq!(parse_float_value("1.5").unwrap(), FloatValue::new(1.5));
        assert_eq!(parse_float_value("  -0  ").unwrap(), FloatValue::new(0.0));
        assert_eq!(parse_float_value("inf").unwrap().number(), isize::MAX);
        assert_eq!(parse_float_value("-inf").unwrap().number(), isize::MIN);
        assert_eq!(parse_float_value("NaN").unwrap().number(), 0);
        assert!(parse_float_value("").is_err());
        assert!(parse_float_value("abc").is_err());
        assert!(parse_float_value("\u{1F600}").is_err());
    }
}
#[cfg(all(test, feature = "parser"))]
mod app_region_tests {
    use super::*;
    /// Both spellings must reach the same property, so CSS written for Electron
    /// works unchanged.
    #[test]
1
    fn both_spellings_map_to_the_same_property() {
        use crate::props::property::{get_css_key_map, CssPropertyType};
1
        let map = get_css_key_map();
        // Go through the public lookup rather than the private table: this is
        // the path a stylesheet actually takes.
1
        assert_eq!(
1
            CssPropertyType::from_str("-azul-app-region", &map),
            Some(CssPropertyType::AppRegion)
        );
1
        assert_eq!(
1
            CssPropertyType::from_str("-webkit-app-region", &map),
            Some(CssPropertyType::AppRegion),
            "Electron's spelling must be accepted verbatim"
        );
1
    }
    #[test]
1
    fn drag_and_no_drag_parse_and_round_trip() {
1
        assert_eq!(parse_style_app_region("drag"), Ok(StyleAppRegion::Drag));
1
        assert_eq!(
1
            parse_style_app_region(" no-drag "),
            Ok(StyleAppRegion::NoDrag)
        );
        // `none` is what someone reaches for after writing `-webkit-app-region:
        // none` out of habit; accept it rather than silently dropping the rule.
1
        assert_eq!(parse_style_app_region("none"), Ok(StyleAppRegion::NoDrag));
1
        assert!(parse_style_app_region("sometimes").is_err());
1
        assert_eq!(StyleAppRegion::Drag.print_as_css_value(), "drag");
1
        assert_eq!(StyleAppRegion::NoDrag.print_as_css_value(), "no-drag");
1
    }
    /// The DEFAULT must be NoDrag. A default of Drag would make every element
    /// in the tree move the window.
    #[test]
1
    fn the_default_is_not_draggable() {
1
        assert_eq!(StyleAppRegion::default(), StyleAppRegion::NoDrag);
1
    }
}