Skip to main content

orinium_browser/engine/css/
values.rs

1//! CSSの値を表す構造体と列挙型
2
3pub type CssIdent = smol_str::SmolStr;
4
5#[derive(Debug, Clone, PartialEq)]
6pub enum Unit {
7    Px,
8    Em,
9    Rem,
10    Percent,
11    Vw,
12    Vh,
13    Deg,
14}
15
16#[derive(Debug, Clone, PartialEq)]
17pub enum CssValue {
18    Keyword(CssIdent),               // e.g. auto, none
19    Length(f32, Unit),               // e.g. 10px
20    Number(f32),                     // e.g. 1.5
21    String(String),                  // e.g. "http"
22    Color(String),                   // e.g. #fff, #1f1f11
23    Function(String, Vec<CssValue>), // e.g. rgb(255,0,0)
24    List(Vec<CssValue>),             // e.g. 100px auto
25}
26
27impl CssValue {
28    /// Colorの文字列からRGBAタプルを返す
29    pub fn to_rgba_tuple(&self) -> Option<(u8, u8, u8, u8)> {
30        match self {
31            CssValue::Color(s) => parse_color(&format!("#{}", s)),
32            _ => None,
33        }
34    }
35}
36
37/// 簡易カラー文字列パーサ
38fn parse_color(s: &str) -> Option<(u8, u8, u8, u8)> {
39    let s = s.trim();
40    if let Some(hex) = s.strip_prefix('#') {
41        match hex.len() {
42            3 => {
43                // #RGB
44                let r = u8::from_str_radix(&hex[0..1].repeat(2), 16).ok()?;
45                let g = u8::from_str_radix(&hex[1..2].repeat(2), 16).ok()?;
46                let b = u8::from_str_radix(&hex[2..3].repeat(2), 16).ok()?;
47                Some((r, g, b, 255))
48            }
49            6 => {
50                // #RRGGBB
51                let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
52                let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
53                let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
54                Some((r, g, b, 255))
55            }
56            8 => {
57                // #RRGGBBAA
58                let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
59                let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
60                let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
61                let a = u8::from_str_radix(&hex[6..8], 16).ok()?;
62                Some((r, g, b, a))
63            }
64            _ => None,
65        }
66    } else {
67        None
68    }
69}