Skip to main content

nsh_core/
transform.rs

1//! `transform` lists: React Native / CSS semantics, composed into 4×4
2//! matrices and decomposed again for platforms that only take separate
3//! translation / scale / rotation properties (Android views).
4//!
5//! Matrices use Core Animation's layout (`CATransform3D`): row vectors,
6//! `m41..m43` hold the translation. A list `[A, B]` means "apply B, then
7//! A" like CSS, which in row-vector form is `B · A`.
8
9use crate::geometry::{Points, Radians, Size};
10
11/// Most entries a `transform` list can have: room for every step
12/// Tailwind's utilities compose (`translate`, `rotate`, `scale`, then
13/// `rotateX() rotateY() rotateZ() skewX() skewY()`) and the perspective of
14/// `perspective-*`.
15pub const MAX_TRANSFORMS: usize = 16;
16
17/// One kind of transform entry.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum TransformKind {
20    /// `translateX`, points.
21    TranslateX,
22    /// `translateY`, points.
23    TranslateY,
24    /// `scale`.
25    Scale,
26    /// `scaleX`.
27    ScaleX,
28    /// `scaleY`.
29    ScaleY,
30    /// `rotate` / `rotateZ`, degrees clockwise.
31    Rotate,
32    /// `rotateX`, degrees.
33    RotateX,
34    /// `rotateY`, degrees.
35    RotateY,
36    /// `skewX`, degrees.
37    SkewX,
38    /// `skewY`, degrees.
39    SkewY,
40    /// `perspective`, the distance of the viewer in points.
41    Perspective,
42    /// A translation by a fraction of the view's width (`translate-x-1/2`);
43    /// the core turns it into `TranslateX` with the view's size before it
44    /// reaches a platform.
45    TranslateXFraction,
46    /// A translation by a fraction of the view's height.
47    TranslateYFraction,
48}
49
50impl TransformKind {
51    /// Parses a transform key.
52    pub fn parse(key: &str) -> Option<Self> {
53        use TransformKind::*;
54        Some(match key {
55            "translateX" => TranslateX,
56            "translateY" => TranslateY,
57            "scale" => Scale,
58            "scaleX" => ScaleX,
59            "scaleY" => ScaleY,
60            "rotate" | "rotateZ" => Rotate,
61            "rotateX" => RotateX,
62            "rotateY" => RotateY,
63            "skewX" => SkewX,
64            "skewY" => SkewY,
65            "perspective" => Perspective,
66            _ => return None,
67        })
68    }
69
70    /// True for kinds whose value is an angle (`"45deg"` strings).
71    pub fn is_angle(self) -> bool {
72        use TransformKind::*;
73        matches!(self, Rotate | RotateX | RotateY | SkewX | SkewY)
74    }
75
76    /// The value that changes nothing.
77    pub fn identity(self) -> f32 {
78        use TransformKind::*;
79        match self {
80            Scale | ScaleX | ScaleY => 1.0,
81            _ => 0.0,
82        }
83    }
84}
85
86/// One entry of a `transform` list.
87#[derive(Debug, Clone, Copy, PartialEq)]
88pub struct TransformOp {
89    /// What the entry does.
90    pub kind: TransformKind,
91    /// Its amount (points, degrees or a factor).
92    pub value: f32,
93}
94
95/// A `transform` list. Fixed capacity, so styles stay `Copy`.
96#[derive(Clone, Copy, PartialEq)]
97pub struct Transform {
98    ops: [TransformOp; MAX_TRANSFORMS],
99    len: u8,
100}
101
102impl std::fmt::Debug for Transform {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        f.debug_list().entries(self.ops()).finish()
105    }
106}
107
108impl Transform {
109    /// The empty list.
110    pub const IDENTITY: Transform = Transform {
111        ops: [TransformOp {
112            kind: TransformKind::TranslateX,
113            value: 0.0,
114        }; MAX_TRANSFORMS],
115        len: 0,
116    };
117
118    /// The entries, in order.
119    #[inline]
120    pub fn ops(&self) -> &[TransformOp] {
121        &self.ops[..self.len as usize]
122    }
123
124    /// Appends an entry; returns its index, or `None` when the list is full.
125    pub fn push(&mut self, kind: TransformKind, value: f32) -> Option<u8> {
126        let i = self.len as usize;
127        if i == MAX_TRANSFORMS {
128            return None;
129        }
130        self.ops[i] = TransformOp { kind, value };
131        self.len += 1;
132        Some(i as u8)
133    }
134
135    /// Whether some entry is a fraction of the view's size.
136    pub fn has_fractions(&self) -> bool {
137        self.ops().iter().any(|op| {
138            matches!(
139                op.kind,
140                TransformKind::TranslateXFraction | TransformKind::TranslateYFraction
141            )
142        })
143    }
144
145    /// The list with size fractions turned into points for a view of
146    /// `size`.
147    pub fn resolve_fractions(&self, size: Size<Points>) -> Transform {
148        let mut t = *self;
149        for op in &mut t.ops[..t.len as usize] {
150            match op.kind {
151                TransformKind::TranslateXFraction => {
152                    *op = TransformOp {
153                        kind: TransformKind::TranslateX,
154                        value: op.value * size.width.0,
155                    }
156                }
157                TransformKind::TranslateYFraction => {
158                    *op = TransformOp {
159                        kind: TransformKind::TranslateY,
160                        value: op.value * size.height.0,
161                    }
162                }
163                _ => {}
164            }
165        }
166        t
167    }
168
169    /// True if the list is empty or every entry is an identity.
170    pub fn is_identity(&self) -> bool {
171        self.ops().iter().all(|op| op.value == op.kind.identity())
172    }
173
174    /// Composes the list. `value(i)` may override entry `i`'s amount (an
175    /// animated value).
176    pub fn matrix(&self, value: impl Fn(usize) -> Option<f32>) -> Matrix {
177        let mut m = Matrix::IDENTITY;
178        for (i, op) in self.ops().iter().enumerate() {
179            let v = value(i).unwrap_or(op.value) as f64;
180            // [A, B] applies B first: in row-vector form, B · A.
181            m = Matrix::of(op.kind, v).mul(&m);
182        }
183        m
184    }
185}
186
187impl Default for Transform {
188    fn default() -> Self {
189        Self::IDENTITY
190    }
191}
192
193/// A 4×4 matrix in `CATransform3D` layout (`m[0..4]` is the first row).
194#[derive(Debug, Clone, Copy, PartialEq)]
195pub struct Matrix(pub [f64; 16]);
196
197impl Matrix {
198    /// The identity.
199    pub const IDENTITY: Matrix = Matrix([
200        1.0, 0.0, 0.0, 0.0, //
201        0.0, 1.0, 0.0, 0.0, //
202        0.0, 0.0, 1.0, 0.0, //
203        0.0, 0.0, 0.0, 1.0,
204    ]);
205
206    /// The matrix of one transform entry.
207    pub fn of(kind: TransformKind, v: f64) -> Matrix {
208        let mut m = Matrix::IDENTITY;
209        let a = &mut m.0;
210        let (sin, cos) = v.to_radians().sin_cos();
211        match kind {
212            TransformKind::TranslateX => a[12] = v,
213            TransformKind::TranslateY => a[13] = v,
214            TransformKind::Scale => (a[0], a[5]) = (v, v),
215            TransformKind::ScaleX => a[0] = v,
216            TransformKind::ScaleY => a[5] = v,
217            TransformKind::Rotate => {
218                (a[0], a[1], a[4], a[5]) = (cos, sin, -sin, cos);
219            }
220            TransformKind::RotateX => {
221                (a[5], a[6], a[9], a[10]) = (cos, sin, -sin, cos);
222            }
223            TransformKind::RotateY => {
224                (a[0], a[2], a[8], a[10]) = (cos, -sin, sin, cos);
225            }
226            TransformKind::SkewX => a[4] = v.to_radians().tan(),
227            TransformKind::SkewY => a[1] = v.to_radians().tan(),
228            TransformKind::Perspective => {
229                if v != 0.0 {
230                    a[11] = -1.0 / v;
231                }
232            }
233            // Resolved by the core (`Transform::resolve_fractions`).
234            TransformKind::TranslateXFraction | TransformKind::TranslateYFraction => {}
235        }
236        m
237    }
238
239    /// `self · other`: apply `self`, then `other` (row vectors).
240    pub fn mul(&self, other: &Matrix) -> Matrix {
241        let (a, b) = (&self.0, &other.0);
242        let mut out = [0.0; 16];
243        for r in 0..4 {
244            for c in 0..4 {
245                out[r * 4 + c] = (0..4).map(|k| a[r * 4 + k] * b[k * 4 + c]).sum();
246            }
247        }
248        Matrix(out)
249    }
250
251    /// True if the matrix is a 2D affine transform (no depth, no
252    /// perspective).
253    pub fn is_2d(&self) -> bool {
254        let m = &self.0;
255        let zero = |v: f64| v.abs() < 1e-9;
256        zero(m[2])
257            && zero(m[3])
258            && zero(m[6])
259            && zero(m[7])
260            && zero(m[8])
261            && zero(m[9])
262            && (m[10] - 1.0).abs() < 1e-9
263            && zero(m[11])
264            && zero(m[14])
265            && (m[15] - 1.0).abs() < 1e-9
266    }
267
268    /// Splits the matrix into the separate properties of an Android view.
269    /// Skew has no view property and is dropped. `None` for degenerate
270    /// matrices (a zero scale).
271    pub fn decompose(&self) -> Option<Decomposed> {
272        if self.is_2d() {
273            return Some(self.decompose_2d());
274        }
275        self.decompose_3d()
276    }
277
278    fn decompose_2d(&self) -> Decomposed {
279        let m = &self.0;
280        let (a, b, c, d) = (m[0], m[1], m[4], m[5]);
281        let scale_x = (a * a + b * b).sqrt();
282        let det = a * d - b * c;
283        // A mirrored matrix keeps its rotation; the flip goes to scale y.
284        let scale_y = if scale_x > 0.0 {
285            det / scale_x
286        } else {
287            (c * c + d * d).sqrt()
288        };
289        Decomposed {
290            translate: [points(m[12]), points(m[13]), Points::ZERO],
291            scale: [scale_x, scale_y, 1.0],
292            rotate: [Radians::ZERO, Radians::ZERO, angle(b.atan2(a))],
293            perspective: None,
294        }
295    }
296
297    /// The CSS Transforms "decomposing a 3D matrix" algorithm, with the
298    /// rotation as Euler angles (X then Y then Z).
299    fn decompose_3d(&self) -> Option<Decomposed> {
300        let mut m = [[0.0f64; 4]; 4];
301        for (r, row) in m.iter_mut().enumerate() {
302            row.copy_from_slice(&self.0[r * 4..r * 4 + 4]);
303        }
304        if m[3][3] == 0.0 {
305            return None;
306        }
307        let w = m[3][3];
308        for row in &mut m {
309            for v in row {
310                *v /= w;
311            }
312        }
313        let term: f64 = if m[0][3] != 0.0 || m[1][3] != 0.0 || m[2][3] != 0.0 {
314            // Solve rhs = p · P for the perspective row p, where P is the
315            // matrix without its perspective column; only the z term matters
316            // for a camera distance.
317            let mut p = m;
318            for row in p.iter_mut().take(3) {
319                row[3] = 0.0;
320            }
321            p[3][3] = 1.0;
322            let inverse = invert(&p)?;
323            let rhs = [m[0][3], m[1][3], m[2][3], m[3][3]];
324            (0..4).map(|k| inverse[2][k] * rhs[k]).sum()
325        } else {
326            0.0
327        };
328        // The term is `-1 / distance`.
329        let perspective = (term != 0.0).then(|| points(-1.0 / term));
330        let translate = [points(m[3][0]), points(m[3][1]), points(m[3][2])];
331        let mut rows = [
332            [m[0][0], m[0][1], m[0][2]],
333            [m[1][0], m[1][1], m[1][2]],
334            [m[2][0], m[2][1], m[2][2]],
335        ];
336        let len = |v: &[f64; 3]| (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
337        let dot = |a: &[f64; 3], b: &[f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
338        let mut scale = [0.0; 3];
339        scale[0] = len(&rows[0]);
340        if scale[0] == 0.0 {
341            return None;
342        }
343        rows[0] = rows[0].map(|v| v / scale[0]);
344        let xy = dot(&rows[0], &rows[1]);
345        rows[1] = [0, 1, 2].map(|i| rows[1][i] - rows[0][i] * xy);
346        scale[1] = len(&rows[1]);
347        if scale[1] == 0.0 {
348            return None;
349        }
350        rows[1] = rows[1].map(|v| v / scale[1]);
351        let xz = dot(&rows[0], &rows[2]);
352        rows[2] = [0, 1, 2].map(|i| rows[2][i] - rows[0][i] * xz);
353        let yz = dot(&rows[1], &rows[2]);
354        rows[2] = [0, 1, 2].map(|i| rows[2][i] - rows[1][i] * yz);
355        scale[2] = len(&rows[2]);
356        if scale[2] == 0.0 {
357            return None;
358        }
359        rows[2] = rows[2].map(|v| v / scale[2]);
360        let cross = [
361            rows[1][1] * rows[2][2] - rows[1][2] * rows[2][1],
362            rows[1][2] * rows[2][0] - rows[1][0] * rows[2][2],
363            rows[1][0] * rows[2][1] - rows[1][1] * rows[2][0],
364        ];
365        if dot(&rows[0], &cross) < 0.0 {
366            for i in 0..3 {
367                scale[i] = -scale[i];
368                rows[i] = rows[i].map(|v| -v);
369            }
370        }
371        // Euler angles of the rotation rows (R = Rx · Ry · Rz in row-vector
372        // order: X applied first).
373        let ry = (-rows[0][2]).clamp(-1.0, 1.0).asin();
374        let (rx, rz) = if ry.cos().abs() > 1e-6 {
375            (rows[1][2].atan2(rows[2][2]), rows[0][1].atan2(rows[0][0]))
376        } else {
377            (0.0, (-rows[1][0]).atan2(rows[1][1]))
378        };
379        Some(Decomposed {
380            translate,
381            scale,
382            rotate: [angle(rx), angle(ry), angle(rz)],
383            perspective,
384        })
385    }
386}
387
388/// A length the matrices computed in `f64`.
389fn points(v: f64) -> Points {
390    Points(v as f32)
391}
392
393/// An angle the matrices computed in `f64`.
394fn angle(v: f64) -> Radians {
395    Radians(v as f32)
396}
397
398/// The inverse of a 4×4 matrix (Gauss-Jordan); `None` if singular.
399fn invert(m: &[[f64; 4]; 4]) -> Option<[[f64; 4]; 4]> {
400    let mut a = *m;
401    let mut inv = [[0.0; 4]; 4];
402    for (i, row) in inv.iter_mut().enumerate() {
403        row[i] = 1.0;
404    }
405    for col in 0..4 {
406        let pivot = (col..4).max_by(|&x, &y| a[x][col].abs().total_cmp(&a[y][col].abs()))?;
407        if a[pivot][col].abs() < 1e-12 {
408            return None;
409        }
410        a.swap(col, pivot);
411        inv.swap(col, pivot);
412        let d = a[col][col];
413        for k in 0..4 {
414            a[col][k] /= d;
415            inv[col][k] /= d;
416        }
417        for r in 0..4 {
418            if r != col {
419                let f = a[r][col];
420                for k in 0..4 {
421                    a[r][k] -= f * a[col][k];
422                    inv[r][k] -= f * inv[col][k];
423                }
424            }
425        }
426    }
427    Some(inv)
428}
429
430/// A matrix split into view properties.
431#[derive(Debug, Clone, Copy, PartialEq)]
432pub struct Decomposed {
433    /// Translation along x, y and z.
434    pub translate: [Points; 3],
435    /// Scale factors.
436    pub scale: [f64; 3],
437    /// Rotation around x, y and z (z clockwise on screen).
438    pub rotate: [Radians; 3],
439    /// The viewer's distance (`perspective`), `None` without perspective.
440    pub perspective: Option<Points>,
441}
442
443/// CSS's `transform` (`"translateX(10px) rotate(45deg) scale(1.5)"`,
444/// `"none"`) as entries, in order: `translate()` / `translateX()` /
445/// `translateY()` (lengths, or percentages of the view's size), `scale()`
446/// / `scaleX()` / `scaleY()`, `rotate()` / `rotateZ()` / `rotateX()` /
447/// `rotateY()`, `skew()` / `skewX()` / `skewY()` (angles) and
448/// `perspective()`. `None` for anything else.
449pub(crate) fn parse_css(s: &str) -> Option<Vec<TransformOp>> {
450    let mut out = Vec::new();
451    let mut rest = s.trim();
452    if rest == "none" {
453        return Some(out);
454    }
455    while !rest.is_empty() {
456        let open = rest.find('(')?;
457        let close = open + rest[open..].find(')')?;
458        let args: Vec<&str> = rest[open + 1..close].split(',').map(str::trim).collect();
459        function(rest[..open].trim(), &args, &mut out)?;
460        rest = rest[close + 1..].trim_start();
461    }
462    Some(out)
463}
464
465/// One function of [`parse_css`], pushed onto `out`.
466fn function(name: &str, args: &[&str], out: &mut Vec<TransformOp>) -> Option<()> {
467    use TransformKind::*;
468    let op = |kind, value| TransformOp { kind, value };
469    match name {
470        "translate" if matches!(args.len(), 1 | 2) => {
471            out.push(translation(false, args[0])?);
472            if let Some(y) = args.get(1) {
473                out.push(translation(true, y)?);
474            }
475        }
476        "translateX" | "translateY" if args.len() == 1 => {
477            out.push(translation(name == "translateY", args[0])?)
478        }
479        "scale" if args.len() == 1 => out.push(op(Scale, crate::css::amount(args[0])?)),
480        "scale" if args.len() == 2 => {
481            out.push(op(ScaleX, crate::css::amount(args[0])?));
482            out.push(op(ScaleY, crate::css::amount(args[1])?));
483        }
484        "scaleX" | "scaleY" | "rotate" | "rotateZ" | "rotateX" | "rotateY" | "skewX" | "skewY"
485        | "perspective"
486            if args.len() == 1 =>
487        {
488            let kind = match name {
489                "rotateZ" => Rotate,
490                other => TransformKind::parse(other)?,
491            };
492            let value = match kind {
493                Perspective => crate::css::length(args[0])?,
494                k if k.is_angle() => crate::css::angle(args[0])?,
495                _ => crate::css::amount(args[0])?,
496            };
497            out.push(op(kind, value));
498        }
499        "skew" if matches!(args.len(), 1 | 2) => {
500            out.push(op(SkewX, crate::css::angle(args[0])?));
501            if let Some(y) = args.get(1) {
502                out.push(op(SkewY, crate::css::angle(y)?));
503            }
504        }
505        _ => return None,
506    }
507    Some(())
508}
509
510/// A translation along x (or y when `vertical`) as CSS writes one: a
511/// length (`"10px"`, `"2rem"`, `"0"`), or a percentage of the view's size.
512pub fn translation(vertical: bool, s: &str) -> Option<TransformOp> {
513    use TransformKind::*;
514    let (kind, value) = match s.trim().strip_suffix('%') {
515        Some(p) => (
516            if vertical {
517                TranslateYFraction
518            } else {
519                TranslateXFraction
520            },
521            crate::css::number(p)? / 100.0,
522        ),
523        None => (
524            if vertical { TranslateY } else { TranslateX },
525            crate::css::length(s)?,
526        ),
527    };
528    Some(TransformOp { kind, value })
529}
530
531/// CSS's `translate` property (`"10px"`, `"10px 50%"`, `"none"`): x, then
532/// y when given.
533pub(crate) fn parse_translate(s: &str) -> Option<Vec<TransformOp>> {
534    let s = s.trim();
535    if s == "none" {
536        return Some(Vec::new());
537    }
538    let parts: Vec<&str> = s.split_whitespace().collect();
539    match parts[..] {
540        [x] => Some(vec![translation(false, x)?]),
541        [x, y] => Some(vec![translation(false, x)?, translation(true, y)?]),
542        _ => None,
543    }
544}
545
546/// CSS's `rotate` property (`"45deg"`, `"x 90deg"`, `"none"`): a turn
547/// about the z axis, or the x, y or z axis it names.
548pub(crate) fn parse_rotate(s: &str) -> Option<Vec<TransformOp>> {
549    let s = s.trim();
550    if s == "none" {
551        return Some(Vec::new());
552    }
553    let parts: Vec<&str> = s.split_whitespace().collect();
554    let (kind, angle) = match parts[..] {
555        [a] => (TransformKind::Rotate, a),
556        ["x", a] => (TransformKind::RotateX, a),
557        ["y", a] => (TransformKind::RotateY, a),
558        ["z", a] => (TransformKind::Rotate, a),
559        _ => return None,
560    };
561    Some(vec![TransformOp {
562        kind,
563        value: crate::css::angle(angle)?,
564    }])
565}
566
567/// CSS's `scale` property (`"1.5"`, `"150%"`, `"1 2"`, `"none"`): one
568/// factor for both axes, or x and y.
569pub(crate) fn parse_scale(s: &str) -> Option<Vec<TransformOp>> {
570    let s = s.trim();
571    if s == "none" {
572        return Some(Vec::new());
573    }
574    let parts: Vec<&str> = s.split_whitespace().collect();
575    let op = |kind, s: &str| {
576        Some(TransformOp {
577            kind,
578            value: crate::css::amount(s)?,
579        })
580    };
581    match parts[..] {
582        [k] => Some(vec![op(TransformKind::Scale, k)?]),
583        [x, y] => Some(vec![
584            op(TransformKind::ScaleX, x)?,
585            op(TransformKind::ScaleY, y)?,
586        ]),
587        _ => None,
588    }
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    fn close(a: f64, b: f64) -> bool {
596        (a - b).abs() < 1e-6
597    }
598
599    /// Equal up to `f32`'s precision.
600    fn near(a: f32, b: f32) -> bool {
601        (a - b).abs() < 1e-3
602    }
603
604    #[test]
605    fn css_transforms_parse_as_a_browser_reads_them() {
606        use TransformKind::*;
607        let ops = |s: &str| {
608            parse_css(s).map(|ops| ops.iter().map(|o| (o.kind, o.value)).collect::<Vec<_>>())
609        };
610        assert_eq!(
611            ops("translateX(10px) rotate(45deg) scale(1.5)"),
612            Some(vec![(TranslateX, 10.0), (Rotate, 45.0), (Scale, 1.5)])
613        );
614        assert_eq!(
615            ops("translate(50%, 2rem) skew(10deg) perspective(800px) rotateY(0.25turn)"),
616            Some(vec![
617                (TranslateXFraction, 0.5),
618                (TranslateY, 32.0),
619                (SkewX, 10.0),
620                (Perspective, 800.0),
621                (RotateY, 90.0)
622            ])
623        );
624        assert_eq!(ops("scale(1, 2)"), Some(vec![(ScaleX, 1.0), (ScaleY, 2.0)]));
625        assert_eq!(ops("none"), Some(vec![]));
626        // What NSH does not do is rejected, never read another way.
627        assert_eq!(ops("matrix(1, 0, 0, 1, 0, 0)"), None);
628        assert_eq!(ops("rotate(45)"), None);
629        assert_eq!(ops("translateX(10px"), None);
630        let one = |r: Option<Vec<TransformOp>>| {
631            r.map(|ops| ops.iter().map(|o| (o.kind, o.value)).collect::<Vec<_>>())
632        };
633        assert_eq!(
634            one(parse_translate("10px 50%")),
635            Some(vec![(TranslateX, 10.0), (TranslateYFraction, 0.5)])
636        );
637        assert_eq!(one(parse_rotate("x 90deg")), Some(vec![(RotateX, 90.0)]));
638        assert_eq!(one(parse_rotate("45deg")), Some(vec![(Rotate, 45.0)]));
639        assert_eq!(one(parse_scale("150%")), Some(vec![(Scale, 1.5)]));
640        assert_eq!(
641            one(parse_scale("1 2")),
642            Some(vec![(ScaleX, 1.0), (ScaleY, 2.0)])
643        );
644    }
645
646    fn list(ops: &[(TransformKind, f32)]) -> Transform {
647        let mut t = Transform::IDENTITY;
648        for &(k, v) in ops {
649            t.push(k, v).unwrap();
650        }
651        t
652    }
653
654    /// Applies a matrix to a point (row vector).
655    fn apply(m: &Matrix, x: f64, y: f64) -> (f64, f64) {
656        let a = &m.0;
657        let w = x * a[3] + y * a[7] + a[15];
658        (
659            (x * a[0] + y * a[4] + a[12]) / w,
660            (x * a[1] + y * a[5] + a[13]) / w,
661        )
662    }
663
664    #[test]
665    fn lists_apply_right_to_left_like_css() {
666        // translateX(50) rotate(90deg): rotate first, then move right.
667        let m = list(&[
668            (TransformKind::TranslateX, 50.0),
669            (TransformKind::Rotate, 90.0),
670        ])
671        .matrix(|_| None);
672        let (x, y) = apply(&m, 10.0, 0.0);
673        // (10, 0) rotated 90° clockwise (y down) is (0, 10), then moved by 50.
674        assert!(close(x, 50.0) && close(y, 10.0), "{x} {y}");
675        // The other order moves first, then rotates around the origin.
676        let m = list(&[
677            (TransformKind::Rotate, 90.0),
678            (TransformKind::TranslateX, 50.0),
679        ])
680        .matrix(|_| None);
681        let (x, y) = apply(&m, 10.0, 0.0);
682        assert!(close(x, 0.0) && close(y, 60.0), "{x} {y}");
683    }
684
685    #[test]
686    fn overrides_replace_entries() {
687        let t = list(&[(TransformKind::TranslateY, 5.0)]);
688        let m = t.matrix(|i| (i == 0).then_some(20.0));
689        assert!(close(m.0[13], 20.0));
690    }
691
692    #[test]
693    fn decomposes_2d_and_3d() {
694        let t = list(&[
695            (TransformKind::TranslateX, 12.0),
696            (TransformKind::Rotate, 135.0),
697            (TransformKind::Scale, 2.0),
698        ]);
699        let d = t.matrix(|_| None).decompose().unwrap();
700        assert!(near(d.translate[0].0, 12.0));
701        assert!(close(d.scale[0], 2.0) && close(d.scale[1], 2.0));
702        assert!(near(d.rotate[2].to_degrees(), 135.0), "{:?}", d.rotate);
703
704        let t = list(&[
705            (TransformKind::Perspective, 800.0),
706            (TransformKind::RotateY, 30.0),
707        ]);
708        let d = t.matrix(|_| None).decompose().unwrap();
709        assert!(near(d.rotate[1].to_degrees(), 30.0), "{:?}", d.rotate);
710        let distance = d.perspective.unwrap();
711        assert!(near(distance.0, 800.0), "{distance:?}");
712
713        let t = list(&[(TransformKind::RotateX, -40.0)]);
714        let d = t.matrix(|_| None).decompose().unwrap();
715        assert!(near(d.rotate[0].to_degrees(), -40.0), "{:?}", d.rotate);
716        assert!(
717            list(&[(TransformKind::Scale, 0.0)])
718                .matrix(|_| None)
719                .decompose()
720                .is_some()
721        );
722    }
723
724    #[test]
725    fn identity_detection() {
726        assert!(Transform::IDENTITY.is_identity());
727        assert!(list(&[(TransformKind::Scale, 1.0)]).is_identity());
728        assert!(!list(&[(TransformKind::SkewX, 10.0)]).is_identity());
729    }
730}