Skip to main content

rust_css_parser/ast/transform/
matrix.rs

1//! Port of `src/ast/transform/matrix.ts`.
2
3use super::utils::{is_2d_matrix, is_identity};
4use super::Matrix;
5use crate::ast::arena::{AstArena, TokenValue};
6use crate::ast::types::EnumToken;
7
8/// set the values of a `matrix()` (6 values) or of a `matrix3d()` (16 values) function
9pub fn set_matrix_values(values: &[f64], count: usize, matrix: &mut Matrix) {
10    if count == 6 {
11        *matrix = [values[0], values[1], 0.0, 0.0, values[2], values[3], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, values[4], values[5], 0.0, 1.0];
12    } else {
13        matrix.copy_from_slice(&values[..16]);
14    }
15}
16
17/// the tokens of a matrix: `none`, `matrix()` if it is a 2d matrix, `matrix3d()` otherwise
18pub fn serialize(arena: &AstArena, matrix: &Matrix) -> u32 {
19    if is_identity(matrix) {
20        return arena.create_token(EnumToken::IdenTokenType, TokenValue::Str("none"), None);
21    }
22    // https://drafts.csswg.org/css-transforms-2/#two-dimensional-subset
23    let is_2d = is_2d_matrix(matrix);
24    let count = if is_2d { 6 } else { 16 };
25    let mut tokens: Vec<u32> = Vec::with_capacity(count * 2 - 1);
26    for i in 0..count {
27        if i > 0 {
28            tokens.push(arena.create_token(EnumToken::CommaTokenType, TokenValue::None, None));
29        }
30        // matrix(a, b, c, d, e, f): values 0, 1, 4, 5, 12, 13
31        let index = if is_2d {
32            if i < 2 {
33                i
34            } else if i < 4 {
35                i + 2
36            } else {
37                i + 8
38            }
39        } else {
40            i
41        };
42        tokens.push(arena.create_token(EnumToken::NumberTokenType, TokenValue::Num(matrix[index]), None));
43    }
44    arena.create_function(EnumToken::TransformFunctionTokenType, if is_2d { "matrix" } else { "matrix3d" }, Some(&tokens))
45}