orinium_browser/engine/css/
values.rs

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