Skip to main content

takumi_core/style/properties/
linear_gradient.rs

1use std::{
2  fmt,
3  ops::{Deref, Neg},
4};
5
6use cssparser::{Parser, Token};
7use smallvec::SmallVec;
8use tiny_skia::PremultipliedColorU8;
9use typed_builder::TypedBuilder;
10
11use super::gradient_utils::{
12  ColorLut, GradientOverlayTile, LutAxis, gradient_tile_accessors, half_pixel_samples,
13  parse_gradient_function, parse_gradient_stops, write_gradient_css,
14};
15use crate::geometry::Size;
16use crate::style::{
17  Animatable, Color, ColorInput, ColorInterpolationMethod, FromCss, Length, MakeComputed,
18  ParseResult, SizingContext, ToCss, impl_css_enum, is_math_function, parse_angle,
19  tw::TailwindPropertyParser, unexpected_token,
20};
21
22/// Represents a linear gradient.
23#[derive(Debug, Clone, PartialEq, TypedBuilder)]
24#[non_exhaustive]
25pub struct LinearGradient {
26  /// Whether the gradient repeats beyond the last stop.
27  #[builder(default)]
28  pub repeating: bool,
29  /// The gradient direction.
30  #[builder(default)]
31  pub direction: LinearGradientDirection,
32  /// The color interpolation method used between stops.
33  #[builder(default = ColorInterpolationMethod::LEGACY)]
34  pub interpolation: ColorInterpolationMethod,
35  /// The steps of the gradient.
36  #[builder(setter(into))]
37  pub stops: Box<[GradientStop]>,
38}
39
40impl MakeComputed for LinearGradient {
41  fn make_computed(&mut self, sizing: &SizingContext) {
42    self.stops.make_computed(sizing);
43  }
44}
45
46/// Resolved geometry and stops shared by gradient renderers.
47pub struct LinearGradientGeometry {
48  /// Direction vector X component.
49  pub dir_x: f32,
50  /// Direction vector Y component.
51  pub dir_y: f32,
52  /// Full axis length in pixels.
53  pub axis_length: f32,
54  /// Projection offset for the gradient axis.
55  projection_bias: f32,
56  stops: SmallVec<[ResolvedGradientStop; 4]>,
57}
58
59impl LinearGradient {
60  fn direction_components(&self, width: f32, height: f32) -> (f32, f32) {
61    let angle = match self.direction {
62      LinearGradientDirection::Angle(angle) => angle,
63      LinearGradientDirection::Keyword(keyword_direction) => {
64        if let (Some(horizontal), Some(vertical)) =
65          (keyword_direction.horizontal, keyword_direction.vertical)
66        {
67          let dir_x = match horizontal {
68            HorizontalKeyword::Left => -height,
69            HorizontalKeyword::Right => height,
70          };
71          let dir_y = match vertical {
72            VerticalKeyword::Top => -width,
73            VerticalKeyword::Bottom => width,
74          };
75          let magnitude = dir_x.hypot(dir_y);
76
77          if magnitude > f32::EPSILON {
78            return (dir_x / magnitude, dir_y / magnitude);
79          }
80        }
81
82        keyword_direction.to_angle()
83      }
84    };
85    let degrees = angle.0.rem_euclid(360.0);
86
87    // Blink's `EndPointsFromAngle` takes the four axis angles exactly.
88    if degrees == 0.0 {
89      (0.0, -1.0)
90    } else if degrees == 90.0 {
91      (1.0, 0.0)
92    } else if degrees == 180.0 {
93      (0.0, 1.0)
94    } else if degrees == 270.0 {
95      (-1.0, 0.0)
96    } else {
97      let rad = degrees.to_radians();
98
99      (rad.sin(), -rad.cos())
100    }
101  }
102
103  /// Resolves the geometry and stops for a target viewport.
104  pub fn resolve_geometry(
105    &self,
106    width: f32,
107    height: f32,
108    sizing: &SizingContext,
109    current_color: Color,
110  ) -> LinearGradientGeometry {
111    let (dir_x, dir_y) = self.direction_components(width, height);
112    let cx = width / 2.0;
113    let cy = height / 2.0;
114    let max_extent = ((width * dir_x.abs()) + (height * dir_y.abs())) / 2.0;
115    let axis_length = 2.0 * max_extent;
116
117    LinearGradientGeometry {
118      dir_x,
119      dir_y,
120      axis_length,
121      projection_bias: max_extent - cx * dir_x - cy * dir_y,
122      stops: ResolvedGradientStop::resolve(
123        &self.stops,
124        axis_length.max(1e-6),
125        sizing,
126        current_color,
127      ),
128    }
129  }
130}
131
132impl LinearGradientGeometry {
133  /// Resolved stops in axis pixels.
134  pub fn stops(&self) -> &[ResolvedGradientStop] {
135    &self.stops
136  }
137
138  /// Mutable resolved stops for backend color filtering.
139  pub fn stops_mut(&mut self) -> &mut [ResolvedGradientStop] {
140    &mut self.stops
141  }
142}
143
144/// Precomputed drawing context for repeated sampling of a `LinearGradient`.
145#[derive(Debug, Clone)]
146pub struct LinearGradientTile {
147  /// Target width in pixels.
148  pub width: u32,
149  /// Target height in pixels.
150  pub height: u32,
151  /// Direction vector X component derived from angle.
152  pub dir_x: f32,
153  /// Direction vector Y component derived from angle.
154  pub dir_y: f32,
155  /// Full axis length along gradient direction in pixels.
156  pub axis_length: f32,
157  /// Whether this gradient repeats.
158  pub repeating: bool,
159  /// First resolved stop position in pixels, used as repeating origin.
160  pub repeat_start: f32,
161  /// Repeat period in pixels.
162  pub repeat_period: f32,
163  /// Projection bias for `x * dir_x + y * dir_y + projection_bias`.
164  pub projection_bias: f32,
165  /// Scale converting axis-space position in pixels into LUT index space.
166  pub position_to_lut_scale: f32,
167  /// Whether every sampled pixel in this gradient is fully opaque.
168  pub fully_opaque: bool,
169  /// Pre-computed colour samples along the axis.
170  pub lut: ColorLut,
171  /// Precomputed axis samples for fast horizontal/vertical fills.
172  pub axis_aligned_fast_path: Option<LinearGradientFastPathData>,
173}
174
175/// Per-row sampling state for incremental projection stepping.
176#[derive(Debug, Clone, Copy)]
177pub struct LinearGradientRowState {
178  projection: f32,
179  projection_step: f32,
180  max_lut_index: usize,
181}
182
183/// Axis-aligned fast-path orientation.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum LinearGradientFastPathKind {
186  /// Left-to-right gradient.
187  Horizontal,
188  /// Top-to-bottom gradient.
189  Vertical,
190}
191
192/// Owned axis samples for an axis-aligned gradient.
193#[derive(Debug, Clone)]
194pub struct LinearGradientFastPathData {
195  /// Fast-path orientation.
196  pub kind: LinearGradientFastPathKind,
197  /// Axis samples, laid out as documented on the struct.
198  pub axis_samples: Box<[PremultipliedColorU8]>,
199  /// Whether the samples carry dither noise (and use the dithered layout).
200  pub dithered: bool,
201}
202
203/// Borrowed view of axis samples for an axis-aligned gradient.
204#[derive(Debug, Clone, Copy)]
205pub struct LinearGradientFastPath<'a> {
206  /// Fast-path orientation.
207  pub kind: LinearGradientFastPathKind,
208  /// Axis samples, laid out as documented on [`LinearGradientFastPathData`].
209  pub axis_samples: &'a [PremultipliedColorU8],
210  /// Whether the samples carry dither noise (and use the dithered layout).
211  pub dithered: bool,
212  /// Whether every sample is fully opaque.
213  pub fully_opaque: bool,
214}
215
216impl LinearGradientTile {
217  const AXIS_ALIGNMENT_EPSILON: f32 = 1e-4;
218
219  /// Projects a pixel onto the gradient axis, in pixels.
220  #[inline(always)]
221  pub(crate) fn projection_at(&self, x: f32, y: f32) -> f32 {
222    x * self.dir_x + y * self.dir_y + self.projection_bias
223  }
224
225  #[inline(always)]
226  fn pixel_lut_index(&self, x: u32, y: u32) -> usize {
227    self.point_index(x as f32 + 0.5, y as f32 + 0.5)
228  }
229
230  #[inline(always)]
231  fn point_index(&self, x: f32, y: f32) -> usize {
232    let projection = self.projection_at(x, y);
233    if self.repeating && self.repeat_period > 1e-6 {
234      let wrapped = (projection - self.repeat_start).rem_euclid(self.repeat_period);
235      ((wrapped * self.position_to_lut_scale).round() as usize).min(self.lut.len() - 1)
236    } else {
237      self.lut_index_for_projection_with_len(projection, self.lut.len())
238    }
239  }
240
241  /// Maps an axis projection to a LUT index for a LUT of `lut_len`.
242  #[inline(always)]
243  pub(crate) fn lut_index_for_projection_with_len(&self, projection: f32, lut_len: usize) -> usize {
244    if lut_len <= 1 {
245      return 0;
246    }
247
248    let position_px = projection.clamp(0.0, self.axis_length);
249    ((position_px * self.position_to_lut_scale).round() as usize).min(lut_len - 1)
250  }
251
252  fn classify_axis_aligned(dir_x: f32, dir_y: f32) -> Option<LinearGradientFastPathKind> {
253    if dir_y.abs() <= Self::AXIS_ALIGNMENT_EPSILON
254      && (dir_x.abs() - 1.0).abs() <= Self::AXIS_ALIGNMENT_EPSILON
255    {
256      return Some(LinearGradientFastPathKind::Horizontal);
257    }
258
259    if dir_x.abs() <= Self::AXIS_ALIGNMENT_EPSILON
260      && (dir_y.abs() - 1.0).abs() <= Self::AXIS_ALIGNMENT_EPSILON
261    {
262      return Some(LinearGradientFastPathKind::Vertical);
263    }
264
265    None
266  }
267
268  fn build_axis_samples(&self, kind: LinearGradientFastPathKind) -> Box<[PremultipliedColorU8]> {
269    // An axis-aligned projection ignores the cross axis, so sampling the
270    // dithered variants at small cross coordinates hits every noise phase.
271    match (kind, self.lut.dither_active()) {
272      (LinearGradientFastPathKind::Horizontal, false) => {
273        (0..self.width).map(|x| self.sample_pixel(x, 0)).collect()
274      }
275      (LinearGradientFastPathKind::Vertical, false) => {
276        (0..self.height).map(|y| self.sample_pixel(0, y)).collect()
277      }
278      (LinearGradientFastPathKind::Horizontal, true) => (0..8u32)
279        .flat_map(|y| (0..self.width).map(move |x| (x, y)))
280        .map(|(x, y)| self.sample_pixel_dithered(x, y))
281        .collect(),
282      (LinearGradientFastPathKind::Vertical, true) => (0..self.height)
283        .flat_map(|y| (0..8u32).map(move |x| (x, y)))
284        .map(|(x, y)| self.sample_pixel_dithered(x, y))
285        .collect(),
286    }
287  }
288
289  /// Borrowed axis-aligned fast path, if this gradient has one.
290  pub fn fast_path(&self) -> Option<LinearGradientFastPath<'_>> {
291    let fast_path = self.axis_aligned_fast_path.as_ref()?;
292    Some(LinearGradientFastPath {
293      kind: fast_path.kind,
294      axis_samples: &fast_path.axis_samples,
295      dithered: fast_path.dithered,
296      fully_opaque: self.fully_opaque,
297    })
298  }
299
300  /// Builds a drawing context from a gradient and a target viewport.
301  pub fn new(
302    gradient: &LinearGradient,
303    width: u32,
304    height: u32,
305    sizing: &SizingContext,
306    current_color: Color,
307    dither: bool,
308  ) -> Self {
309    Self::sized(
310      gradient,
311      Size {
312        width: width as f32,
313        height: height as f32,
314      },
315      sizing,
316      current_color,
317      dither,
318    )
319  }
320
321  /// Builds a drawing context from a gradient over a tile of `size`, its pixel grid covering it.
322  pub fn sized(
323    gradient: &LinearGradient,
324    size: Size<f32>,
325    sizing: &SizingContext,
326    current_color: Color,
327    dither: bool,
328  ) -> Self {
329    let (width, height) = (size.width.ceil() as u32, size.height.ceil() as u32);
330    let geometry = gradient.resolve_geometry(size.width, size.height, sizing, current_color);
331    let (dir_x, dir_y) = (geometry.dir_x, geometry.dir_y);
332    let axis_aligned_kind = Self::classify_axis_aligned(dir_x, dir_y);
333    let axis = LutAxis::new(gradient.repeating, geometry.stops, geometry.axis_length);
334    let lut_size = match axis_aligned_kind {
335      Some(LinearGradientFastPathKind::Horizontal) => {
336        axis.lut_size_covering(half_pixel_samples(width as usize))
337      }
338      Some(LinearGradientFastPathKind::Vertical) => {
339        axis.lut_size_covering(half_pixel_samples(height as usize))
340      }
341      None => axis.lut_size(),
342    };
343    let lut = axis.lut(lut_size, gradient.interpolation, dither);
344    let lut_len = lut.len();
345    let position_to_lut_scale = axis.position_to_lut_scale(lut_len);
346    let fully_opaque = axis.stops.iter().all(|stop| stop.color.0[3] == u8::MAX);
347
348    let mut tile = LinearGradientTile {
349      width,
350      height,
351      dir_x,
352      dir_y,
353      axis_length: geometry.axis_length,
354      repeating: axis.repeating,
355      repeat_start: axis.repeat_start,
356      repeat_period: axis.repeat_period,
357      projection_bias: geometry.projection_bias,
358      position_to_lut_scale,
359      fully_opaque,
360      lut,
361      axis_aligned_fast_path: None,
362    };
363
364    if !tile.repeating
365      && let Some(kind) = axis_aligned_kind
366    {
367      tile.axis_aligned_fast_path = Some(LinearGradientFastPathData {
368        kind,
369        axis_samples: tile.build_axis_samples(kind),
370        dithered: tile.lut.dither_active(),
371      });
372    }
373
374    tile
375  }
376}
377
378impl GradientOverlayTile for LinearGradientTile {
379  type RowState = LinearGradientRowState;
380
381  gradient_tile_accessors!();
382
383  #[inline(always)]
384  fn point_lut_index(&self, x: f32, y: f32) -> usize {
385    self.point_index(x, y)
386  }
387
388  #[inline(always)]
389  fn sample_pixel(&self, x: u32, y: u32) -> PremultipliedColorU8 {
390    match self.lut.len() {
391      0 => PremultipliedColorU8::TRANSPARENT,
392      1 => self.lut.sample(0),
393      _ => self.lut.sample(self.pixel_lut_index(x, y)),
394    }
395  }
396
397  #[inline(always)]
398  fn sample_pixel_dithered(&self, x: u32, y: u32) -> PremultipliedColorU8 {
399    if !self.lut.dither_active() {
400      return self.sample_pixel(x, y);
401    }
402
403    self.lut.sample_dithered(self.pixel_lut_index(x, y), x, y)
404  }
405
406  #[inline(always)]
407  fn begin_row(&self, src_x_start: u32, src_y: u32, lut_len: usize) -> Self::RowState {
408    let projection = self.projection_at(src_x_start as f32 + 0.5, src_y as f32 + 0.5);
409    LinearGradientRowState {
410      projection,
411      projection_step: self.dir_x,
412      max_lut_index: lut_len.saturating_sub(1),
413    }
414  }
415
416  #[inline(always)]
417  fn next_lut_index(&self, row_state: &mut Self::RowState) -> usize {
418    let lut_idx = if self.repeating && self.repeat_period > 1e-6 {
419      let wrapped = (row_state.projection - self.repeat_start).rem_euclid(self.repeat_period);
420      ((wrapped * self.position_to_lut_scale).round() as usize).min(row_state.max_lut_index)
421    } else {
422      let position_px = row_state.projection.clamp(0.0, self.axis_length);
423      ((position_px * self.position_to_lut_scale).round() as usize).min(row_state.max_lut_index)
424    };
425
426    row_state.projection += row_state.projection_step;
427    lut_idx
428  }
429}
430
431/// Represents a gradient stop position.
432#[derive(Debug, Clone, Copy, PartialEq)]
433pub struct StopPosition(pub Length);
434
435impl MakeComputed for StopPosition {
436  fn make_computed(&mut self, sizing: &SizingContext) {
437    self.0.make_computed(sizing);
438  }
439}
440
441/// Represents a gradient stop.
442#[derive(Debug, Clone, PartialEq)]
443#[non_exhaustive]
444pub enum GradientStop {
445  /// A color gradient stop.
446  ColorHint {
447    /// The color of the gradient stop.
448    color: ColorInput,
449    /// The position of the gradient stop.
450    hint: Option<StopPosition>,
451  },
452  /// A numeric gradient stop.
453  Hint(StopPosition),
454}
455
456impl MakeComputed for GradientStop {
457  fn make_computed(&mut self, sizing: &SizingContext) {
458    match self {
459      GradientStop::ColorHint { hint, .. } => hint.make_computed(sizing),
460      GradientStop::Hint(hint) => hint.make_computed(sizing),
461    }
462  }
463}
464
465/// Represents a resolved gradient stop with a position.
466#[derive(Debug, Clone, PartialEq)]
467#[non_exhaustive]
468pub struct ResolvedGradientStop {
469  /// The color of the gradient stop.
470  pub color: Color,
471  /// The position of the gradient stop in pixels from the start of the axis.
472  pub position: f32,
473}
474
475impl<'i> FromCss<'i> for StopPosition {
476  fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, StopPosition> {
477    if let Ok(num) = input.try_parse(Parser::expect_number) {
478      return Ok(StopPosition(Length::Percentage(
479        num.clamp(0.0, 1.0) * 100.0,
480      )));
481    }
482
483    if let Ok(unit_value) = input.try_parse(Parser::expect_percentage) {
484      return Ok(StopPosition(Length::Percentage(unit_value * 100.0)));
485    }
486
487    let Ok(length) = input.try_parse(Length::from_css) else {
488      return Err(unexpected_token!(input.next()?,));
489    };
490
491    Ok(StopPosition(length))
492  }
493
494  const VALID_TOKENS: &'static [&'static str] = Length::VALID_TOKENS;
495}
496
497impl<'i> FromCss<'i> for GradientStop {
498  /// Parses a gradient hint from the input.
499  fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, GradientStop> {
500    if let Ok(hint) = input.try_parse(StopPosition::from_css) {
501      return Ok(GradientStop::Hint(hint));
502    };
503
504    let color = ColorInput::from_css(input)?;
505    let hint = input.try_parse(StopPosition::from_css).ok();
506
507    Ok(GradientStop::ColorHint { color, hint })
508  }
509
510  const VALID_TOKENS: &'static [&'static str] = &["<color>", "<length>"];
511}
512
513/// Represents an angle value in degrees.
514#[derive(Debug, Default, Clone, Copy, PartialEq)]
515pub struct Angle(f32);
516
517impl MakeComputed for Angle {}
518
519impl ToCss for Angle {
520  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
521    write!(dest, "{degrees}deg", degrees = self.0)
522  }
523}
524
525impl Animatable for Angle {
526  fn missing_value() -> Option<Self> {
527    Some(Angle::zero())
528  }
529
530  fn interpolate(
531    &mut self,
532    from: &Self,
533    to: &Self,
534    progress: f32,
535    _sizing: &SizingContext,
536    _current_color: Color,
537  ) {
538    let from_degrees = **from;
539    let to_degrees = **to;
540    let delta = (to_degrees - from_degrees + 180.0).rem_euclid(360.0) - 180.0;
541    *self = Angle::new(from_degrees + delta * progress);
542  }
543}
544
545impl TailwindPropertyParser for Angle {
546  fn parse_tw(token: &str) -> Option<Self> {
547    match token.to_ascii_lowercase().as_str() {
548      "none" => return Some(Angle::zero()),
549      "to-t" => return Some(Angle::new(0.0)),
550      "to-tr" => return Some(Angle::new(45.0)),
551      "to-r" => return Some(Angle::new(90.0)),
552      "to-br" => return Some(Angle::new(135.0)),
553      "to-b" => return Some(Angle::new(180.0)),
554      "to-bl" => return Some(Angle::new(225.0)),
555      "to-l" => return Some(Angle::new(270.0)),
556      "to-tl" => return Some(Angle::new(315.0)),
557      _ => {}
558    }
559
560    let angle = token.parse::<f32>().ok()?;
561
562    Some(Angle::new(angle))
563  }
564}
565
566impl Neg for Angle {
567  type Output = Self;
568
569  fn neg(self) -> Self::Output {
570    Angle::new(-self.0)
571  }
572}
573
574impl Deref for Angle {
575  type Target = f32;
576  fn deref(&self) -> &Self::Target {
577    &self.0
578  }
579}
580
581impl Angle {
582  /// Returns a zero angle.
583  pub const fn zero() -> Self {
584    Angle(0.0)
585  }
586
587  /// Creates a new angle value, normalizing it to the range [0, 360).
588  pub fn new(value: f32) -> Self {
589    Angle(value.rem_euclid(360.0))
590  }
591}
592
593/// Represents a horizontal keyword.
594#[derive(Debug, Clone, Copy, PartialEq)]
595#[non_exhaustive]
596pub enum HorizontalKeyword {
597  /// The left keyword.
598  Left,
599  /// The right keyword.
600  Right,
601}
602
603/// Represents a vertical keyword.
604#[derive(Debug, Clone, Copy, PartialEq)]
605#[non_exhaustive]
606pub enum VerticalKeyword {
607  /// The top keyword.
608  Top,
609  /// The bottom keyword.
610  Bottom,
611}
612
613impl_css_enum!(
614  HorizontalKeyword,
615  "left" => HorizontalKeyword::Left,
616  "right" => HorizontalKeyword::Right,
617);
618
619impl_css_enum!(
620  VerticalKeyword,
621  "top" => VerticalKeyword::Top,
622  "bottom" => VerticalKeyword::Bottom,
623);
624
625/// The original `to <side-or-corner>` direction parsed from CSS.
626#[derive(Debug, Clone, Copy, PartialEq)]
627pub struct GradientKeywordDirection {
628  /// Horizontal keyword, if one was provided.
629  pub horizontal: Option<HorizontalKeyword>,
630  /// Vertical keyword, if one was provided.
631  pub vertical: Option<VerticalKeyword>,
632}
633
634/// The direction of a linear gradient.
635#[derive(Debug, Clone, Copy, PartialEq)]
636pub enum LinearGradientDirection {
637  /// An explicit numeric angle.
638  Angle(Angle),
639  /// A box-relative side-or-corner direction.
640  Keyword(GradientKeywordDirection),
641}
642
643impl Default for LinearGradientDirection {
644  fn default() -> Self {
645    Self::Angle(Angle::new(180.0))
646  }
647}
648
649impl HorizontalKeyword {
650  /// Returns the angle in degrees.
651  pub(crate) fn degrees(&self) -> f32 {
652    match self {
653      HorizontalKeyword::Left => 270.0,
654      HorizontalKeyword::Right => 90.0,
655    }
656  }
657
658  /// Returns the mixed angle in degrees.
659  pub(crate) fn vertical_mixed_degrees(&self) -> f32 {
660    match self {
661      HorizontalKeyword::Left => -45.0,
662      HorizontalKeyword::Right => 45.0,
663    }
664  }
665}
666
667impl VerticalKeyword {
668  /// Returns the angle in degrees.
669  pub(crate) fn degrees(&self) -> f32 {
670    match self {
671      VerticalKeyword::Top => 0.0,
672      VerticalKeyword::Bottom => 180.0,
673    }
674  }
675}
676
677impl GradientKeywordDirection {
678  /// Converts a side-or-corner direction into the matching CSS angle.
679  pub(crate) fn to_angle(self) -> Angle {
680    match (self.horizontal, self.vertical) {
681      (None, None) => Angle::new(180.0),
682      (Some(horizontal), None) => Angle::new(horizontal.degrees()),
683      (None, Some(vertical)) => Angle::new(vertical.degrees()),
684      (Some(horizontal), Some(VerticalKeyword::Top)) => {
685        Angle::new(horizontal.vertical_mixed_degrees())
686      }
687      (Some(horizontal), Some(VerticalKeyword::Bottom)) => {
688        Angle::new(180.0 - horizontal.vertical_mixed_degrees())
689      }
690    }
691  }
692}
693
694impl<'i> FromCss<'i> for GradientKeywordDirection {
695  fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, Self> {
696    input.expect_ident_matching("to")?;
697
698    if let Ok(vertical) = input.try_parse(VerticalKeyword::from_css) {
699      if let Ok(horizontal) = input.try_parse(HorizontalKeyword::from_css) {
700        return Ok(Self {
701          horizontal: Some(horizontal),
702          vertical: Some(vertical),
703        });
704      }
705
706      return Ok(Self {
707        horizontal: None,
708        vertical: Some(vertical),
709      });
710    }
711
712    if let Ok(horizontal) = input.try_parse(HorizontalKeyword::from_css) {
713      return Ok(Self {
714        horizontal: Some(horizontal),
715        vertical: None,
716      });
717    }
718
719    Err(input.new_error_for_next_token())
720  }
721
722  const VALID_TOKENS: &'static [&'static str] = &["to", "top", "bottom", "left", "right"];
723}
724
725impl<'i> FromCss<'i> for LinearGradientDirection {
726  fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, Self> {
727    if let Ok(direction) = input.try_parse(GradientKeywordDirection::from_css) {
728      return Ok(Self::Keyword(direction));
729    }
730
731    Angle::from_css(input).map(Self::Angle)
732  }
733
734  const VALID_TOKENS: &'static [&'static str] = Angle::VALID_TOKENS;
735}
736
737impl LinearGradient {
738  const FUNCTION_NAMES: [&'static str; 2] = ["linear-gradient", "repeating-linear-gradient"];
739}
740
741impl<'i> FromCss<'i> for LinearGradient {
742  fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, LinearGradient> {
743    let repeating = parse_gradient_function::<Self>(input, Self::FUNCTION_NAMES)?;
744
745    input.parse_nested_block(|input| {
746      let mut direction = LinearGradientDirection::default();
747      let mut interpolation = None;
748      let mut saw_direction = false;
749
750      loop {
751        if let Ok(parsed_direction) = input.try_parse(LinearGradientDirection::from_css) {
752          if saw_direction {
753            return Err(input.new_error_for_next_token());
754          }
755
756          direction = parsed_direction;
757          saw_direction = true;
758          continue;
759        }
760
761        if let Ok(parsed_interpolation) = input.try_parse(ColorInterpolationMethod::from_css) {
762          interpolation = Some(parsed_interpolation);
763          continue;
764        }
765
766        break;
767      }
768
769      input.try_parse(Parser::expect_comma).ok();
770
771      let (stops, modern) = parse_gradient_stops(input, StopPosition::from_css)?;
772
773      Ok(LinearGradient {
774        repeating,
775        direction,
776        interpolation: interpolation.unwrap_or(ColorInterpolationMethod::gradient_default(modern)),
777        stops: stops.into_boxed_slice(),
778      })
779    })
780  }
781
782  const VALID_TOKENS: &'static [&'static str] = &["<linear-gradient()>"];
783}
784
785impl<'i> FromCss<'i> for Angle {
786  fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, Angle> {
787    if input
788      .try_parse(|input| input.expect_ident_matching("none"))
789      .is_ok()
790    {
791      return Ok(Angle::zero());
792    }
793
794    let token = input.next()?;
795
796    match token {
797      Token::Function(function) if is_math_function(function) => {
798        let function = function.clone();
799
800        parse_angle(&function, input).map(Angle::new)
801      }
802      Token::Number { value, .. } => Ok(Angle::new(*value)),
803      Token::Dimension { value, unit, .. } => match unit.as_ref() {
804        "deg" => Ok(Angle::new(*value)),
805        "grad" => Ok(Angle::new(*value / 400.0 * 360.0)),
806        "turn" => Ok(Angle::new(*value * 360.0)),
807        "rad" => Ok(Angle::new(value.to_degrees())),
808        _ => Err(unexpected_token!(token)),
809      },
810      _ => Err(unexpected_token!(token)),
811    }
812  }
813
814  const VALID_TOKENS: &'static [&'static str] = &["<angle>", "none"];
815}
816
817impl ToCss for StopPosition {
818  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
819    self.0.to_css(dest)
820  }
821}
822
823impl ToCss for GradientStop {
824  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
825    match self {
826      Self::ColorHint { color, hint } => {
827        color.to_css(dest)?;
828        if let Some(h) = hint {
829          dest.write_char(' ')?;
830          h.to_css(dest)?;
831        }
832        Ok(())
833      }
834      Self::Hint(h) => h.to_css(dest),
835    }
836  }
837}
838
839impl ToCss for GradientKeywordDirection {
840  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
841    dest.write_str("to")?;
842    if let Some(v) = self.vertical {
843      dest.write_char(' ')?;
844      v.to_css(dest)?;
845    }
846    if let Some(h) = self.horizontal {
847      dest.write_char(' ')?;
848      h.to_css(dest)?;
849    }
850    Ok(())
851  }
852}
853
854impl ToCss for LinearGradientDirection {
855  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
856    match self {
857      Self::Angle(a) => a.to_css(dest),
858      Self::Keyword(kw) => kw.to_css(dest),
859    }
860  }
861}
862
863impl ToCss for LinearGradient {
864  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
865    let name = Self::FUNCTION_NAMES[usize::from(self.repeating)];
866
867    let mut dir_buf = String::new();
868    self.direction.to_css(&mut dir_buf)?;
869    if dir_buf == "180deg" || dir_buf == "to bottom" {
870      dir_buf.clear();
871    }
872
873    write_gradient_css(dest, name, &dir_buf, &self.interpolation, &self.stops)
874  }
875}
876
877#[cfg(test)]
878mod tests {
879
880  use color::{ColorSpaceTag, HueDirection};
881  use tiny_skia::ColorU8;
882
883  use super::*;
884  use crate::{
885    geometry::Size,
886    style::{FromCssStr, properties::gradient_utils::red_blue_stops},
887    viewport::Viewport,
888  };
889  fn sizing() -> SizingContext {
890    SizingContext {
891      viewport: Viewport::new((200, 100)),
892      container_size: Size::NONE,
893      container_read: Default::default(),
894      font_read: None,
895      font_size: 16.0,
896      root_font_size: None,
897      line_height: 0.0,
898      root_line_height: None,
899      ch: 16.0 / 2.0,
900      ex: 16.0 / 2.0,
901    }
902  }
903
904  #[test]
905  fn test_parse_linear_gradient() {
906    assert_eq!(
907      LinearGradient::from_css_str("linear-gradient(to top right, #ff0000, #0000ff)"),
908      Ok(LinearGradient {
909        repeating: false,
910        direction: LinearGradientDirection::Keyword(GradientKeywordDirection {
911          horizontal: Some(HorizontalKeyword::Right),
912          vertical: Some(VerticalKeyword::Top),
913        }),
914        interpolation: ColorInterpolationMethod::LEGACY,
915        stops: red_blue_stops(None, None).into(),
916      })
917    )
918  }
919
920  #[test]
921  fn test_parse_angle() {
922    for (input, expected) in [
923      ("45deg", Angle::new(45.0)),
924      ("200grad", Angle::new(180.0)),
925      ("0.5turn", Angle::new(180.0)),
926      ("90", Angle::new(90.0)),
927    ] {
928      assert_eq!(Angle::from_css_str(input), Ok(expected), "input: {input}");
929    }
930    // rad requires approximate comparison
931    assert!(Angle::from_css_str("3.14159rad").is_ok_and(|a| (a.0 - 180.0).abs() < 0.001));
932  }
933
934  #[test]
935  fn test_parse_direction_keywords() {
936    use HorizontalKeyword::{Left, Right};
937    use VerticalKeyword::{Bottom, Top};
938    for (input, expected) in [
939      (
940        "to top",
941        GradientKeywordDirection {
942          horizontal: None,
943          vertical: Some(Top),
944        },
945      ),
946      (
947        "to right",
948        GradientKeywordDirection {
949          horizontal: Some(Right),
950          vertical: None,
951        },
952      ),
953      (
954        "to bottom",
955        GradientKeywordDirection {
956          horizontal: None,
957          vertical: Some(Bottom),
958        },
959      ),
960      (
961        "to left",
962        GradientKeywordDirection {
963          horizontal: Some(Left),
964          vertical: None,
965        },
966      ),
967      (
968        "to top right",
969        GradientKeywordDirection {
970          horizontal: Some(Right),
971          vertical: Some(Top),
972        },
973      ),
974      (
975        "to bottom left",
976        GradientKeywordDirection {
977          horizontal: Some(Left),
978          vertical: Some(Bottom),
979        },
980      ),
981      (
982        "to top left",
983        GradientKeywordDirection {
984          horizontal: Some(Left),
985          vertical: Some(Top),
986        },
987      ),
988      (
989        "to bottom right",
990        GradientKeywordDirection {
991          horizontal: Some(Right),
992          vertical: Some(Bottom),
993        },
994      ),
995    ] {
996      assert_eq!(
997        GradientKeywordDirection::from_css_str(input),
998        Ok(expected),
999        "input: {input}"
1000      );
1001    }
1002  }
1003
1004  #[test]
1005  fn test_angle_interpolate_uses_shortest_path_across_zero() {
1006    let from = Angle::new(0.0);
1007    let to = Angle::new(-3.0);
1008    let mut interpolated = from;
1009
1010    interpolated.interpolate(&from, &to, 0.5, &sizing(), Color::transparent());
1011
1012    assert!((*interpolated - 358.5).abs() < 0.001);
1013  }
1014
1015  #[test]
1016  fn test_angle_interpolate_uses_shortest_path_forward_across_zero() {
1017    let from = Angle::new(-3.0);
1018    let to = Angle::new(0.0);
1019    let mut interpolated = from;
1020
1021    interpolated.interpolate(&from, &to, 0.5, &sizing(), Color::transparent());
1022
1023    assert!((*interpolated - 358.5).abs() < 0.001);
1024  }
1025
1026  #[test]
1027  fn test_parse_linear_gradient_with_angle() {
1028    assert_eq!(
1029      LinearGradient::from_css_str("linear-gradient(45deg, #ff0000, #0000ff)"),
1030      Ok(LinearGradient {
1031        repeating: false,
1032        direction: LinearGradientDirection::Angle(Angle::new(45.0)),
1033        interpolation: ColorInterpolationMethod::LEGACY,
1034        stops: red_blue_stops(None, None).into(),
1035      })
1036    )
1037  }
1038
1039  #[test]
1040  fn test_parse_linear_gradient_with_interpolation_color_space() {
1041    assert_eq!(
1042      LinearGradient::from_css_str("linear-gradient(in oklab, #ff0000, #0000ff)"),
1043      Ok(LinearGradient {
1044        repeating: false,
1045        direction: LinearGradientDirection::default(),
1046        interpolation: ColorInterpolationMethod {
1047          color_space: ColorSpaceTag::Oklab,
1048          hue_direction: HueDirection::Shorter,
1049        },
1050        stops: red_blue_stops(None, None).into(),
1051      })
1052    );
1053  }
1054
1055  #[test]
1056  fn relative_color_stops_interpolate_in_oklab() {
1057    let gradient =
1058      LinearGradient::from_css_str("linear-gradient(rgb(from red r g b), #0000ff)").unwrap();
1059
1060    assert_eq!(gradient.interpolation.color_space, ColorSpaceTag::Oklab);
1061  }
1062
1063  #[test]
1064  fn interpolation_color_space_round_trips() {
1065    // The serialized form must stay valid CSS (direction and color space in one
1066    // clause), so re-parsing keeps the interpolation instead of dropping it.
1067    let gradient =
1068      LinearGradient::from_css_str("linear-gradient(to right in oklab, #ff0000, #0000ff)").unwrap();
1069    let reparsed = LinearGradient::from_css_str(&gradient.to_css_string()).unwrap();
1070    assert_eq!(gradient, reparsed);
1071    assert_eq!(reparsed.interpolation.color_space, ColorSpaceTag::Oklab);
1072  }
1073
1074  #[test]
1075  fn test_parse_linear_gradient_with_interpolation_hue_direction() {
1076    assert_eq!(
1077      LinearGradient::from_css_str("linear-gradient(to right in oklch longer hue, red, blue)"),
1078      Ok(LinearGradient {
1079        repeating: false,
1080        direction: LinearGradientDirection::Keyword(GradientKeywordDirection {
1081          horizontal: Some(HorizontalKeyword::Right),
1082          vertical: None,
1083        }),
1084        interpolation: ColorInterpolationMethod {
1085          color_space: ColorSpaceTag::Oklch,
1086          hue_direction: HueDirection::Longer,
1087        },
1088        stops: [
1089          GradientStop::ColorHint {
1090            color: ColorInput::Value(Color::from_rgb(0xff0000)),
1091            hint: None,
1092          },
1093          GradientStop::ColorHint {
1094            color: ColorInput::Value(Color::from_rgb(0x0000ff)),
1095            hint: None,
1096          },
1097        ]
1098        .into(),
1099      })
1100    );
1101  }
1102
1103  #[test]
1104  fn test_parse_linear_gradient_rejects_multiple_directions() {
1105    assert!(LinearGradient::from_css_str("linear-gradient(to right 45deg, red, blue)").is_err());
1106    assert!(LinearGradient::from_css_str("linear-gradient(45deg to right, red, blue)").is_err());
1107  }
1108
1109  #[test]
1110  fn test_parse_linear_gradient_with_stops() {
1111    assert_eq!(
1112      LinearGradient::from_css_str("linear-gradient(to right, #ff0000 0%, #0000ff 100%)"),
1113      Ok(LinearGradient {
1114        repeating: false,
1115        direction: LinearGradientDirection::Keyword(GradientKeywordDirection {
1116          horizontal: Some(HorizontalKeyword::Right),
1117          vertical: None,
1118        }),
1119        interpolation: ColorInterpolationMethod::LEGACY,
1120        stops: red_blue_stops(
1121          Some(StopPosition(Length::Percentage(0.0))),
1122          Some(StopPosition(Length::Percentage(100.0))),
1123        )
1124        .into(),
1125      })
1126    );
1127  }
1128
1129  #[test]
1130  fn test_parse_linear_gradient_with_double_position_color_stop() {
1131    assert_eq!(
1132      LinearGradient::from_css_str("linear-gradient(to right, red 10% 20%, blue)"),
1133      Ok(LinearGradient {
1134        repeating: false,
1135        direction: LinearGradientDirection::Keyword(GradientKeywordDirection {
1136          horizontal: Some(HorizontalKeyword::Right),
1137          vertical: None,
1138        }),
1139        interpolation: ColorInterpolationMethod::LEGACY,
1140        stops: [
1141          GradientStop::ColorHint {
1142            color: ColorInput::Value(Color::from_rgb(0xff0000)),
1143            hint: Some(StopPosition(Length::Percentage(10.0))),
1144          },
1145          GradientStop::ColorHint {
1146            color: ColorInput::Value(Color::from_rgb(0xff0000)),
1147            hint: Some(StopPosition(Length::Percentage(20.0))),
1148          },
1149          GradientStop::ColorHint {
1150            color: ColorInput::Value(Color::from_rgb(0x0000ff)),
1151            hint: None,
1152          },
1153        ]
1154        .into(),
1155      })
1156    );
1157  }
1158
1159  #[test]
1160  fn test_parse_linear_gradient_with_hint() {
1161    assert_eq!(
1162      LinearGradient::from_css_str("linear-gradient(to right, #ff0000, 50%, #0000ff)"),
1163      Ok(LinearGradient {
1164        repeating: false,
1165        direction: LinearGradientDirection::Keyword(GradientKeywordDirection {
1166          horizontal: Some(HorizontalKeyword::Right),
1167          vertical: None,
1168        }),
1169        interpolation: ColorInterpolationMethod::LEGACY,
1170        stops: [
1171          GradientStop::ColorHint {
1172            color: ColorInput::Value(Color([255, 0, 0, 255])),
1173            hint: None,
1174          },
1175          GradientStop::Hint(StopPosition(Length::Percentage(50.0))),
1176          GradientStop::ColorHint {
1177            color: ColorInput::Value(Color([0, 0, 255, 255])),
1178            hint: None,
1179          },
1180        ]
1181        .into(),
1182      })
1183    );
1184  }
1185
1186  #[test]
1187  fn test_parse_linear_gradient_single_color() {
1188    assert_eq!(
1189      LinearGradient::from_css_str("linear-gradient(to bottom, #ff0000)"),
1190      Ok(LinearGradient {
1191        repeating: false,
1192        direction: LinearGradientDirection::Keyword(GradientKeywordDirection {
1193          horizontal: None,
1194          vertical: Some(VerticalKeyword::Bottom),
1195        }),
1196        interpolation: ColorInterpolationMethod::LEGACY,
1197        stops: [GradientStop::ColorHint {
1198          color: ColorInput::Value(Color([255, 0, 0, 255])),
1199          hint: None,
1200        }]
1201        .into(),
1202      })
1203    );
1204  }
1205
1206  #[test]
1207  fn test_parse_linear_gradient_default_angle() {
1208    // Default angle is 180 degrees (to bottom)
1209    assert_eq!(
1210      LinearGradient::from_css_str("linear-gradient(#ff0000, #0000ff)"),
1211      Ok(LinearGradient {
1212        repeating: false,
1213        direction: LinearGradientDirection::default(),
1214        interpolation: ColorInterpolationMethod::LEGACY,
1215        stops: [
1216          GradientStop::ColorHint {
1217            color: ColorInput::Value(Color::from_rgb(0xff0000)),
1218            hint: None,
1219          },
1220          GradientStop::ColorHint {
1221            color: ColorInput::Value(Color::from_rgb(0x0000ff)),
1222            hint: None,
1223          },
1224        ]
1225        .into(),
1226      })
1227    );
1228  }
1229
1230  #[test]
1231  fn test_keyword_direction_to_angle() {
1232    assert_eq!(
1233      GradientKeywordDirection {
1234        horizontal: None,
1235        vertical: None
1236      }
1237      .to_angle(),
1238      Angle::new(180.0)
1239    );
1240
1241    assert_eq!(
1242      GradientKeywordDirection {
1243        horizontal: Some(HorizontalKeyword::Left),
1244        vertical: None
1245      }
1246      .to_angle(),
1247      Angle::new(270.0) // "to left" = 270deg
1248    );
1249    assert_eq!(
1250      GradientKeywordDirection {
1251        horizontal: Some(HorizontalKeyword::Right),
1252        vertical: None
1253      }
1254      .to_angle(),
1255      Angle::new(90.0) // "to right" = 90deg
1256    );
1257
1258    assert_eq!(
1259      GradientKeywordDirection {
1260        horizontal: None,
1261        vertical: Some(VerticalKeyword::Top)
1262      }
1263      .to_angle(),
1264      Angle::new(0.0)
1265    );
1266    assert_eq!(
1267      GradientKeywordDirection {
1268        horizontal: None,
1269        vertical: Some(VerticalKeyword::Bottom)
1270      }
1271      .to_angle(),
1272      Angle::new(180.0)
1273    );
1274
1275    assert_eq!(
1276      GradientKeywordDirection {
1277        horizontal: Some(HorizontalKeyword::Left),
1278        vertical: Some(VerticalKeyword::Top)
1279      }
1280      .to_angle(),
1281      Angle::new(315.0)
1282    );
1283    assert_eq!(
1284      GradientKeywordDirection {
1285        horizontal: Some(HorizontalKeyword::Right),
1286        vertical: Some(VerticalKeyword::Top)
1287      }
1288      .to_angle(),
1289      Angle::new(45.0)
1290    );
1291    assert_eq!(
1292      GradientKeywordDirection {
1293        horizontal: Some(HorizontalKeyword::Left),
1294        vertical: Some(VerticalKeyword::Bottom)
1295      }
1296      .to_angle(),
1297      Angle::new(225.0)
1298    );
1299    assert_eq!(
1300      GradientKeywordDirection {
1301        horizontal: Some(HorizontalKeyword::Right),
1302        vertical: Some(VerticalKeyword::Bottom)
1303      }
1304      .to_angle(),
1305      Angle::new(135.0)
1306    );
1307  }
1308
1309  #[test]
1310  fn test_parse_linear_gradient_mixed_hints_and_colors() {
1311    assert_eq!(
1312      LinearGradient::from_css_str("linear-gradient(45deg, #ff0000, 25%, #00ff00, 75%, #0000ff)"),
1313      Ok(LinearGradient {
1314        repeating: false,
1315        direction: LinearGradientDirection::Angle(Angle::new(45.0)),
1316        interpolation: ColorInterpolationMethod::LEGACY,
1317        stops: [
1318          GradientStop::ColorHint {
1319            color: Color([255, 0, 0, 255]).into(),
1320            hint: None,
1321          },
1322          GradientStop::Hint(StopPosition(Length::Percentage(25.0))),
1323          GradientStop::ColorHint {
1324            color: Color([0, 255, 0, 255]).into(),
1325            hint: None,
1326          },
1327          GradientStop::Hint(StopPosition(Length::Percentage(75.0))),
1328          GradientStop::ColorHint {
1329            color: Color([0, 0, 255, 255]).into(),
1330            hint: None,
1331          },
1332        ]
1333        .into(),
1334      })
1335    );
1336  }
1337
1338  #[test]
1339  fn test_linear_gradient_at_simple() {
1340    let gradient = LinearGradient {
1341      repeating: false,
1342      direction: LinearGradientDirection::default(),
1343      interpolation: ColorInterpolationMethod::LEGACY,
1344      stops: red_blue_stops(
1345        Some(StopPosition(Length::Percentage(0.0))),
1346        Some(StopPosition(Length::Percentage(100.0))),
1347      )
1348      .into(),
1349    };
1350
1351    let sizing = SizingContext::builder()
1352      .viewport(Viewport::new((100, 100)))
1353      .build();
1354    let tile = LinearGradientTile::new(&gradient, 100, 100, &sizing, Color::black(), false);
1355
1356    // Pixels sample at their centres, as Skia's shaders do, so the first row is half a pixel in.
1357    let color_top = tile.sample_pixel(50, 0).demultiply();
1358    assert_eq!(color_top, ColorU8::from_rgba(254, 0, 1, 255));
1359
1360    let color_bottom = tile.sample_pixel(50, 100).demultiply();
1361    assert_eq!(color_bottom, ColorU8::from_rgba(0, 0, 255, 255));
1362
1363    let color_middle = tile.sample_pixel(50, 50).demultiply();
1364    assert_eq!(color_middle, ColorU8::from_rgba(126, 0, 129, 255));
1365  }
1366
1367  #[test]
1368  fn test_linear_gradient_at_horizontal() {
1369    let gradient = LinearGradient {
1370      repeating: false,
1371      direction: LinearGradientDirection::Angle(Angle::new(90.0)),
1372      interpolation: ColorInterpolationMethod::LEGACY,
1373      stops: red_blue_stops(
1374        Some(StopPosition(Length::Percentage(0.0))),
1375        Some(StopPosition(Length::Percentage(100.0))),
1376      )
1377      .into(),
1378    };
1379
1380    let sizing = SizingContext::builder()
1381      .viewport(Viewport::new((100, 100)))
1382      .build();
1383
1384    let tile = LinearGradientTile::new(&gradient, 100, 100, &sizing, Color::black(), false);
1385    let color_left = tile.sample_pixel(0, 50).demultiply();
1386    assert_eq!(color_left, ColorU8::from_rgba(254, 0, 1, 255));
1387
1388    let color_right = tile.sample_pixel(100, 50).demultiply();
1389    assert_eq!(color_right, ColorU8::from_rgba(0, 0, 255, 255));
1390  }
1391
1392  #[test]
1393  fn test_keyword_corner_direction_uses_aspect_ratio() {
1394    let gradient = LinearGradient {
1395      repeating: false,
1396      direction: LinearGradientDirection::Keyword(GradientKeywordDirection {
1397        horizontal: Some(HorizontalKeyword::Right),
1398        vertical: Some(VerticalKeyword::Bottom),
1399      }),
1400      interpolation: ColorInterpolationMethod::LEGACY,
1401      stops: red_blue_stops(
1402        Some(StopPosition(Length::Percentage(0.0))),
1403        Some(StopPosition(Length::Percentage(100.0))),
1404      )
1405      .into(),
1406    };
1407
1408    let sizing = SizingContext::builder()
1409      .viewport(Viewport::new((200, 100)))
1410      .build();
1411    let tile = LinearGradientTile::new(&gradient, 200, 100, &sizing, Color::black(), false);
1412
1413    assert!((tile.dir_x - 0.4472136).abs() < 0.001);
1414    assert!((tile.dir_y - 0.8944272).abs() < 0.001);
1415  }
1416
1417  #[test]
1418  fn test_linear_gradient_at_single_color() {
1419    let gradient = LinearGradient {
1420      repeating: false,
1421      direction: LinearGradientDirection::Angle(Angle::new(0.0)),
1422      interpolation: ColorInterpolationMethod::LEGACY,
1423      stops: [GradientStop::ColorHint {
1424        color: Color([255, 0, 0, 255]).into(), // Red
1425        hint: None,
1426      }]
1427      .into(),
1428    };
1429
1430    let sizing = SizingContext::builder()
1431      .viewport(Viewport::new((100, 100)))
1432      .build();
1433    let tile = LinearGradientTile::new(&gradient, 100, 100, &sizing, Color::black(), false);
1434    let color = tile.sample_pixel(50, 50).demultiply();
1435    assert_eq!(color, ColorU8::from_rgba(255, 0, 0, 255));
1436  }
1437
1438  #[test]
1439  fn test_linear_gradient_at_no_steps() {
1440    let gradient = LinearGradient {
1441      repeating: false,
1442      direction: LinearGradientDirection::Angle(Angle::new(0.0)),
1443      interpolation: ColorInterpolationMethod::LEGACY,
1444      stops: [].into(),
1445    };
1446
1447    let sizing = SizingContext::builder()
1448      .viewport(Viewport::new((100, 100)))
1449      .build();
1450    let tile = LinearGradientTile::new(&gradient, 100, 100, &sizing, Color::black(), false);
1451    let color = tile.sample_pixel(50, 50).demultiply();
1452    assert_eq!(color, ColorU8::from_rgba(0, 0, 0, 0));
1453  }
1454
1455  #[test]
1456  fn test_repeating_linear_gradient_stripes() {
1457    let gradient = LinearGradient::builder()
1458      .repeating(true)
1459      .direction(LinearGradientDirection::Angle(Angle::new(90.0)))
1460      .stops([
1461        GradientStop::ColorHint {
1462          color: Color([255, 0, 0, 255]).into(),
1463          hint: Some(StopPosition(Length::Px(0.0))),
1464        },
1465        GradientStop::ColorHint {
1466          color: Color([255, 0, 0, 255]).into(),
1467          hint: Some(StopPosition(Length::Px(5.0))),
1468        },
1469        GradientStop::ColorHint {
1470          color: Color([0, 0, 255, 255]).into(),
1471          hint: Some(StopPosition(Length::Px(5.0))),
1472        },
1473        GradientStop::ColorHint {
1474          color: Color([0, 0, 255, 255]).into(),
1475          hint: Some(StopPosition(Length::Px(10.0))),
1476        },
1477      ])
1478      .build();
1479
1480    let sizing = SizingContext::builder()
1481      .viewport(Viewport::new((40, 1)))
1482      .build();
1483    let tile = LinearGradientTile::new(&gradient, 40, 1, &sizing, Color::black(), false);
1484
1485    assert_eq!(
1486      [
1487        tile.sample_pixel(2, 0).demultiply(),
1488        tile.sample_pixel(7, 0).demultiply(),
1489        tile.sample_pixel(12, 0).demultiply(),
1490        tile.sample_pixel(17, 0).demultiply(),
1491      ],
1492      [
1493        ColorU8::from_rgba(255, 0, 0, 255),
1494        ColorU8::from_rgba(0, 0, 255, 255),
1495        ColorU8::from_rgba(255, 0, 0, 255),
1496        ColorU8::from_rgba(0, 0, 255, 255),
1497      ]
1498    );
1499  }
1500
1501  #[test]
1502  fn test_linear_gradient_px_stops_crisp_line() {
1503    let gradient =
1504      LinearGradient::from_css_str("linear-gradient(to right, grey 1px, transparent 1px)").unwrap();
1505
1506    let sizing = SizingContext::builder()
1507      .viewport(Viewport::new((40, 40)))
1508      .build();
1509    let tile = LinearGradientTile::new(&gradient, 40, 40, &sizing, Color::black(), false);
1510
1511    let c0 = tile.sample_pixel(0, 0).demultiply();
1512    assert_eq!(c0, ColorU8::from_rgba(128, 128, 128, 255));
1513
1514    let c1 = tile.sample_pixel(1, 0).demultiply();
1515    assert_eq!(c1, ColorU8::from_rgba(0, 0, 0, 0));
1516
1517    let c2 = tile.sample_pixel(40, 0).demultiply();
1518    assert_eq!(c2, ColorU8::from_rgba(0, 0, 0, 0));
1519  }
1520
1521  #[test]
1522  fn test_linear_gradient_vertical_px_stops_top_pixel() {
1523    let gradient =
1524      LinearGradient::from_css_str("linear-gradient(to bottom, grey 1px, transparent 1px)")
1525        .unwrap();
1526
1527    let sizing = SizingContext::builder()
1528      .viewport(Viewport::new((40, 40)))
1529      .build();
1530    let tile = LinearGradientTile::new(&gradient, 40, 40, &sizing, Color::black(), false);
1531
1532    // color at top-left (0, 0) should be grey (1px hard stop)
1533    assert_eq!(
1534      tile.sample_pixel(0, 0).demultiply(),
1535      ColorU8::from_rgba(128, 128, 128, 255)
1536    );
1537  }
1538
1539  #[test]
1540  fn test_stop_position_parsing() {
1541    for (input, expected) in [
1542      ("0.25", StopPosition(Length::Percentage(25.0))),
1543      ("75%", StopPosition(Length::Percentage(75.0))),
1544      ("50%", StopPosition(Length::Percentage(50.0))),
1545      ("12px", StopPosition(Length::Px(12.0))),
1546      ("8px", StopPosition(Length::Px(8.0))),
1547    ] {
1548      assert_eq!(
1549        StopPosition::from_css_str(input),
1550        Ok(expected),
1551        "input: {input}"
1552      );
1553    }
1554  }
1555
1556  #[test]
1557  fn resolve_stops_percentage_and_px_linear() {
1558    let gradient = LinearGradient::builder()
1559      .direction(LinearGradientDirection::Angle(Angle::new(0.0)))
1560      .stops([
1561        GradientStop::ColorHint {
1562          color: Color::black().into(),
1563          hint: Some(StopPosition(Length::Percentage(0.0))),
1564        },
1565        GradientStop::ColorHint {
1566          color: Color::black().into(),
1567          hint: Some(StopPosition(Length::Percentage(50.0))),
1568        },
1569        GradientStop::ColorHint {
1570          color: Color::black().into(),
1571          hint: Some(StopPosition(Length::Px(100.0))),
1572        },
1573      ])
1574      .build();
1575
1576    let sizing = SizingContext::builder()
1577      .viewport(Viewport::new((200, 100)))
1578      .build();
1579
1580    let resolved = ResolvedGradientStop::resolve(
1581      &gradient.stops,
1582      sizing.viewport.size.width.unwrap_or_default() as f32,
1583      &sizing,
1584      Color::black(),
1585    );
1586    assert_eq!(resolved.len(), 3);
1587    assert!((resolved[0].position - 0.0).abs() < 1e-3);
1588    assert!((resolved[1].position - 100.0).abs() < 1e-3);
1589    assert!((resolved[2].position - 100.0).abs() < 1e-3);
1590  }
1591
1592  #[test]
1593  fn resolve_stops_equal_positions_allowed_linear() {
1594    let gradient = LinearGradient::builder()
1595      .direction(LinearGradientDirection::Angle(Angle::new(0.0)))
1596      .stops([
1597        GradientStop::ColorHint {
1598          color: Color::black().into(),
1599          hint: Some(StopPosition(Length::Px(0.0))),
1600        },
1601        GradientStop::ColorHint {
1602          color: Color::black().into(),
1603          hint: Some(StopPosition(Length::Px(0.0))),
1604        },
1605      ])
1606      .build();
1607    let sizing = SizingContext::builder()
1608      .viewport(Viewport::new((200, 100)))
1609      .build();
1610
1611    let resolved = ResolvedGradientStop::resolve(
1612      &gradient.stops,
1613      sizing.viewport.size.width.unwrap_or_default() as f32,
1614      &sizing,
1615      Color::black(),
1616    );
1617    assert_eq!(resolved.len(), 2);
1618    assert!((resolved[0].position - 0.0).abs() < 1e-3);
1619    assert!((resolved[1].position - 0.0).abs() < 1e-3);
1620  }
1621}