takumi-css 0.2.0-beta.0

CSS parsing and style resolution layer for takumi.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::fmt;

use crate::style::{ToCss, declare_enum_from_css_impl, unexpected_token};
use cssparser::Parser;

use crate::style::{
  Animatable, BorderStyle, Color, ColorInput, CssSyntaxKind, CssToken, FromCss, MakeComputed,
  ParseResult, SizingContext, properties::Length, tw::TailwindPropertyParser,
};

/// CSSWG `<line-width>` keyword (`thin | medium | thick`).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum LineWidthKeyword {
  /// `thin`, resolves to 1px.
  Thin,
  /// `medium`, resolves to 3px (initial value of `border-width`/`outline-width`).
  #[default]
  Medium,
  /// `thick`, resolves to 5px.
  Thick,
}

declare_enum_from_css_impl!(
  LineWidthKeyword,
  "thin" => LineWidthKeyword::Thin,
  "medium" => LineWidthKeyword::Medium,
  "thick" => LineWidthKeyword::Thick,
);

impl From<LineWidthKeyword> for Length {
  fn from(keyword: LineWidthKeyword) -> Self {
    Length::Px(match keyword {
      LineWidthKeyword::Thin => 1.0,
      LineWidthKeyword::Medium => 3.0,
      LineWidthKeyword::Thick => 5.0,
    })
  }
}

/// CSSWG `<line-width>`: a `thin | medium | thick` keyword or a `<length>`.
///
/// Used by `border-*-width` and `outline-width`. The initial value is `medium`.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum LineWidth {
  /// A `thin | medium | thick` keyword.
  Keyword(LineWidthKeyword),
  /// An explicit length.
  Length(Length),
}

impl Default for LineWidth {
  fn default() -> Self {
    Self::Keyword(LineWidthKeyword::Medium)
  }
}

impl From<Length> for LineWidth {
  fn from(length: Length) -> Self {
    Self::Length(length)
  }
}

impl From<LineWidth> for Length {
  fn from(width: LineWidth) -> Self {
    match width {
      LineWidth::Keyword(keyword) => keyword.into(),
      LineWidth::Length(length) => length,
    }
  }
}

impl<'i> FromCss<'i> for LineWidth {
  fn from_css(input: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    if let Ok(keyword) = input.try_parse(LineWidthKeyword::from_css) {
      return Ok(Self::Keyword(keyword));
    }

    Ok(Self::Length(Length::from_css(input)?))
  }

  const VALID_TOKENS: &'static [CssToken] = &[
    CssToken::Keyword("thin"),
    CssToken::Keyword("medium"),
    CssToken::Keyword("thick"),
    CssToken::Syntax(CssSyntaxKind::Length),
  ];
}

impl MakeComputed for LineWidth {
  fn make_computed(&mut self, sizing: &SizingContext) {
    if let Self::Length(length) = self {
      length.make_computed(sizing);
    }
  }
}

impl Animatable for LineWidth {
  fn interpolate(
    &mut self,
    from: &Self,
    to: &Self,
    progress: f32,
    sizing: &SizingContext,
    current_color: Color,
  ) {
    let from_length = Length::from(*from);
    let to_length = Length::from(*to);
    let mut value = from_length;
    value.interpolate(&from_length, &to_length, progress, sizing, current_color);
    *self = Self::Length(value);
  }
}

impl TailwindPropertyParser for LineWidth {
  fn parse_tw(token: &str) -> Option<Self> {
    token
      .parse::<f32>()
      .ok()
      .map(|value| Self::Length(Length::Px(value)))
  }
}

impl ToCss for LineWidth {
  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
    match self {
      Self::Keyword(LineWidthKeyword::Thin) => dest.write_str("thin"),
      Self::Keyword(LineWidthKeyword::Medium) => dest.write_str("medium"),
      Self::Keyword(LineWidthKeyword::Thick) => dest.write_str("thick"),
      Self::Length(length) => length.to_css(dest),
    }
  }
}

/// Parsed `border` value.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Border {
  /// Border width.
  pub width: LineWidth,
  /// Border style.
  pub style: BorderStyle,
  /// Border color.
  pub color: ColorInput,
}

impl<'i> FromCss<'i> for Border {
  fn from_css(input: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    let mut width = None;
    let mut style = None;
    let mut color = None;

    loop {
      if input.is_exhausted() {
        break;
      }

      if let Ok(value) = input.try_parse(LineWidth::from_css) {
        width = Some(value);
        continue;
      }

      if let Ok(value) = input.try_parse(BorderStyle::from_css) {
        style = Some(value);
        continue;
      }

      if let Ok(value) = input.try_parse(ColorInput::from_css) {
        color = Some(value);
        continue;
      }

      return Err(unexpected_token!(
        input.current_source_location(),
        input.next()?,
      ));
    }

    Ok(Border {
      width: width.unwrap_or_default(),
      style: style.unwrap_or_default(),
      color: color.unwrap_or_default(),
    })
  }

  const VALID_TOKENS: &'static [CssToken] = &[
    CssToken::Syntax(CssSyntaxKind::Length),
    CssToken::Syntax(CssSyntaxKind::BorderStyle),
    CssToken::Syntax(CssSyntaxKind::Color),
  ];
}

impl MakeComputed for Border {
  fn make_computed(&mut self, sizing: &SizingContext) {
    self.width.make_computed(sizing);
  }
}

#[cfg(test)]
mod tests {
  use crate::style::Color;

  use super::*;

  #[test]
  fn test_parse_border_style_solid() {
    assert_eq!(BorderStyle::from_str("solid"), Ok(BorderStyle::Solid));
  }

  #[test]
  fn test_parse_border_style_dashed() {
    assert_eq!(BorderStyle::from_str("dashed"), Ok(BorderStyle::Dashed));
  }

  #[test]
  fn test_parse_border_width_only() {
    assert_eq!(
      Border::from_str("10px"),
      Ok(Border {
        width: LineWidth::Length(Length::Px(10.0)),
        style: BorderStyle::None,
        color: ColorInput::CurrentColor,
      })
    );
  }

  #[test]
  fn test_parse_border_style_only() {
    assert_eq!(
      Border::from_str("solid"),
      Ok(Border {
        width: LineWidth::default(),
        style: BorderStyle::Solid,
        color: ColorInput::CurrentColor,
      })
    );
  }

  #[test]
  fn test_parse_border_color_only() {
    assert_eq!(
      Border::from_str("red"),
      Ok(Border {
        width: LineWidth::default(),
        style: BorderStyle::None,
        color: ColorInput::Value(Color([255, 0, 0, 255])),
      })
    );
  }

  #[test]
  fn test_parse_border_width_and_style() {
    assert_eq!(
      Border::from_str("2px solid"),
      Ok(Border {
        width: LineWidth::Length(Length::Px(2.0)),
        style: BorderStyle::Solid,
        color: ColorInput::CurrentColor,
      })
    );
  }

  #[test]
  fn test_parse_border_width_style_color() {
    assert_eq!(
      Border::from_str("2px solid red"),
      Ok(Border {
        width: LineWidth::Length(Length::Px(2.0)),
        style: BorderStyle::Solid,
        color: ColorInput::Value(Color([255, 0, 0, 255])),
      })
    );
  }

  #[test]
  fn test_parse_border_style_width_color() {
    assert_eq!(
      Border::from_str("solid 2px red"),
      Ok(Border {
        width: LineWidth::Length(Length::Px(2.0)),
        style: BorderStyle::Solid,
        color: ColorInput::Value(Color([255, 0, 0, 255])),
      })
    );
  }

  #[test]
  fn test_parse_border_color_style_width() {
    assert_eq!(
      Border::from_str("red solid 2px"),
      Ok(Border {
        width: LineWidth::Length(Length::Px(2.0)),
        style: BorderStyle::Solid,
        color: ColorInput::Value(Color([255, 0, 0, 255])),
      })
    );
  }

  #[test]
  fn test_parse_border_rem_units() {
    assert_eq!(
      Border::from_str("1.5rem solid blue"),
      Ok(Border {
        width: LineWidth::Length(Length::Rem(1.5)),
        style: BorderStyle::Solid,
        color: ColorInput::Value(Color([0, 0, 255, 255])),
      })
    );
  }

  #[test]
  fn test_parse_border_hex_color() {
    assert_eq!(
      Border::from_str("3px solid #ff0000"),
      Ok(Border {
        width: LineWidth::Length(Length::Px(3.0)),
        style: BorderStyle::Solid,
        color: ColorInput::Value(Color([255, 0, 0, 255])),
      })
    );
  }

  #[test]
  fn test_parse_border_rgb_color() {
    assert_eq!(
      Border::from_str("4px solid rgb(0, 255, 0)"),
      Ok(Border {
        width: LineWidth::Length(Length::Px(4.0)),
        style: BorderStyle::Solid,
        color: ColorInput::Value(Color([0, 255, 0, 255])),
      })
    );
  }

  #[test]
  fn test_parse_border_dashed() {
    assert_eq!(
      Border::from_str("2px dashed red"),
      Ok(Border {
        width: LineWidth::Length(Length::Px(2.0)),
        style: BorderStyle::Dashed,
        color: ColorInput::Value(Color([255, 0, 0, 255])),
      })
    );
  }

  #[test]
  fn test_parse_border_invalid_color() {
    assert!(Border::from_str("2px solid invalid-color").is_err());
  }

  #[test]
  fn test_parse_border_empty() {
    assert_eq!(Border::from_str(""), Ok(Border::default()));
  }

  #[test]
  fn test_border_value_from_css() {
    assert_eq!(
      Border::from_str("3px solid blue"),
      Ok(Border {
        width: LineWidth::Length(Length::Px(3.0)),
        style: BorderStyle::Solid,
        color: ColorInput::Value(Color([0, 0, 255, 255])),
      })
    );
  }

  #[test]
  fn test_border_value_from_invalid_css() {
    assert!(Border::from_str("invalid border").is_err());
  }

  #[test]
  fn test_line_width_default_is_medium() {
    assert_eq!(
      LineWidth::default(),
      LineWidth::Keyword(LineWidthKeyword::Medium)
    );
    assert_eq!(Length::from(LineWidth::default()), Length::Px(3.0));
    assert_eq!(Length::from(LineWidthKeyword::Thin), Length::Px(1.0));
    assert_eq!(Length::from(LineWidthKeyword::Thick), Length::Px(5.0));
  }

  #[test]
  fn test_line_width_keywords() {
    assert_eq!(
      LineWidth::from_str("thin"),
      Ok(LineWidth::Keyword(LineWidthKeyword::Thin))
    );
    assert_eq!(
      LineWidth::from_str("medium"),
      Ok(LineWidth::Keyword(LineWidthKeyword::Medium))
    );
    assert_eq!(
      LineWidth::from_str("thick"),
      Ok(LineWidth::Keyword(LineWidthKeyword::Thick))
    );
    assert_eq!(
      LineWidth::from_str("2px"),
      Ok(LineWidth::Length(Length::Px(2.0)))
    );
  }

  #[test]
  fn test_border_keyword_width() {
    assert_eq!(
      Border::from_str("thick solid"),
      Ok(Border {
        width: LineWidth::Keyword(LineWidthKeyword::Thick),
        style: BorderStyle::Solid,
        color: ColorInput::CurrentColor,
      })
    );
  }
}