1use 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
16pub trait ToCss {
18 fn to_css_string(&self) -> String;
19}
20
21impl ToCss for Length {
24 fn to_css_string(&self) -> String {
25 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 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
95impl 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 let escaped = self.value.replace('\\', "\\\\").replace('"', "\\\"");
119 format!("\"{escaped}\"")
120 }
121}
122
123impl ToCss for Url {
124 fn to_css_string(&self) -> String {
125 let escaped = self.value.replace('\\', "\\\\").replace('"', "\\\"");
127 format!("url(\"{escaped}\")")
128 }
129}
130
131impl 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 format!("(-1 * {})", e.to_css_string())
144 }
145 MathExpression::Sum(a, b) => {
146 format!("{} + {}", a.to_css_string(), b.to_css_string())
148 }
149 MathExpression::Product(a, b) => {
150 format!("{} * {}", a.to_css_string(), b.to_css_string())
152 }
153 MathExpression::Quotient(a, b) => {
154 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
188impl 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
206fn 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
240fn 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}