Skip to main content

muskitty_css_values/
numeric.rs

1//! 数值类型 — CSS Values Level 4 §4-§6。
2
3use muskitty_css::parser::ComponentValue;
4use muskitty_css::tokenizer::Token;
5
6/// 值解析错误。
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct ParseError {
9    pub message: String,
10}
11
12impl ParseError {
13    pub fn new(message: impl Into<String>) -> Self {
14        Self {
15            message: message.into(),
16        }
17    }
18}
19
20impl std::fmt::Display for ParseError {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        write!(f, "CSS value parse error: {}", self.message)
23    }
24}
25
26impl std::error::Error for ParseError {}
27
28/// 从 ComponentValue 列表中提取唯一的非 whitespace token。
29pub fn single_non_ws_cv(cvs: &[ComponentValue]) -> Result<&ComponentValue, ParseError> {
30    let filtered: Vec<&ComponentValue> = cvs
31        .iter()
32        .filter(|cv| !matches!(cv, ComponentValue::PreservedToken(Token::Whitespace)))
33        .collect();
34    if filtered.len() != 1 {
35        return Err(ParseError::new(format!(
36            "expected exactly one value, got {}",
37            filtered.len()
38        )));
39    }
40    Ok(filtered[0])
41}
42
43// ── §5 Length ────────────────────────────────────────────────────────
44
45/// CSS `<length>` 值 (css-values-4 §5)。
46///
47/// 一个数值 + 长度单位。本阶段不计算绝对长度(如 em→px),
48/// 保留原始值和单位,求值留到 Cascade 阶段。
49#[derive(Debug, Clone, PartialEq)]
50pub struct Length {
51    pub value: f64,
52    pub unit: LengthUnit,
53}
54
55/// 长度单位 (css-values-4 §5.1 相对、§5.2 绝对)。
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum LengthUnit {
58    // 相对 (§5.1)
59    Em,
60    Rem,
61    Ex,
62    Ch,
63    Vw,
64    Vh,
65    Vmin,
66    Vmax,
67    // 绝对 (§5.2)
68    Px,
69    Cm,
70    Mm,
71    In,
72    Pt,
73    Pc,
74    Q,
75}
76
77impl LengthUnit {
78    /// 从字符串解析长度单位(ASCII case-insensitive)。
79    pub fn parse_unit(s: &str) -> Option<Self> {
80        match s.to_ascii_lowercase().as_str() {
81            "em" => Some(Self::Em),
82            "rem" => Some(Self::Rem),
83            "ex" => Some(Self::Ex),
84            "ch" => Some(Self::Ch),
85            "vw" => Some(Self::Vw),
86            "vh" => Some(Self::Vh),
87            "vmin" => Some(Self::Vmin),
88            "vmax" => Some(Self::Vmax),
89            "px" => Some(Self::Px),
90            "cm" => Some(Self::Cm),
91            "mm" => Some(Self::Mm),
92            "in" => Some(Self::In),
93            "pt" => Some(Self::Pt),
94            "pc" => Some(Self::Pc),
95            "q" => Some(Self::Q),
96            _ => None,
97        }
98    }
99
100    /// 序列化为 CSS 单位字符串。
101    pub fn to_str(self) -> &'static str {
102        match self {
103            Self::Em => "em",
104            Self::Rem => "rem",
105            Self::Ex => "ex",
106            Self::Ch => "ch",
107            Self::Vw => "vw",
108            Self::Vh => "vh",
109            Self::Vmin => "vmin",
110            Self::Vmax => "vmax",
111            Self::Px => "px",
112            Self::Cm => "cm",
113            Self::Mm => "mm",
114            Self::In => "in",
115            Self::Pt => "pt",
116            Self::Pc => "pc",
117            Self::Q => "Q",
118        }
119    }
120}
121
122impl Length {
123    /// 从 CSS 字符串解析一个 `<length>` 值。
124    pub fn parse(input: &str) -> Result<Self, ParseError> {
125        let cvs = muskitty_css::parse_list_of_component_values(input);
126        Self::from_cvs(&cvs)
127    }
128
129    /// 从 ComponentValue 列表解析。
130    pub fn from_cvs(cvs: &[ComponentValue]) -> Result<Self, ParseError> {
131        let cv = single_non_ws_cv(cvs)?;
132        match cv {
133            ComponentValue::PreservedToken(Token::Dimension(numeric, unit)) => {
134                let unit = LengthUnit::parse_unit(unit)
135                    .ok_or_else(|| ParseError::new(format!("unknown length unit: {unit}")))?;
136                Ok(Length {
137                    value: numeric.value,
138                    unit,
139                })
140            }
141            _ => Err(ParseError::new("expected a dimension token for length")),
142        }
143    }
144}
145
146// ── §4.6 Percentage ─────────────────────────────────────────────────
147
148/// CSS `<percentage>` 值 (§4.6)。
149#[derive(Debug, Clone, PartialEq)]
150pub struct Percentage {
151    pub value: f64,
152}
153
154impl Percentage {
155    pub fn parse(input: &str) -> Result<Self, ParseError> {
156        let cvs = muskitty_css::parse_list_of_component_values(input);
157        Self::from_cvs(&cvs)
158    }
159
160    pub fn from_cvs(cvs: &[ComponentValue]) -> Result<Self, ParseError> {
161        let cv = single_non_ws_cv(cvs)?;
162        match cv {
163            ComponentValue::PreservedToken(Token::Percentage(numeric)) => Ok(Percentage {
164                value: numeric.value,
165            }),
166            _ => Err(ParseError::new("expected a percentage token")),
167        }
168    }
169}
170
171// ── §4.4 Number ─────────────────────────────────────────────────────
172
173/// CSS `<number>` 值 (§4.4)。
174#[derive(Debug, Clone, PartialEq)]
175pub struct Number {
176    pub value: f64,
177}
178
179impl Number {
180    pub fn parse(input: &str) -> Result<Self, ParseError> {
181        let cvs = muskitty_css::parse_list_of_component_values(input);
182        Self::from_cvs(&cvs)
183    }
184
185    pub fn from_cvs(cvs: &[ComponentValue]) -> Result<Self, ParseError> {
186        let cv = single_non_ws_cv(cvs)?;
187        match cv {
188            ComponentValue::PreservedToken(Token::Number(numeric)) => Ok(Number {
189                value: numeric.value,
190            }),
191            _ => Err(ParseError::new("expected a number token")),
192        }
193    }
194}
195
196// ── §4.3 Integer ────────────────────────────────────────────────────
197
198/// CSS `<integer>` 值 (§4.3)。
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct Integer {
201    pub value: i32,
202}
203
204impl Integer {
205    pub fn parse(input: &str) -> Result<Self, ParseError> {
206        let cvs = muskitty_css::parse_list_of_component_values(input);
207        Self::from_cvs(&cvs)
208    }
209
210    pub fn from_cvs(cvs: &[ComponentValue]) -> Result<Self, ParseError> {
211        let cv = single_non_ws_cv(cvs)?;
212        match cv {
213            ComponentValue::PreservedToken(Token::Number(numeric)) if numeric.is_integer => {
214                Ok(Integer {
215                    value: numeric.value as i32,
216                })
217            }
218            _ => Err(ParseError::new("expected an integer token")),
219        }
220    }
221}
222
223// ── §6.1 Angle ──────────────────────────────────────────────────────
224
225/// CSS `<angle>` 值 (§6.1)。
226#[derive(Debug, Clone, PartialEq)]
227pub struct Angle {
228    pub value: f64,
229    pub unit: AngleUnit,
230}
231
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub enum AngleUnit {
234    Deg,
235    Grad,
236    Rad,
237    Turn,
238}
239
240impl AngleUnit {
241    pub fn parse_unit(s: &str) -> Option<Self> {
242        match s.to_ascii_lowercase().as_str() {
243            "deg" => Some(Self::Deg),
244            "grad" => Some(Self::Grad),
245            "rad" => Some(Self::Rad),
246            "turn" => Some(Self::Turn),
247            _ => None,
248        }
249    }
250}
251
252impl Angle {
253    pub fn parse(input: &str) -> Result<Self, ParseError> {
254        let cvs = muskitty_css::parse_list_of_component_values(input);
255        Self::from_cvs(&cvs)
256    }
257
258    pub fn from_cvs(cvs: &[ComponentValue]) -> Result<Self, ParseError> {
259        let cv = single_non_ws_cv(cvs)?;
260        match cv {
261            ComponentValue::PreservedToken(Token::Dimension(numeric, unit)) => {
262                let unit = AngleUnit::parse_unit(unit)
263                    .ok_or_else(|| ParseError::new(format!("unknown angle unit: {unit}")))?;
264                Ok(Angle {
265                    value: numeric.value,
266                    unit,
267                })
268            }
269            // §6.1: bare 0 is a valid angle (represents 0deg)
270            ComponentValue::PreservedToken(Token::Number(numeric)) if numeric.value == 0.0 => {
271                Ok(Angle {
272                    value: 0.0,
273                    unit: AngleUnit::Deg,
274                })
275            }
276            _ => Err(ParseError::new("expected a dimension or 0 for angle")),
277        }
278    }
279}
280
281// ── §6.2 Time ───────────────────────────────────────────────────────
282
283/// CSS `<time>` 值 (§6.2)。
284#[derive(Debug, Clone, PartialEq)]
285pub struct Time {
286    pub value: f64,
287    pub unit: TimeUnit,
288}
289
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
291pub enum TimeUnit {
292    S,
293    Ms,
294}
295
296impl TimeUnit {
297    pub fn parse_unit(s: &str) -> Option<Self> {
298        match s.to_ascii_lowercase().as_str() {
299            "s" => Some(Self::S),
300            "ms" => Some(Self::Ms),
301            _ => None,
302        }
303    }
304}
305
306impl Time {
307    pub fn parse(input: &str) -> Result<Self, ParseError> {
308        let cvs = muskitty_css::parse_list_of_component_values(input);
309        Self::from_cvs(&cvs)
310    }
311
312    pub fn from_cvs(cvs: &[ComponentValue]) -> Result<Self, ParseError> {
313        let cv = single_non_ws_cv(cvs)?;
314        match cv {
315            ComponentValue::PreservedToken(Token::Dimension(numeric, unit)) => {
316                let unit = TimeUnit::parse_unit(unit)
317                    .ok_or_else(|| ParseError::new(format!("unknown time unit: {unit}")))?;
318                Ok(Time {
319                    value: numeric.value,
320                    unit,
321                })
322            }
323            _ => Err(ParseError::new("expected a dimension token for time")),
324        }
325    }
326}
327
328// ── §6.3 Frequency ──────────────────────────────────────────────────
329
330/// CSS `<frequency>` 值 (§6.3)。
331#[derive(Debug, Clone, PartialEq)]
332pub struct Frequency {
333    pub value: f64,
334    pub unit: FrequencyUnit,
335}
336
337#[derive(Debug, Clone, Copy, PartialEq, Eq)]
338pub enum FrequencyUnit {
339    Hz,
340    KHz,
341}
342
343impl FrequencyUnit {
344    pub fn parse_unit(s: &str) -> Option<Self> {
345        match s.to_ascii_lowercase().as_str() {
346            "hz" => Some(Self::Hz),
347            "khz" => Some(Self::KHz),
348            _ => None,
349        }
350    }
351}
352
353impl Frequency {
354    pub fn parse(input: &str) -> Result<Self, ParseError> {
355        let cvs = muskitty_css::parse_list_of_component_values(input);
356        Self::from_cvs(&cvs)
357    }
358
359    pub fn from_cvs(cvs: &[ComponentValue]) -> Result<Self, ParseError> {
360        let cv = single_non_ws_cv(cvs)?;
361        match cv {
362            ComponentValue::PreservedToken(Token::Dimension(numeric, unit)) => {
363                let unit = FrequencyUnit::parse_unit(unit)
364                    .ok_or_else(|| ParseError::new(format!("unknown frequency unit: {unit}")))?;
365                Ok(Frequency {
366                    value: numeric.value,
367                    unit,
368                })
369            }
370            _ => Err(ParseError::new("expected a dimension token for frequency")),
371        }
372    }
373}
374
375// ── §6.4 Resolution ─────────────────────────────────────────────────
376
377/// CSS `<resolution>` 值 (§6.4)。
378#[derive(Debug, Clone, PartialEq)]
379pub struct Resolution {
380    pub value: f64,
381    pub unit: ResolutionUnit,
382}
383
384#[derive(Debug, Clone, Copy, PartialEq, Eq)]
385pub enum ResolutionUnit {
386    Dpi,
387    Dpcm,
388    Dppx,
389}
390
391impl ResolutionUnit {
392    pub fn parse_unit(s: &str) -> Option<Self> {
393        match s.to_ascii_lowercase().as_str() {
394            "dpi" => Some(Self::Dpi),
395            "dpcm" => Some(Self::Dpcm),
396            "dppx" => Some(Self::Dppx),
397            _ => None,
398        }
399    }
400}
401
402impl Resolution {
403    pub fn parse(input: &str) -> Result<Self, ParseError> {
404        let cvs = muskitty_css::parse_list_of_component_values(input);
405        Self::from_cvs(&cvs)
406    }
407
408    pub fn from_cvs(cvs: &[ComponentValue]) -> Result<Self, ParseError> {
409        let cv = single_non_ws_cv(cvs)?;
410        match cv {
411            ComponentValue::PreservedToken(Token::Dimension(numeric, unit)) => {
412                let unit = ResolutionUnit::parse_unit(unit)
413                    .ok_or_else(|| ParseError::new(format!("unknown resolution unit: {unit}")))?;
414                Ok(Resolution {
415                    value: numeric.value,
416                    unit,
417                })
418            }
419            _ => Err(ParseError::new("expected a dimension token for resolution")),
420        }
421    }
422}
423
424// ── §4.7 Ratio ──────────────────────────────────────────────────────
425
426/// CSS `<ratio>` 值 (§4.7)。
427///
428/// 语法:`<number [0,∞]> [ / <number [0,∞]> ]?`
429/// 单数字时 height 默认 1.0。
430#[derive(Debug, Clone, PartialEq)]
431pub struct Ratio {
432    pub width: f64,
433    pub height: f64,
434}
435
436impl Ratio {
437    pub fn parse(input: &str) -> Result<Self, ParseError> {
438        let cvs = muskitty_css::parse_list_of_component_values(input);
439        Self::from_cvs(&cvs)
440    }
441
442    pub fn from_cvs(cvs: &[ComponentValue]) -> Result<Self, ParseError> {
443        // 过滤 whitespace,收集非 ws 的 component values
444        let filtered: Vec<&ComponentValue> = cvs
445            .iter()
446            .filter(|cv| !matches!(cv, ComponentValue::PreservedToken(Token::Whitespace)))
447            .collect();
448
449        if filtered.is_empty() {
450            return Err(ParseError::new("ratio requires at least one number"));
451        }
452
453        // 第一个必须是 number
454        let width = match filtered[0] {
455            ComponentValue::PreservedToken(Token::Number(numeric)) => numeric.value,
456            _ => return Err(ParseError::new("ratio first value must be a number")),
457        };
458
459        if width < 0.0 {
460            return Err(ParseError::new("ratio values must be non-negative"));
461        }
462
463        // 只有一个 number → height = 1
464        if filtered.len() == 1 {
465            return Ok(Ratio { width, height: 1.0 });
466        }
467
468        // 两个元素:必须是 `/` + number
469        if filtered.len() != 3 {
470            return Err(ParseError::new(
471                "ratio with second value must be 'number / number'",
472            ));
473        }
474
475        if !matches!(
476            filtered[1],
477            ComponentValue::PreservedToken(Token::Delim('/'))
478        ) {
479            return Err(ParseError::new("expected '/' between ratio numbers"));
480        }
481
482        let height = match filtered[2] {
483            ComponentValue::PreservedToken(Token::Number(numeric)) => numeric.value,
484            _ => return Err(ParseError::new("ratio second value must be a number")),
485        };
486
487        if height < 0.0 {
488            return Err(ParseError::new("ratio values must be non-negative"));
489        }
490
491        Ok(Ratio { width, height })
492    }
493}