Skip to main content

muskitty_css_values/
serialize.rs

1//! 序列化 — CSS Values Level 4 §8.1 + §9.7 calc-serialize。
2//!
3//! 提供 `ToCss` trait 将类型化值序列化回 CSS 字符串。
4//! 序列化遵循 §8.1(functional notation)和 §9.7(calc-serialize)规则,
5//! 但 CV-5 阶段实现的是简化版(不做 calculation tree 的 sort/simplify)。
6
7use crate::math::{MathConstant, MathExpression};
8use crate::numeric::{
9    Angle, Frequency, Integer, Length, Number, Percentage, Ratio, Resolution, Time,
10};
11use crate::textual::{CssString, CustomIdent, DashedIdent, Keyword, Url};
12use crate::var::VarReference;
13use muskitty_css::parser::ComponentValue;
14use muskitty_css::tokenizer::Token;
15
16/// 序列化为 CSS 字符串(specified value 序列化,§8.1)。
17pub trait ToCss {
18    fn to_css_string(&self) -> String;
19}
20
21// ── 数值类型 ────────────────────────────────────────────────────────
22
23impl ToCss for Length {
24    fn to_css_string(&self) -> String {
25        // §8.1: number 后跟单位,无空格
26        format!("{}{}", format_number(self.value), self.unit.to_str())
27    }
28}
29
30impl ToCss for Percentage {
31    fn to_css_string(&self) -> String {
32        format!("{}%", format_number(self.value))
33    }
34}
35
36impl ToCss for Number {
37    fn to_css_string(&self) -> String {
38        format_number(self.value)
39    }
40}
41
42impl ToCss for Integer {
43    fn to_css_string(&self) -> String {
44        self.value.to_string()
45    }
46}
47
48impl ToCss for Angle {
49    fn to_css_string(&self) -> String {
50        format!("{}{}", format_number(self.value), angle_unit_str(self.unit))
51    }
52}
53
54impl ToCss for Time {
55    fn to_css_string(&self) -> String {
56        format!("{}{}", format_number(self.value), time_unit_str(self.unit))
57    }
58}
59
60impl ToCss for Frequency {
61    fn to_css_string(&self) -> String {
62        format!(
63            "{}{}",
64            format_number(self.value),
65            frequency_unit_str(self.unit)
66        )
67    }
68}
69
70impl ToCss for Resolution {
71    fn to_css_string(&self) -> String {
72        format!(
73            "{}{}",
74            format_number(self.value),
75            resolution_unit_str(self.unit)
76        )
77    }
78}
79
80impl ToCss for Ratio {
81    fn to_css_string(&self) -> String {
82        // §4.7: 单数字时 height 默认 1,但序列化时如果 height==1 只输出 width
83        if self.height == 1.0 {
84            format_number(self.width)
85        } else {
86            format!(
87                "{} / {}",
88                format_number(self.width),
89                format_number(self.height)
90            )
91        }
92    }
93}
94
95// ── 文本类型 ────────────────────────────────────────────────────────
96
97impl ToCss for Keyword {
98    fn to_css_string(&self) -> String {
99        self.value.clone()
100    }
101}
102
103impl ToCss for CustomIdent {
104    fn to_css_string(&self) -> String {
105        self.value.clone()
106    }
107}
108
109impl ToCss for DashedIdent {
110    fn to_css_string(&self) -> String {
111        self.value.clone()
112    }
113}
114
115impl ToCss for CssString {
116    fn to_css_string(&self) -> String {
117        // §8.1: string 序列化时用双引号包裹,转义内部双引号和反斜杠
118        let escaped = self.value.replace('\\', "\\\\").replace('"', "\\\"");
119        format!("\"{escaped}\"")
120    }
121}
122
123impl ToCss for Url {
124    fn to_css_string(&self) -> String {
125        // §8.1: url() 序列化为 url("value") 形式(quoted)
126        let escaped = self.value.replace('\\', "\\\\").replace('"', "\\\"");
127        format!("url(\"{escaped}\")")
128    }
129}
130
131// ── MathExpression ─────────────────────────────────────────────────
132
133impl ToCss for MathExpression {
134    fn to_css_string(&self) -> String {
135        match self {
136            MathExpression::Length(l) => l.to_css_string(),
137            MathExpression::Percentage(p) => p.to_css_string(),
138            MathExpression::Number(n) => n.to_css_string(),
139            MathExpression::Constant(c) => c.to_str().to_string(),
140            MathExpression::Var(v) => v.to_css_string(),
141            MathExpression::Negate(e) => {
142                // §9.7: Negate 序列化为 (-1 * expr)
143                format!("(-1 * {})", e.to_css_string())
144            }
145            MathExpression::Sum(a, b) => {
146                // §9.7: + 两侧有空格
147                format!("{} + {}", a.to_css_string(), b.to_css_string())
148            }
149            MathExpression::Product(a, b) => {
150                // §9.7: * 两侧无空格
151                format!("{} * {}", a.to_css_string(), b.to_css_string())
152            }
153            MathExpression::Quotient(a, b) => {
154                // §9.7: / 两侧无空格
155                format!("{} / {}", a.to_css_string(), b.to_css_string())
156            }
157            MathExpression::Min(args) => {
158                format!("min({})", serialize_args(args))
159            }
160            MathExpression::Max(args) => {
161                format!("max({})", serialize_args(args))
162            }
163            MathExpression::Clamp { min, val, max } => {
164                format!(
165                    "clamp({}, {}, {})",
166                    min.to_css_string(),
167                    val.to_css_string(),
168                    max.to_css_string()
169                )
170            }
171        }
172    }
173}
174
175impl ToCss for MathConstant {
176    fn to_css_string(&self) -> String {
177        self.to_str().to_string()
178    }
179}
180
181fn serialize_args(args: &[MathExpression]) -> String {
182    args.iter()
183        .map(|a| a.to_css_string())
184        .collect::<Vec<_>>()
185        .join(", ")
186}
187
188// ── VarReference ───────────────────────────────────────────────────
189
190impl ToCss for VarReference {
191    fn to_css_string(&self) -> String {
192        match &self.fallback {
193            None => format!("var({})", self.name),
194            Some(fallback) => {
195                let s: String = fallback
196                    .iter()
197                    .map(cv_to_string)
198                    .collect::<Vec<_>>()
199                    .join("");
200                format!("var({}, {})", self.name, s.trim())
201            }
202        }
203    }
204}
205
206/// 将单个 ComponentValue 序列化为 CSS 字符串片段。
207///
208/// 这是一个最小化的序列化器,只覆盖 var() fallback 中常见的 token 类型。
209/// 完整的 ComponentValue 序列化应在 css-parser 层实现。
210fn cv_to_string(cv: &ComponentValue) -> String {
211    match cv {
212        ComponentValue::PreservedToken(Token::Ident(s)) => s.clone(),
213        ComponentValue::PreservedToken(Token::String(s)) => format!("\"{s}\""),
214        ComponentValue::PreservedToken(Token::Number(n)) => format_number(n.value),
215        ComponentValue::PreservedToken(Token::Percentage(n)) => {
216            format!("{}%", format_number(n.value))
217        }
218        ComponentValue::PreservedToken(Token::Dimension(n, u)) => {
219            format!("{}{}", format_number(n.value), u)
220        }
221        ComponentValue::PreservedToken(Token::Whitespace) => " ".to_string(),
222        ComponentValue::PreservedToken(Token::Comma) => ",".to_string(),
223        ComponentValue::PreservedToken(Token::Colon) => ":".to_string(),
224        ComponentValue::PreservedToken(Token::Semicolon) => ";".to_string(),
225        ComponentValue::PreservedToken(Token::Delim(c)) => c.to_string(),
226        ComponentValue::PreservedToken(Token::Hash(s, _)) => format!("#{s}"),
227        ComponentValue::Function(f) => {
228            let args: String = f
229                .value
230                .iter()
231                .map(cv_to_string)
232                .collect::<Vec<_>>()
233                .join("");
234            format!("{}({})", f.name, args.trim())
235        }
236        _ => String::new(),
237    }
238}
239
240// ── 辅助函数 ────────────────────────────────────────────────────────
241
242/// §8.1: 数字序列化——整数无小数点,浮点数保留有效数字。
243fn format_number(v: f64) -> String {
244    if v == v.trunc() && v.is_finite() {
245        format!("{:.0}", v)
246    } else {
247        format!("{}", v)
248    }
249}
250
251fn angle_unit_str(u: crate::numeric::AngleUnit) -> &'static str {
252    use crate::numeric::AngleUnit::*;
253    match u {
254        Deg => "deg",
255        Grad => "grad",
256        Rad => "rad",
257        Turn => "turn",
258    }
259}
260
261fn time_unit_str(u: crate::numeric::TimeUnit) -> &'static str {
262    use crate::numeric::TimeUnit::*;
263    match u {
264        S => "s",
265        Ms => "ms",
266    }
267}
268
269fn frequency_unit_str(u: crate::numeric::FrequencyUnit) -> &'static str {
270    use crate::numeric::FrequencyUnit::*;
271    match u {
272        Hz => "Hz",
273        KHz => "kHz",
274    }
275}
276
277fn resolution_unit_str(u: crate::numeric::ResolutionUnit) -> &'static str {
278    use crate::numeric::ResolutionUnit::*;
279    match u {
280        Dpi => "dpi",
281        Dpcm => "dpcm",
282        Dppx => "dppx",
283    }
284}