takumi-css 0.2.0-rc.2

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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use std::fmt;

use crate::style::{ToCss, unexpected_token};
use bitflags::bitflags;
use cssparser::{Parser, Token, match_ignore_ascii_case};
use typed_builder::TypedBuilder;

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

bitflags! {
  /// Represents a collection of text decoration lines.
  #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
  #[non_exhaustive]
  pub struct TextDecorationLines: u8 {
    /// Underline text decoration.
    const UNDERLINE = 0b001;
    /// Line-through text decoration.
    const LINE_THROUGH = 0b010;
    /// Overline text decoration.
    const OVERLINE = 0b100;
  }
}

impl<'i> FromCss<'i> for TextDecorationLines {
  fn from_css(input: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    let mut lines = TextDecorationLines::empty();

    // Parse at least one line decoration
    let first_location = input.current_source_location();
    let first_ident = input.expect_ident()?;
    match_ignore_ascii_case! {first_ident,
      "underline" => lines |= TextDecorationLines::UNDERLINE,
      "line-through" => lines |= TextDecorationLines::LINE_THROUGH,
      "overline" => lines |= TextDecorationLines::OVERLINE,
      _ => return Err(unexpected_token!(first_location, &Token::Ident(first_ident.clone()))),
    }

    // Parse additional decorations if present
    while !input.is_exhausted() {
      let state = input.state();
      if let Ok(ident) = input.expect_ident() {
        match_ignore_ascii_case! {ident,
          "underline" => lines |= TextDecorationLines::UNDERLINE,
          "line-through" => lines |= TextDecorationLines::LINE_THROUGH,
          "overline" => lines |= TextDecorationLines::OVERLINE,
          _ => {
            input.reset(&state);
            break;
          }
        }
      } else {
        break;
      }
    }

    Ok(lines)
  }

  const VALID_TOKENS: &'static [CssToken] = &[
    CssToken::Keyword("underline"),
    CssToken::Keyword("line-through"),
    CssToken::Keyword("overline"),
  ];
}

impl MakeComputed for TextDecorationLines {}

/// Represents text decoration thickness options.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum TextDecorationThickness {
  /// Use the font's default thickness, fallback to `auto` if not available.
  FromFont,
  /// Use a specific length.
  Length(Length),
}

impl Default for TextDecorationThickness {
  fn default() -> Self {
    Self::Length(Length::Auto)
  }
}

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

impl Animatable for TextDecorationThickness {
  fn interpolate(
    &mut self,
    from: &Self,
    to: &Self,
    progress: f32,
    sizing: &SizingContext,
    current_color: Color,
  ) {
    *self = match (*from, *to) {
      (TextDecorationThickness::Length(from), TextDecorationThickness::Length(to)) => {
        let mut value = from;
        value.interpolate(&from, &to, progress, sizing, current_color);
        TextDecorationThickness::Length(value)
      }
      _ => {
        if progress >= 0.5 {
          *to
        } else {
          *from
        }
      }
    };
  }
}

/// Decoration thickness resolved for rendering.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SizedTextDecorationThickness {
  /// Use the font's own thickness.
  FromFont,
  /// A thickness in pixels.
  Value(f32),
}

impl<'i> FromCss<'i> for TextDecorationThickness {
  fn from_css(input: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    if input
      .try_parse(|input| input.expect_ident_matching("from-font"))
      .is_ok()
    {
      return Ok(Self::FromFont);
    }

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

  const VALID_TOKENS: &'static [CssToken] = &[
    CssToken::Keyword("from-font"),
    CssToken::Syntax(CssSyntaxKind::Length),
    CssToken::Syntax(CssSyntaxKind::Percentage),
  ];
}

impl TailwindPropertyParser for TextDecorationThickness {
  fn parse_tw(token: &str) -> Option<Self> {
    if let Ok(number) = token.parse::<f32>() {
      return Some(Self::Length(Length::Px(number)));
    }

    Self::from_str(token).ok()
  }
}

impl ToCss for TextDecorationLines {
  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
    if self.is_empty() {
      return dest.write_str("none");
    }
    let mut first = true;
    if self.contains(TextDecorationLines::UNDERLINE) {
      dest.write_str("underline")?;
      first = false;
    }
    if self.contains(TextDecorationLines::LINE_THROUGH) {
      if !first {
        dest.write_char(' ')?;
      }
      dest.write_str("line-through")?;
      first = false;
    }
    if self.contains(TextDecorationLines::OVERLINE) {
      if !first {
        dest.write_char(' ')?;
      }
      dest.write_str("overline")?;
    }
    Ok(())
  }
}

impl ToCss for TextDecorationThickness {
  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
    match self {
      Self::FromFont => dest.write_str("from-font"),
      Self::Length(l) => l.to_css(dest),
    }
  }
}

/// Represents the `text-underline-offset` value, shifting the underline away from
/// the text. Positive lengths move it further from the text.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub enum TextUnderlineOffset {
  /// Use the font's default underline position.
  #[default]
  Auto,
  /// Offset by a specific length; percentages resolve against `1em`.
  Length(Length),
}

impl TextUnderlineOffset {
  /// Resolves the offset to pixels, with `auto` yielding `0`.
  pub fn resolve_px(&self, sizing: &SizingContext) -> f32 {
    match self {
      Self::Auto => 0.0,
      Self::Length(length) => length.to_px(sizing, sizing.font_size),
    }
  }
}

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

impl Animatable for TextUnderlineOffset {
  fn interpolate(
    &mut self,
    from: &Self,
    to: &Self,
    progress: f32,
    sizing: &SizingContext,
    current_color: Color,
  ) {
    *self = match (*from, *to) {
      (TextUnderlineOffset::Length(from), TextUnderlineOffset::Length(to)) => {
        let mut value = from;
        value.interpolate(&from, &to, progress, sizing, current_color);
        TextUnderlineOffset::Length(value)
      }
      _ if progress >= 0.5 => *to,
      _ => *from,
    };
  }
}

impl<'i> FromCss<'i> for TextUnderlineOffset {
  fn from_css(input: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    if input
      .try_parse(|input| input.expect_ident_matching("auto"))
      .is_ok()
    {
      return Ok(Self::Auto);
    }

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

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

impl ToCss for TextUnderlineOffset {
  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
    match self {
      Self::Auto => dest.write_str("auto"),
      Self::Length(length) => length.to_css(dest),
    }
  }
}

/// Represents text decoration style options (currently only solid is supported).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub enum TextDecorationStyle {
  /// Solid text decoration style.
  #[default]
  Solid,
}

declare_enum_from_css_impl!(
  TextDecorationStyle,
  "solid" => Self::Solid
);

/// Parsed `text-decoration` value.
#[derive(Debug, Default, Clone, PartialEq, TypedBuilder)]
#[builder(field_defaults(default))]
#[non_exhaustive]
pub struct TextDecoration {
  /// Text decoration line style.
  pub line: TextDecorationLines,
  /// Text decoration style (currently only solid is supported).
  pub style: TextDecorationStyle,
  /// Optional text decoration color.
  pub color: ColorInput,
  /// Optional text decoration thickness.
  pub thickness: TextDecorationThickness,
}

impl MakeComputed for TextDecoration {
  fn make_computed(&mut self, sizing: &SizingContext) {
    self.color.make_computed(sizing);
    self.thickness.make_computed(sizing);
  }
}

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

    loop {
      if let Ok(value) = input.try_parse(TextDecorationLines::from_css) {
        line |= value;
        continue;
      }

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

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

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

      if input.is_exhausted() {
        break;
      }

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

    Ok(TextDecoration {
      line,
      style: style.unwrap_or_default(),
      color: color.unwrap_or_default(),
      thickness: thickness.unwrap_or_default(),
    })
  }

  const VALID_TOKENS: &'static [CssToken] = &[
    CssToken::Keyword("underline"),
    CssToken::Keyword("line-through"),
    CssToken::Keyword("overline"),
    CssToken::Keyword("solid"),
    CssToken::Keyword("from-font"),
    CssToken::Syntax(CssSyntaxKind::Color),
    CssToken::Syntax(CssSyntaxKind::Length),
    CssToken::Syntax(CssSyntaxKind::Percentage),
  ];
}

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

  #[test]
  fn test_parse_text_decoration_underline() {
    assert_eq!(
      TextDecoration::from_str("underline"),
      Ok(
        TextDecoration::builder()
          .line(TextDecorationLines::UNDERLINE)
          .build()
      )
    );
  }

  #[test]
  fn test_parse_text_decoration_line_through() {
    assert_eq!(
      TextDecoration::from_str("line-through"),
      Ok(
        TextDecoration::builder()
          .line(TextDecorationLines::LINE_THROUGH)
          .build()
      )
    );
  }

  #[test]
  fn test_parse_text_decoration_underline_solid() {
    assert_eq!(
      TextDecoration::from_str("underline solid"),
      Ok(
        TextDecoration::builder()
          .line(TextDecorationLines::UNDERLINE)
          .style(TextDecorationStyle::Solid)
          .build()
      )
    );
  }

  #[test]
  fn test_parse_text_decoration_line_through_solid_red() {
    assert_eq!(
      TextDecoration::from_str("line-through solid red"),
      Ok(
        TextDecoration::builder()
          .line(TextDecorationLines::LINE_THROUGH)
          .style(TextDecorationStyle::Solid)
          .color(ColorInput::Value(Color([255, 0, 0, 255])))
          .build()
      )
    );
  }

  #[test]
  fn test_parse_text_decoration_multiple_lines() {
    assert_eq!(
      TextDecoration::from_str("underline line-through solid red"),
      Ok(
        TextDecoration::builder()
          .line(TextDecorationLines::UNDERLINE | TextDecorationLines::LINE_THROUGH)
          .style(TextDecorationStyle::Solid)
          .color(ColorInput::Value(Color([255, 0, 0, 255])))
          .build()
      )
    );
  }

  #[test]
  fn test_parse_text_decoration_invalid() {
    let result = TextDecoration::from_str("invalid");
    assert!(result.is_err());
  }

  #[test]
  fn test_parse_text_underline_offset_auto() {
    assert_eq!(
      TextUnderlineOffset::from_str("auto"),
      Ok(TextUnderlineOffset::Auto)
    );
  }

  #[test]
  fn test_parse_text_underline_offset_length() {
    assert_eq!(
      TextUnderlineOffset::from_str("3px"),
      Ok(TextUnderlineOffset::Length(Length::Px(3.0)))
    );
  }

  #[test]
  fn test_parse_text_underline_offset_invalid() {
    assert!(TextUnderlineOffset::from_str("solid").is_err());
  }
}