Skip to main content

rust_css_parser/ast/transform/
compute.rs

1//! Port of `src/ast/transform/compute.ts`: computation of the matrix of a transform list.
2
3use super::matrix::{serialize, set_matrix_values};
4use super::minify::minify;
5use super::perspective::perspective;
6use super::rotate::{rotate, rotate3d};
7use super::scale::{scale, scale3d, scale_x, scale_y, scale_z};
8use super::skew::{skew, skew_x, skew_y};
9use super::translate::{translate, translate3d, translate_x, translate_y, translate_z};
10use super::utils::{multiply_in_place, to_zero, IDENTITY_MATRIX};
11use super::Matrix;
12use crate::ast::arena::{AstArena, TokenValue};
13use crate::ast::strings::StringDerived;
14use crate::ast::types::EnumToken;
15use crate::syntax::color::color::{get_angle, get_number};
16use crate::syntax::syntax::length2_px;
17
18/// kind of a transform function name, and family of the name (`TransformKind`)
19#[allow(non_snake_case, non_upper_case_globals)]
20pub mod TransformKind {
21    pub const None: u32 = 0;
22    pub const Translate: u32 = 1;
23    pub const TranslateX: u32 = 2;
24    pub const TranslateY: u32 = 3;
25    pub const TranslateZ: u32 = 4;
26    pub const Translate3d: u32 = 5;
27    pub const Rotate: u32 = 6;
28    pub const RotateX: u32 = 7;
29    pub const RotateY: u32 = 8;
30    pub const RotateZ: u32 = 9;
31    pub const Rotate3d: u32 = 10;
32    pub const Scale: u32 = 11;
33    pub const ScaleX: u32 = 12;
34    pub const ScaleY: u32 = 13;
35    pub const ScaleZ: u32 = 14;
36    pub const Scale3d: u32 = 15;
37    pub const Skew: u32 = 16;
38    pub const SkewX: u32 = 17;
39    pub const SkewY: u32 = 18;
40    pub const Perspective: u32 = 19;
41    pub const Matrix: u32 = 20;
42    pub const Matrix3d: u32 = 21;
43    /// the name of the `transform` property or of a prefixed version (`-webkit-transform`)
44    pub const Property: u32 = 22;
45    pub const KindMask: u32 = 0xff;
46    pub const TranslateFamily: u32 = 1 << 8;
47    pub const RotateFamily: u32 = 2 << 8;
48    pub const ScaleFamily: u32 = 3 << 8;
49    pub const FamilyMask: u32 = 3 << 8;
50}
51
52fn kind_of_name(name: &str) -> u32 {
53    use TransformKind as K;
54    match name {
55        "translate" => K::Translate,
56        "translateX" => K::TranslateX,
57        "translateY" => K::TranslateY,
58        "translateZ" => K::TranslateZ,
59        "translate3d" => K::Translate3d,
60        "rotate" => K::Rotate,
61        "rotateX" => K::RotateX,
62        "rotateY" => K::RotateY,
63        "rotateZ" => K::RotateZ,
64        "rotate3d" => K::Rotate3d,
65        "scale" => K::Scale,
66        "scaleX" => K::ScaleX,
67        "scaleY" => K::ScaleY,
68        "scaleZ" => K::ScaleZ,
69        "scale3d" => K::Scale3d,
70        "skew" => K::Skew,
71        "skewX" => K::SkewX,
72        "skewY" => K::SkewY,
73        "perspective" => K::Perspective,
74        "matrix" => K::Matrix,
75        "matrix3d" => K::Matrix3d,
76        _ => K::None,
77    }
78}
79
80/// `/^(-[a-z]+-)?transform$/`
81fn is_transform_property(name: &str) -> bool {
82    let Some(prefix) = name.strip_suffix("transform") else {
83        return false;
84    };
85    prefix.is_empty() || (prefix.len() > 2 && prefix.starts_with('-') && prefix.ends_with('-') && prefix[1..prefix.len() - 1].bytes().all(|b| b.is_ascii_lowercase()))
86}
87
88fn compute_transform_kind(name: &str) -> u32 {
89    let mut kind = kind_of_name(name);
90    if kind == TransformKind::None && is_transform_property(name) {
91        return TransformKind::Property;
92    }
93    if name.starts_with("translate") {
94        kind |= TransformKind::TranslateFamily;
95    } else if name.starts_with("rotate") {
96        kind |= TransformKind::RotateFamily;
97    } else if name.starts_with("scale") {
98        kind |= TransformKind::ScaleFamily;
99    }
100    kind
101}
102
103/// the kind and the family of a string, computed once per interned string
104pub fn transform_kind(arena: &AstArena, id: u32) -> u32 {
105    arena.string_derived(id, StringDerived::TransformKind, |id| arena.with_string(id, compute_transform_kind))
106}
107
108/// multiply a matrix in place by the matrix of a transform function. false if the matrix cannot be computed (it is
109/// then partially updated)
110pub fn compute_transform(arena: &AstArena, token: u32, matrix: &mut Matrix) -> bool {
111    use TransformKind as K;
112    if arena.data_types.get(token) != EnumToken::TransformFunctionTokenType {
113        return false;
114    }
115    let kind = transform_kind(arena, arena.string_value.get(token)) & K::KindMask;
116    let mut args = [0.0f64; 16];
117    let mut count = 0usize;
118    let t = |x: u32| arena.data_types.get(x);
119    let children = arena.token_iter(token).collect::<Vec<_>>();
120    match kind {
121        K::Translate | K::TranslateX | K::TranslateY | K::TranslateZ | K::Translate3d => {
122            for &child in &children {
123                if matches!(t(child), EnumToken::CommentTokenType | EnumToken::CommaTokenType | EnumToken::WhitespaceTokenType) {
124                    continue;
125                }
126                let Some(val) = length2_px(arena, child) else {
127                    return false;
128                };
129                if count < 16 {
130                    args[count] = val;
131                }
132                count += 1;
133            }
134            let max = if kind == K::Translate3d { 3 } else if kind == K::Translate { 2 } else { 1 };
135            if count == 0 || count > max {
136                return false;
137            }
138            match kind {
139                K::TranslateX => translate_x(args[0], matrix),
140                K::TranslateY => translate_y(args[0], matrix),
141                K::TranslateZ => translate_z(args[0], matrix),
142                K::Translate => translate(args[0], if count > 1 { Some(args[1]) } else { None }, matrix),
143                _ => translate3d(args[0], if count > 1 { Some(args[1]) } else { None }, if count > 2 { Some(args[2]) } else { None }, matrix),
144            }
145            true
146        }
147        K::Rotate | K::RotateX | K::RotateY | K::RotateZ | K::Rotate3d => {
148            let (mut x, mut y, mut z) = (0.0, 0.0, 0.0);
149            let (mut first, mut second, mut third, mut last) = (0u32, 0u32, 0u32, 0u32);
150            // the whitespace tokens are arguments
151            for &child in &children {
152                if matches!(t(child), EnumToken::CommentTokenType | EnumToken::CommaTokenType) {
153                    continue;
154                }
155                match count {
156                    0 => first = child,
157                    1 => second = child,
158                    2 => third = child,
159                    _ => {}
160                }
161                last = child;
162                count += 1;
163            }
164            if count != if kind == K::Rotate3d { 4 } else { 1 } {
165                return false;
166            }
167            match kind {
168                K::RotateX => x = 1.0,
169                K::RotateY => y = 1.0,
170                K::Rotate | K::RotateZ => z = 1.0,
171                _ => {
172                    x = get_number(arena, first);
173                    y = get_number(arena, second);
174                    z = get_number(arena, third);
175                }
176            }
177            let angle = get_angle(arena, last);
178            if x.is_nan() || y.is_nan() || z.is_nan() || angle.is_nan() {
179                return false;
180            }
181            if kind == K::Rotate || kind == K::RotateZ {
182                rotate(angle * 2.0 * std::f64::consts::PI, matrix);
183            } else {
184                rotate3d(angle * 2.0 * std::f64::consts::PI, x, y, z, matrix);
185            }
186            true
187        }
188        K::Scale | K::ScaleX | K::ScaleY | K::ScaleZ | K::Scale3d => {
189            for &child in &children {
190                let typ = t(child);
191                if typ == EnumToken::CommentTokenType || typ == EnumToken::CommaTokenType {
192                    continue;
193                }
194                // whitespace tokens are not allowed
195                if typ != EnumToken::NumberTokenType && typ != EnumToken::PercentageTokenType {
196                    return false;
197                }
198                if count < 16 {
199                    args[count] = get_number(arena, child);
200                }
201                count += 1;
202            }
203            match kind {
204                K::Scale3d => {
205                    if count != 3 {
206                        return false;
207                    }
208                    scale3d(args[0], args[1], args[2], matrix);
209                }
210                K::Scale => {
211                    if count != 1 && count != 2 {
212                        return false;
213                    }
214                    scale(args[0], if count > 1 { args[1] } else { args[0] }, matrix);
215                }
216                _ if count != 1 => return false,
217                K::ScaleX => scale_x(args[0], matrix),
218                K::ScaleY => scale_y(args[0], matrix),
219                _ => scale_z(args[0], matrix),
220            }
221            true
222        }
223        K::Skew | K::SkewX | K::SkewY => {
224            for &child in &children {
225                if matches!(t(child), EnumToken::CommentTokenType | EnumToken::CommaTokenType | EnumToken::WhitespaceTokenType) {
226                    continue;
227                }
228                if count < 16 {
229                    args[count] = get_angle(arena, child) * 2.0 * std::f64::consts::PI;
230                }
231                count += 1;
232            }
233            if count == 0 || count > if kind == K::Skew { 2 } else { 1 } {
234                return false;
235            }
236            match kind {
237                K::Skew => skew(args[0], if count > 1 { Some(args[1]) } else { None }, matrix),
238                K::SkewX => skew_x(args[0], matrix),
239                _ => skew_y(args[0], matrix),
240            }
241            true
242        }
243        K::Perspective => {
244            // None for `none`
245            let mut distance: Option<f64> = None;
246            for &child in &children {
247                let typ = t(child);
248                if typ == EnumToken::CommentTokenType || typ == EnumToken::WhitespaceTokenType {
249                    continue;
250                }
251                count += 1;
252                if typ == EnumToken::IdenTokenType && arena.string_equals(arena.string_value.get(child), "none") {
253                    distance = None;
254                    continue;
255                }
256                let Some(val) = length2_px(arena, child) else {
257                    return false;
258                };
259                distance = Some(val);
260            }
261            if count != 1 {
262                return false;
263            }
264            perspective(distance, matrix);
265            true
266        }
267        K::Matrix | K::Matrix3d => {
268            for &child in &children {
269                if matches!(t(child), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType | EnumToken::CommaTokenType) {
270                    continue;
271                }
272                if count < 16 {
273                    args[count] = get_number(arena, child);
274                }
275                count += 1;
276            }
277            if count != if kind == K::Matrix { 6 } else { 16 } {
278                return false;
279            }
280            let mut values = [0.0; 16];
281            set_matrix_values(&args, count, &mut values);
282            multiply_in_place(matrix, &values);
283            true
284        }
285        _ => false,
286    }
287}
288
289/// multiply a matrix in place by the matrices of a list of transform functions
290pub fn compute_matrix(arena: &AstArena, tokens: &[u32], start: usize, end: usize, matrix: &mut Matrix) -> bool {
291    tokens[start..end].iter().all(|&t| compute_transform(arena, t, matrix))
292}
293
294/// result of [`compute`]
295pub struct ComputedTransform {
296    /// the values of the matrix of the transform list, rounded (see `to_zero()`)
297    pub values: Matrix,
298    /// the matrix of the transform list: `none`, `matrix()` or `matrix3d()`
299    pub matrix: u32,
300    /// the transform list, each run of translations, rotations or scales and each other function minified
301    pub cumulative: Vec<u32>,
302    /// the minified matrix
303    pub minified: Vec<u32>,
304    /// true if the tokens of the `cumulative` list are all new tokens
305    pub created: bool,
306}
307
308/// compute the matrix of a transform list. `None` if the matrix cannot be computed
309pub fn compute(arena: &AstArena, transform_list: &[u32]) -> Option<ComputedTransform> {
310    use TransformKind as K;
311    // all rotation arguments must be numbers, percentages or angles below one turn
312    for &token in transform_list {
313        let kind = transform_kind(arena, arena.string_value.get(token)) & K::KindMask;
314        if matches!(kind, K::Rotate | K::RotateX | K::RotateY | K::RotateZ | K::Rotate3d) {
315            for child in arena.token_iter(token) {
316                let typ = arena.data_types.get(child);
317                if typ == EnumToken::WhitespaceTokenType || typ == EnumToken::CommaTokenType {
318                    continue;
319                }
320                if (typ != EnumToken::AngleTokenType && typ != EnumToken::NumberTokenType && typ != EnumToken::PercentageTokenType)
321                    // angle >= 360deg, do not transform
322                    || get_angle(arena, child).abs() >= 1.0
323                {
324                    return None;
325                }
326            }
327        }
328    }
329    let (tokens, runs) = split_transform_list(arena, transform_list);
330    let mut cumulative: Vec<u32> = Vec::new();
331    let mut matrix: Matrix = IDENTITY_MATRIX;
332    let mut empty = true;
333    let mut created = true;
334    for run in 0..runs.len().saturating_sub(1) {
335        let (start, end) = (runs[run], runs[run + 1]);
336        let mut run_matrix = IDENTITY_MATRIX;
337        if !compute_matrix(arena, &tokens, start, end, &mut run_matrix) {
338            return None;
339        }
340        multiply_in_place(&mut matrix, &run_matrix);
341        match minify(arena, &run_matrix) {
342            None => {
343                created = false;
344                empty = false;
345                for &token in &tokens[start..end] {
346                    push_transform(arena, &mut cumulative, token);
347                }
348            }
349            Some(minified) => {
350                empty = empty && minified.is_empty();
351                for token in minified {
352                    push_transform(arena, &mut cumulative, token);
353                }
354            }
355        }
356    }
357    let serialized = serialize(arena, &matrix);
358    if !empty && cumulative.is_empty() {
359        cumulative.push(arena.create_token(EnumToken::IdenTokenType, TokenValue::Str("none"), None));
360    }
361    to_zero(&mut matrix);
362    let matrix_token = serialize(arena, &matrix);
363    let minified = minify(arena, &matrix).unwrap_or_else(|| vec![serialized]);
364    Some(ComputedTransform { values: matrix, matrix: matrix_token, cumulative, minified, created })
365}
366
367/// append a token to a transform list. `none` is omitted
368fn push_transform(arena: &AstArena, list: &mut Vec<u32>, token: u32) {
369    if arena.data_types.get(token) != EnumToken::IdenTokenType || !arena.string_equals(arena.string_value.get(token), "none") {
370        list.push(token);
371    }
372}
373
374/// split a transform list into runs: the consecutive translations, rotations and scales are grouped, the other
375/// tokens are alone. the comments and the whitespace tokens are ignored. `(tokens, run starts + end)`
376fn split_transform_list(arena: &AstArena, transform_list: &[u32]) -> (Vec<u32>, Vec<usize>) {
377    let mut pattern = 0u32;
378    let mut tokens: Vec<u32> = Vec::new();
379    let mut runs: Vec<usize> = Vec::new();
380    for &token in transform_list {
381        let typ = arena.data_types.get(token);
382        if typ == EnumToken::CommentTokenType || typ == EnumToken::WhitespaceTokenType {
383            continue;
384        }
385        if typ == EnumToken::TransformFunctionTokenType {
386            let family = transform_kind(arena, arena.string_value.get(token)) & TransformKind::FamilyMask;
387            if pattern != 0 && family == pattern {
388                // continue the current run
389                tokens.push(token);
390                continue;
391            }
392            pattern = family;
393        }
394        runs.push(tokens.len());
395        tokens.push(token);
396    }
397    runs.push(tokens.len());
398    (tokens, runs)
399}