1use super::angle::{Angle, AnglePercentage};
4use super::color::{ColorFallbackKind, CssColor};
5use super::length::{Length, LengthPercentage};
6use super::number::CSSNumber;
7use super::percentage::{DimensionPercentage, NumberOrPercentage, Percentage};
8use super::position::{HorizontalPositionKeyword, VerticalPositionKeyword};
9use super::position::{Position, PositionComponent};
10use crate::compat;
11use crate::error::{ParserError, PrinterError};
12use crate::macros::enum_property;
13use crate::prefixes::Feature;
14use crate::targets::{should_compile, Browsers, Targets};
15use crate::traits::{IsCompatible, Parse, ToCss, TrySign, Zero};
16use crate::values::number::NonNegative;
17use crate::vendor_prefix::VendorPrefix;
18#[cfg(feature = "visitor")]
19use crate::visitor::Visit;
20use cssparser::*;
21use std::f32::consts::PI;
22
23#[cfg(feature = "serde")]
24use crate::serialization::ValueWrapper;
25
26#[derive(Debug, Clone, PartialEq)]
28#[cfg_attr(feature = "visitor", derive(Visit))]
29#[cfg_attr(
30 feature = "serde",
31 derive(serde::Serialize, serde::Deserialize),
32 serde(tag = "type", rename_all = "kebab-case")
33)]
34#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
35#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
36pub enum Gradient {
37 Linear(LinearGradient),
39 RepeatingLinear(LinearGradient),
41 Radial(RadialGradient),
43 RepeatingRadial(RadialGradient),
45 Conic(ConicGradient),
47 RepeatingConic(ConicGradient),
49 #[cfg_attr(feature = "serde", serde(rename = "webkit-gradient"))]
51 WebKitGradient(WebKitGradient),
52}
53
54impl Gradient {
55 pub fn get_vendor_prefix(&self) -> VendorPrefix {
57 match self {
58 Gradient::Linear(LinearGradient { vendor_prefix, .. })
59 | Gradient::RepeatingLinear(LinearGradient { vendor_prefix, .. })
60 | Gradient::Radial(RadialGradient { vendor_prefix, .. })
61 | Gradient::RepeatingRadial(RadialGradient { vendor_prefix, .. }) => *vendor_prefix,
62 Gradient::WebKitGradient(_) => VendorPrefix::WebKit,
63 _ => VendorPrefix::None,
64 }
65 }
66
67 pub fn get_necessary_prefixes(&self, targets: Targets) -> VendorPrefix {
69 macro_rules! get_prefixes {
70 ($feature: ident, $prefix: expr) => {
71 targets.prefixes($prefix, Feature::$feature)
72 };
73 }
74
75 match self {
76 Gradient::Linear(linear) => get_prefixes!(LinearGradient, linear.vendor_prefix),
77 Gradient::RepeatingLinear(linear) => get_prefixes!(RepeatingLinearGradient, linear.vendor_prefix),
78 Gradient::Radial(radial) => get_prefixes!(RadialGradient, radial.vendor_prefix),
79 Gradient::RepeatingRadial(radial) => get_prefixes!(RepeatingRadialGradient, radial.vendor_prefix),
80 _ => VendorPrefix::None,
81 }
82 }
83
84 pub fn get_prefixed(&self, prefix: VendorPrefix) -> Gradient {
86 match self {
87 Gradient::Linear(linear) => {
88 let mut new_linear = linear.clone();
89 let needs_legacy_direction = linear.vendor_prefix == VendorPrefix::None && prefix != VendorPrefix::None;
90 if needs_legacy_direction {
91 new_linear.direction = convert_to_legacy_direction(&new_linear.direction);
92 }
93 new_linear.vendor_prefix = prefix;
94 Gradient::Linear(new_linear)
95 }
96 Gradient::RepeatingLinear(linear) => {
97 let mut new_linear = linear.clone();
98 let needs_legacy_direction = linear.vendor_prefix == VendorPrefix::None && prefix != VendorPrefix::None;
99 if needs_legacy_direction {
100 new_linear.direction = convert_to_legacy_direction(&new_linear.direction);
101 }
102 new_linear.vendor_prefix = prefix;
103 Gradient::RepeatingLinear(new_linear)
104 }
105 Gradient::Radial(radial) => Gradient::Radial(RadialGradient {
106 vendor_prefix: prefix,
107 ..radial.clone()
108 }),
109 Gradient::RepeatingRadial(radial) => Gradient::RepeatingRadial(RadialGradient {
110 vendor_prefix: prefix,
111 ..radial.clone()
112 }),
113 _ => self.clone(),
114 }
115 }
116
117 pub fn get_legacy_webkit(&self) -> Result<Gradient, ()> {
121 Ok(Gradient::WebKitGradient(WebKitGradient::from_standard(self)?))
122 }
123
124 pub fn get_necessary_fallbacks(&self, targets: Targets) -> ColorFallbackKind {
126 match self {
127 Gradient::Linear(LinearGradient { items, .. })
128 | Gradient::Radial(RadialGradient { items, .. })
129 | Gradient::RepeatingLinear(LinearGradient { items, .. })
130 | Gradient::RepeatingRadial(RadialGradient { items, .. }) => {
131 let mut fallbacks = ColorFallbackKind::empty();
132 for item in items {
133 fallbacks |= item.get_necessary_fallbacks(targets)
134 }
135 fallbacks
136 }
137 Gradient::Conic(ConicGradient { items, .. }) | Gradient::RepeatingConic(ConicGradient { items, .. }) => {
138 let mut fallbacks = ColorFallbackKind::empty();
139 for item in items {
140 fallbacks |= item.get_necessary_fallbacks(targets)
141 }
142 fallbacks
143 }
144 Gradient::WebKitGradient(..) => ColorFallbackKind::empty(),
145 }
146 }
147
148 pub fn get_fallback(&self, kind: ColorFallbackKind) -> Gradient {
150 match self {
151 Gradient::Linear(g) => Gradient::Linear(g.get_fallback(kind)),
152 Gradient::RepeatingLinear(g) => Gradient::RepeatingLinear(g.get_fallback(kind)),
153 Gradient::Radial(g) => Gradient::Radial(g.get_fallback(kind)),
154 Gradient::RepeatingRadial(g) => Gradient::RepeatingRadial(g.get_fallback(kind)),
155 Gradient::Conic(g) => Gradient::Conic(g.get_fallback(kind)),
156 Gradient::RepeatingConic(g) => Gradient::RepeatingConic(g.get_fallback(kind)),
157 Gradient::WebKitGradient(g) => Gradient::WebKitGradient(g.get_fallback(kind)),
158 }
159 }
160}
161
162impl<'i> Parse<'i> for Gradient {
163 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
164 let location = input.current_source_location();
165 let func = input.expect_function()?.clone();
166 input.parse_nested_block(|input| {
167 match_ignore_ascii_case! { &func,
168 "linear-gradient" => Ok(Gradient::Linear(LinearGradient::parse(input, VendorPrefix::None)?)),
169 "repeating-linear-gradient" => Ok(Gradient::RepeatingLinear(LinearGradient::parse(input, VendorPrefix::None)?)),
170 "radial-gradient" => Ok(Gradient::Radial(RadialGradient::parse(input, VendorPrefix::None)?)),
171 "repeating-radial-gradient" => Ok(Gradient::RepeatingRadial(RadialGradient::parse(input, VendorPrefix::None)?)),
172 "conic-gradient" => Ok(Gradient::Conic(ConicGradient::parse(input)?)),
173 "repeating-conic-gradient" => Ok(Gradient::RepeatingConic(ConicGradient::parse(input)?)),
174 "-webkit-linear-gradient" => Ok(Gradient::Linear(LinearGradient::parse(input, VendorPrefix::WebKit)?)),
175 "-webkit-repeating-linear-gradient" => Ok(Gradient::RepeatingLinear(LinearGradient::parse(input, VendorPrefix::WebKit)?)),
176 "-webkit-radial-gradient" => Ok(Gradient::Radial(RadialGradient::parse(input, VendorPrefix::WebKit)?)),
177 "-webkit-repeating-radial-gradient" => Ok(Gradient::RepeatingRadial(RadialGradient::parse(input, VendorPrefix::WebKit)?)),
178 "-moz-linear-gradient" => Ok(Gradient::Linear(LinearGradient::parse(input, VendorPrefix::Moz)?)),
179 "-moz-repeating-linear-gradient" => Ok(Gradient::RepeatingLinear(LinearGradient::parse(input, VendorPrefix::Moz)?)),
180 "-moz-radial-gradient" => Ok(Gradient::Radial(RadialGradient::parse(input, VendorPrefix::Moz)?)),
181 "-moz-repeating-radial-gradient" => Ok(Gradient::RepeatingRadial(RadialGradient::parse(input, VendorPrefix::Moz)?)),
182 "-o-linear-gradient" => Ok(Gradient::Linear(LinearGradient::parse(input, VendorPrefix::O)?)),
183 "-o-repeating-linear-gradient" => Ok(Gradient::RepeatingLinear(LinearGradient::parse(input, VendorPrefix::O)?)),
184 "-o-radial-gradient" => Ok(Gradient::Radial(RadialGradient::parse(input, VendorPrefix::O)?)),
185 "-o-repeating-radial-gradient" => Ok(Gradient::RepeatingRadial(RadialGradient::parse(input, VendorPrefix::O)?)),
186 "-webkit-gradient" => Ok(Gradient::WebKitGradient(WebKitGradient::parse(input)?)),
187 _ => Err(location.new_unexpected_token_error(cssparser::Token::Ident(func.clone())))
188 }
189 })
190 }
191}
192
193impl ToCss for Gradient {
194 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
195 let (f, prefix) = match self {
196 Gradient::Linear(g) => ("linear-gradient(", Some(g.vendor_prefix)),
197 Gradient::RepeatingLinear(g) => ("repeating-linear-gradient(", Some(g.vendor_prefix)),
198 Gradient::Radial(g) => ("radial-gradient(", Some(g.vendor_prefix)),
199 Gradient::RepeatingRadial(g) => ("repeating-radial-gradient(", Some(g.vendor_prefix)),
200 Gradient::Conic(_) => ("conic-gradient(", None),
201 Gradient::RepeatingConic(_) => ("repeating-conic-gradient(", None),
202 Gradient::WebKitGradient(_) => ("-webkit-gradient(", None),
203 };
204
205 if let Some(prefix) = prefix {
206 prefix.to_css(dest)?;
207 }
208
209 dest.write_str(f)?;
210
211 match self {
212 Gradient::Linear(linear) | Gradient::RepeatingLinear(linear) => {
213 linear.to_css(dest, linear.vendor_prefix != VendorPrefix::None)?
214 }
215 Gradient::Radial(radial) | Gradient::RepeatingRadial(radial) => radial.to_css(dest)?,
216 Gradient::Conic(conic) | Gradient::RepeatingConic(conic) => conic.to_css(dest)?,
217 Gradient::WebKitGradient(g) => g.to_css(dest)?,
218 }
219
220 dest.write_char(')')?;
221
222 Ok(())
223 }
224}
225
226#[derive(Debug, Clone, PartialEq)]
228#[cfg_attr(feature = "visitor", derive(Visit))]
229#[cfg_attr(
230 feature = "serde",
231 derive(serde::Serialize, serde::Deserialize),
232 serde(rename_all = "camelCase")
233)]
234#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
235#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
236pub struct LinearGradient {
237 pub vendor_prefix: VendorPrefix,
239 pub direction: LineDirection,
241 pub items: Vec<GradientItem<LengthPercentage>>,
243}
244
245impl LinearGradient {
246 fn parse<'i, 't>(
247 input: &mut Parser<'i, 't>,
248 vendor_prefix: VendorPrefix,
249 ) -> Result<LinearGradient, ParseError<'i, ParserError<'i>>> {
250 let direction = if let Ok(direction) =
251 input.try_parse(|input| LineDirection::parse(input, vendor_prefix != VendorPrefix::None))
252 {
253 input.expect_comma()?;
254 direction
255 } else {
256 LineDirection::Vertical(VerticalPositionKeyword::Bottom)
257 };
258 let items = parse_items(input)?;
259 Ok(LinearGradient {
260 direction,
261 items,
262 vendor_prefix,
263 })
264 }
265
266 fn to_css<PrinterT: crate::printer::PrinterTrait>(
267 &self,
268 dest: &mut PrinterT,
269 is_prefixed: bool,
270 ) -> Result<(), PrinterError> {
271 let angle = match &self.direction {
272 LineDirection::Vertical(VerticalPositionKeyword::Bottom) => 180.0,
273 LineDirection::Vertical(VerticalPositionKeyword::Top) => 0.0,
274 LineDirection::Angle(angle) => angle.to_degrees(),
275 _ => -1.0,
276 };
277
278 if angle == 180.0 {
280 serialize_items(&self.items, dest)
281
282 } else if angle == 0.0
285 && dest.options().minify
286 && self.items.iter().all(|item| {
287 matches!(
288 item,
289 GradientItem::Hint(LengthPercentage::Percentage(_))
290 | GradientItem::ColorStop(ColorStop {
291 position: None | Some(LengthPercentage::Percentage(_)),
292 ..
293 })
294 )
295 })
296 {
297 let items: Vec<GradientItem<LengthPercentage>> = self
298 .items
299 .iter()
300 .rev()
301 .map(|item| {
302 match item {
304 GradientItem::Hint(LengthPercentage::Percentage(p)) => {
305 GradientItem::Hint(LengthPercentage::Percentage(Percentage(1.0 - p.0)))
306 }
307 GradientItem::ColorStop(ColorStop { color, position }) => GradientItem::ColorStop(ColorStop {
308 color: color.clone(),
309 position: position.clone().map(|p| match p {
310 LengthPercentage::Percentage(p) => LengthPercentage::Percentage(Percentage(1.0 - p.0)),
311 _ => unreachable!(),
312 }),
313 }),
314 _ => unreachable!(),
315 }
316 })
317 .collect();
318 serialize_items(&items, dest)
319 } else {
320 if self.direction != LineDirection::Vertical(VerticalPositionKeyword::Bottom)
321 && self.direction != LineDirection::Angle(Angle::Deg(180.0))
322 {
323 self.direction.to_css(dest, is_prefixed)?;
324 dest.delim(',', false)?;
325 }
326
327 serialize_items(&self.items, dest)
328 }
329 }
330
331 fn get_fallback(&self, kind: ColorFallbackKind) -> LinearGradient {
332 LinearGradient {
333 direction: self.direction.clone(),
334 items: self.items.iter().map(|item| item.get_fallback(kind)).collect(),
335 vendor_prefix: self.vendor_prefix,
336 }
337 }
338}
339
340impl IsCompatible for LinearGradient {
341 fn is_compatible(&self, browsers: Browsers) -> bool {
342 self.items.iter().all(|item| item.is_compatible(browsers))
343 }
344}
345
346#[derive(Debug, Clone, PartialEq)]
348#[cfg_attr(feature = "visitor", derive(Visit))]
349#[cfg_attr(
350 feature = "serde",
351 derive(serde::Serialize, serde::Deserialize),
352 serde(rename_all = "camelCase")
353)]
354#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
355#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
356pub struct RadialGradient {
357 pub vendor_prefix: VendorPrefix,
359 pub shape: EndingShape,
361 pub position: Position,
363 pub items: Vec<GradientItem<LengthPercentage>>,
365}
366
367impl<'i> RadialGradient {
368 fn parse<'t>(
369 input: &mut Parser<'i, 't>,
370 vendor_prefix: VendorPrefix,
371 ) -> Result<RadialGradient, ParseError<'i, ParserError<'i>>> {
372 let shape = input.try_parse(EndingShape::parse).ok();
373 let position = input
374 .try_parse(|input| {
375 input.expect_ident_matching("at")?;
376 Position::parse(input)
377 })
378 .ok();
379
380 if shape.is_some() || position.is_some() {
381 input.expect_comma()?;
382 }
383
384 let items = parse_items(input)?;
385 Ok(RadialGradient {
386 shape: shape.unwrap_or_default(),
387 position: position.unwrap_or(Position::center()),
388 items,
389 vendor_prefix,
390 })
391 }
392}
393
394impl ToCss for RadialGradient {
395 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
396 if self.shape != EndingShape::default() {
397 self.shape.to_css(dest)?;
398 if self.position.is_center() {
399 dest.delim(',', false)?;
400 } else {
401 dest.write_char(' ')?;
402 }
403 }
404
405 if !self.position.is_center() {
406 dest.write_str("at ")?;
407 self.position.to_css(dest)?;
408 dest.delim(',', false)?;
409 }
410
411 serialize_items(&self.items, dest)
412 }
413}
414
415impl RadialGradient {
416 fn get_fallback(&self, kind: ColorFallbackKind) -> RadialGradient {
417 RadialGradient {
418 shape: self.shape.clone(),
419 position: self.position.clone(),
420 items: self.items.iter().map(|item| item.get_fallback(kind)).collect(),
421 vendor_prefix: self.vendor_prefix,
422 }
423 }
424}
425
426impl IsCompatible for RadialGradient {
427 fn is_compatible(&self, browsers: Browsers) -> bool {
428 self.items.iter().all(|item| item.is_compatible(browsers))
429 }
430}
431
432#[derive(Debug, Clone, PartialEq)]
436#[cfg_attr(feature = "visitor", derive(Visit))]
437#[cfg_attr(
438 feature = "serde",
439 derive(serde::Serialize, serde::Deserialize),
440 serde(tag = "type", rename_all = "kebab-case")
441)]
442#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
443pub enum LineDirection {
444 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<Angle>"))]
446 Angle(Angle),
447 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<HorizontalPositionKeyword>"))]
449 Horizontal(HorizontalPositionKeyword),
450 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<VerticalPositionKeyword>"))]
452 Vertical(VerticalPositionKeyword),
453 Corner {
455 horizontal: HorizontalPositionKeyword,
457 vertical: VerticalPositionKeyword,
459 },
460}
461
462impl LineDirection {
463 fn parse<'i, 't>(
464 input: &mut Parser<'i, 't>,
465 is_prefixed: bool,
466 ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
467 if let Ok(angle) = input.try_parse(Angle::parse_with_unitless_zero) {
470 return Ok(LineDirection::Angle(angle));
471 }
472
473 if !is_prefixed {
474 input.expect_ident_matching("to")?;
475 }
476
477 if let Ok(x) = input.try_parse(HorizontalPositionKeyword::parse) {
478 if let Ok(y) = input.try_parse(VerticalPositionKeyword::parse) {
479 return Ok(LineDirection::Corner {
480 horizontal: x,
481 vertical: y,
482 });
483 }
484 return Ok(LineDirection::Horizontal(x));
485 }
486
487 let y = VerticalPositionKeyword::parse(input)?;
488 if let Ok(x) = input.try_parse(HorizontalPositionKeyword::parse) {
489 return Ok(LineDirection::Corner {
490 horizontal: x,
491 vertical: y,
492 });
493 }
494 Ok(LineDirection::Vertical(y))
495 }
496
497 fn to_css<PrinterT: crate::printer::PrinterTrait>(
498 &self,
499 dest: &mut PrinterT,
500 is_prefixed: bool,
501 ) -> Result<(), PrinterError> {
502 match self {
503 LineDirection::Angle(angle) => angle.to_css(dest),
504 LineDirection::Horizontal(k) => {
505 if dest.options().minify {
506 match k {
507 HorizontalPositionKeyword::Left => {
508 dest.write_str("270deg")?;
509 Ok(())
510 }
511 HorizontalPositionKeyword::Right => {
512 dest.write_str("90deg")?;
513 Ok(())
514 }
515 }
516 } else {
517 if !is_prefixed {
518 dest.write_str("to ")?;
519 }
520 k.to_css(dest)
521 }
522 }
523 LineDirection::Vertical(k) => {
524 if dest.options().minify {
525 match k {
526 VerticalPositionKeyword::Top => {
527 dest.write_str("0deg")?;
528 Ok(())
529 }
530 VerticalPositionKeyword::Bottom => {
531 dest.write_str("180deg")?;
532 Ok(())
533 }
534 }
535 } else {
536 if !is_prefixed {
537 dest.write_str("to ")?;
538 }
539 k.to_css(dest)
540 }
541 }
542 LineDirection::Corner { horizontal, vertical } => {
543 if !is_prefixed {
544 dest.write_str("to ")?;
545 }
546 vertical.to_css(dest)?;
547 dest.write_char(' ')?;
548 horizontal.to_css(dest)
549 }
550 }
551 }
552}
553
554fn convert_to_legacy_direction(direction: &LineDirection) -> LineDirection {
561 match direction {
562 LineDirection::Horizontal(HorizontalPositionKeyword::Left) => {
563 LineDirection::Horizontal(HorizontalPositionKeyword::Right)
564 }
565 LineDirection::Horizontal(HorizontalPositionKeyword::Right) => {
566 LineDirection::Horizontal(HorizontalPositionKeyword::Left)
567 }
568 LineDirection::Vertical(VerticalPositionKeyword::Top) => {
569 LineDirection::Vertical(VerticalPositionKeyword::Bottom)
570 }
571 LineDirection::Vertical(VerticalPositionKeyword::Bottom) => {
572 LineDirection::Vertical(VerticalPositionKeyword::Top)
573 }
574 LineDirection::Corner { horizontal, vertical } => LineDirection::Corner {
575 horizontal: match horizontal {
576 HorizontalPositionKeyword::Left => HorizontalPositionKeyword::Right,
577 HorizontalPositionKeyword::Right => HorizontalPositionKeyword::Left,
578 },
579 vertical: match vertical {
580 VerticalPositionKeyword::Top => VerticalPositionKeyword::Bottom,
581 VerticalPositionKeyword::Bottom => VerticalPositionKeyword::Top,
582 },
583 },
584 LineDirection::Angle(angle) => {
585 let angle = angle.clone();
586 let deg = match angle {
587 Angle::Deg(n) => convert_to_legacy_degree(n),
588 Angle::Rad(n) => {
589 let n = n / (2.0 * PI) * 360.0;
590 convert_to_legacy_degree(n)
591 }
592 Angle::Grad(n) => {
593 let n = n / 400.0 * 360.0;
594 convert_to_legacy_degree(n)
595 }
596 Angle::Turn(n) => {
597 let n = n * 360.0;
598 convert_to_legacy_degree(n)
599 }
600 };
601 LineDirection::Angle(Angle::Deg(deg))
602 }
603 }
604}
605
606fn convert_to_legacy_degree(degree: f32) -> f32 {
607 let n = (450.0 - degree).abs() % 360.0;
609 (n * 1000.0).round() / 1000.0
611}
612
613#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
617#[cfg_attr(feature = "visitor", derive(Visit))]
618#[cfg_attr(
619 feature = "serde",
620 derive(serde::Serialize, serde::Deserialize),
621 serde(tag = "type", content = "value", rename_all = "kebab-case")
622)]
623#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
624pub enum EndingShape {
625 Ellipse(Ellipse),
628 Circle(Circle),
630}
631
632impl Default for EndingShape {
633 fn default() -> EndingShape {
634 EndingShape::Ellipse(Ellipse::Extent(ShapeExtent::FarthestCorner))
635 }
636}
637
638#[derive(Debug, Clone, PartialEq)]
642#[cfg_attr(feature = "visitor", derive(Visit))]
643#[cfg_attr(
644 feature = "serde",
645 derive(serde::Serialize, serde::Deserialize),
646 serde(tag = "type", content = "value", rename_all = "kebab-case")
647)]
648#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
649pub enum Circle {
650 Radius(NonNegative<Length>),
652 Extent(ShapeExtent),
654}
655
656impl<'i> Parse<'i> for Circle {
657 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
658 if let Ok(extent) = input.try_parse(ShapeExtent::parse) {
659 input.expect_ident_matching("circle")?;
661 return Ok(Circle::Extent(extent));
662 }
663
664 if let Ok(length) = input.try_parse(NonNegative::<Length>::parse) {
665 let _ = input.try_parse(|input| input.expect_ident_matching("circle"));
668 return Ok(Circle::Radius(length));
669 }
670
671 if input.try_parse(|input| input.expect_ident_matching("circle")).is_ok() {
672 if let Ok(extent) = input.try_parse(ShapeExtent::parse) {
673 return Ok(Circle::Extent(extent));
674 }
675
676 if let Ok(length) = input.try_parse(NonNegative::<Length>::parse) {
677 return Ok(Circle::Radius(length));
678 }
679
680 return Ok(Circle::Extent(ShapeExtent::FarthestCorner));
682 }
683
684 return Err(input.new_error_for_next_token());
685 }
686}
687
688impl ToCss for Circle {
689 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
690 match self {
691 Circle::Radius(r) => r.to_css(dest),
692 Circle::Extent(extent) => {
693 dest.write_str("circle")?;
694 if *extent != ShapeExtent::FarthestCorner {
695 dest.write_char(' ')?;
696 extent.to_css(dest)?;
697 }
698 Ok(())
699 }
700 }
701 }
702}
703
704#[derive(Debug, Clone, PartialEq)]
708#[cfg_attr(feature = "visitor", derive(Visit))]
709#[cfg_attr(
710 feature = "serde",
711 derive(serde::Serialize, serde::Deserialize),
712 serde(tag = "type", rename_all = "kebab-case")
713)]
714#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
715pub enum Ellipse {
716 Size {
718 x: NonNegative<LengthPercentage>,
720 y: NonNegative<LengthPercentage>,
722 },
723 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<ShapeExtent>"))]
725 Extent(ShapeExtent),
726}
727
728impl<'i> Parse<'i> for Ellipse {
729 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
730 if let Ok(extent) = input.try_parse(ShapeExtent::parse) {
731 if input.try_parse(|input| input.expect_ident_matching("circle")).is_ok() {
734 return Err(input.new_error_for_next_token());
735 }
736 let _ = input.try_parse(|input| input.expect_ident_matching("ellipse"));
737 return Ok(Ellipse::Extent(extent));
738 }
739
740 if let Ok(x) = input.try_parse(NonNegative::<LengthPercentage>::parse) {
741 let y = NonNegative::<LengthPercentage>::parse(input)?;
742 let _ = input.try_parse(|input| input.expect_ident_matching("ellipse"));
744 return Ok(Ellipse::Size { x, y });
745 }
746
747 if input.try_parse(|input| input.expect_ident_matching("ellipse")).is_ok() {
748 if let Ok(extent) = input.try_parse(ShapeExtent::parse) {
749 return Ok(Ellipse::Extent(extent));
750 }
751
752 if let Ok(x) = input.try_parse(NonNegative::<LengthPercentage>::parse) {
753 let y = NonNegative::<LengthPercentage>::parse(input)?;
754 return Ok(Ellipse::Size { x, y });
755 }
756
757 return Ok(Ellipse::Extent(ShapeExtent::FarthestCorner));
759 }
760
761 return Err(input.new_error_for_next_token());
762 }
763}
764
765impl ToCss for Ellipse {
766 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
767 match self {
769 Ellipse::Size { x, y } => {
770 x.to_css(dest)?;
771 dest.write_char(' ')?;
772 y.to_css(dest)
773 }
774 Ellipse::Extent(extent) => extent.to_css(dest),
775 }
776 }
777}
778
779enum_property! {
780 pub enum ShapeExtent {
784 ClosestSide,
786 FarthestSide,
788 ClosestCorner,
790 FarthestCorner,
792 }
793}
794
795#[derive(Debug, Clone, PartialEq)]
797#[cfg_attr(feature = "visitor", derive(Visit))]
798#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
799#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
800#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
801pub struct ConicGradient {
802 pub angle: Angle,
804 pub position: Position,
806 pub items: Vec<GradientItem<AnglePercentage>>,
808}
809
810impl ConicGradient {
811 fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
812 let angle = input.try_parse(|input| {
813 input.expect_ident_matching("from")?;
814 Angle::parse_with_unitless_zero(input)
817 });
818
819 let position = input.try_parse(|input| {
820 input.expect_ident_matching("at")?;
821 Position::parse(input)
822 });
823
824 if angle.is_ok() || position.is_ok() {
825 input.expect_comma()?;
826 }
827
828 let items = parse_items(input)?;
829 Ok(ConicGradient {
830 angle: angle.unwrap_or(Angle::Deg(0.0)),
831 position: position.unwrap_or(Position::center()),
832 items,
833 })
834 }
835}
836
837impl ToCss for ConicGradient {
838 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
839 if !self.angle.is_zero() {
840 dest.write_str("from ")?;
841 self.angle.to_css(dest)?;
842
843 if self.position.is_center() {
844 dest.delim(',', false)?;
845 } else {
846 dest.write_char(' ')?;
847 }
848 }
849
850 if !self.position.is_center() {
851 dest.write_str("at ")?;
852 self.position.to_css(dest)?;
853 dest.delim(',', false)?;
854 }
855
856 serialize_items(&self.items, dest)
857 }
858}
859
860impl ConicGradient {
861 fn get_fallback(&self, kind: ColorFallbackKind) -> ConicGradient {
862 ConicGradient {
863 angle: self.angle.clone(),
864 position: self.position.clone(),
865 items: self.items.iter().map(|item| item.get_fallback(kind)).collect(),
866 }
867 }
868}
869
870impl IsCompatible for ConicGradient {
871 fn is_compatible(&self, browsers: Browsers) -> bool {
872 self.items.iter().all(|item| item.is_compatible(browsers))
873 }
874}
875
876#[derive(Debug, Clone, PartialEq)]
881#[cfg_attr(feature = "visitor", derive(Visit))]
882#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
883#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
884pub struct ColorStop<D> {
885 pub color: CssColor,
887 pub position: Option<D>,
889}
890
891impl<'i, D: Parse<'i>> Parse<'i> for ColorStop<D> {
892 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
893 let color = CssColor::parse(input)?;
894 let position = input.try_parse(D::parse).ok();
895 Ok(ColorStop { color, position })
896 }
897}
898
899impl<D: ToCss> ToCss for ColorStop<D> {
900 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
901 self.color.to_css(dest)?;
902 if let Some(position) = &self.position {
903 dest.write_char(' ')?;
904 position.to_css(dest)?;
905 }
906 Ok(())
907 }
908}
909
910#[derive(Debug, Clone, PartialEq)]
915#[cfg_attr(feature = "visitor", derive(Visit))]
916#[cfg_attr(
917 feature = "serde",
918 derive(serde::Serialize, serde::Deserialize),
919 serde(tag = "type", rename_all = "kebab-case")
920)]
921#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
922pub enum GradientItem<D> {
923 ColorStop(ColorStop<D>),
925 #[cfg_attr(
927 feature = "serde",
928 serde(
929 bound(serialize = "D: serde::Serialize", deserialize = "D: serde::Deserialize<'de>"),
930 with = "ValueWrapper::<D>"
931 )
932 )]
933 Hint(D),
934}
935
936impl<D: ToCss> ToCss for GradientItem<D> {
937 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
938 match self {
939 GradientItem::ColorStop(stop) => stop.to_css(dest),
940 GradientItem::Hint(hint) => hint.to_css(dest),
941 }
942 }
943}
944
945impl<D: Clone> GradientItem<D> {
946 pub fn get_necessary_fallbacks(&self, targets: Targets) -> ColorFallbackKind {
948 match self {
949 GradientItem::ColorStop(stop) => stop.color.get_necessary_fallbacks(targets),
950 GradientItem::Hint(..) => ColorFallbackKind::empty(),
951 }
952 }
953
954 pub fn get_fallback(&self, kind: ColorFallbackKind) -> GradientItem<D> {
956 match self {
957 GradientItem::ColorStop(stop) => GradientItem::ColorStop(ColorStop {
958 color: stop.color.get_fallback(kind),
959 position: stop.position.clone(),
960 }),
961 GradientItem::Hint(..) => self.clone(),
962 }
963 }
964}
965
966impl<D> IsCompatible for GradientItem<D> {
967 fn is_compatible(&self, browsers: Browsers) -> bool {
968 match self {
969 GradientItem::ColorStop(c) => c.color.is_compatible(browsers),
970 GradientItem::Hint(..) => compat::Feature::GradientInterpolationHints.is_compatible(browsers),
971 }
972 }
973}
974
975fn parse_items<'i, 't, D: Parse<'i>>(
976 input: &mut Parser<'i, 't>,
977) -> Result<Vec<GradientItem<D>>, ParseError<'i, ParserError<'i>>> {
978 let mut items = Vec::new();
979 let mut seen_stop = false;
980
981 loop {
982 input.parse_until_before(Delimiter::Comma, |input| {
983 if seen_stop {
984 if let Ok(hint) = input.try_parse(D::parse) {
985 seen_stop = false;
986 items.push(GradientItem::Hint(hint));
987 return Ok(());
988 }
989 }
990
991 let stop = ColorStop::parse(input)?;
992
993 if let Ok(position) = input.try_parse(D::parse) {
994 let color = stop.color.clone();
995 items.push(GradientItem::ColorStop(stop));
996
997 items.push(GradientItem::ColorStop(ColorStop {
998 color,
999 position: Some(position),
1000 }))
1001 } else {
1002 items.push(GradientItem::ColorStop(stop));
1003 }
1004
1005 seen_stop = true;
1006 Ok(())
1007 })?;
1008
1009 match input.next() {
1010 Err(_) => break,
1011 Ok(Token::Comma) => continue,
1012 _ => unreachable!(),
1013 }
1014 }
1015
1016 Ok(items)
1017}
1018
1019fn serialize_items<
1020 D: ToCss + std::cmp::PartialEq<D> + std::ops::Mul<f32, Output = D> + TrySign + Clone + std::fmt::Debug,
1021 PrinterT: crate::printer::PrinterTrait,
1022>(
1023 items: &Vec<GradientItem<DimensionPercentage<D>>>,
1024 dest: &mut PrinterT,
1025) -> Result<(), PrinterError> {
1026 let mut first = true;
1027 let mut last: Option<&GradientItem<DimensionPercentage<D>>> = None;
1028 for item in items {
1029 if *item == GradientItem::Hint(DimensionPercentage::Percentage(Percentage(0.5))) {
1031 continue;
1032 }
1033
1034 if let Some(prev) = last {
1036 if !should_compile!(dest.targets().current, DoublePositionGradients) {
1037 match (prev, item) {
1038 (
1039 GradientItem::ColorStop(ColorStop {
1040 position: Some(_),
1041 color: ca,
1042 }),
1043 GradientItem::ColorStop(ColorStop {
1044 position: Some(p),
1045 color: cb,
1046 }),
1047 ) if ca == cb => {
1048 dest.write_char(' ')?;
1049 p.to_css(dest)?;
1050 last = None;
1051 continue;
1052 }
1053 _ => {}
1054 }
1055 }
1056 }
1057
1058 if first {
1059 first = false;
1060 } else {
1061 dest.delim(',', false)?;
1062 }
1063 item.to_css(dest)?;
1064 last = Some(item)
1065 }
1066 Ok(())
1067}
1068
1069#[derive(Debug, Clone, PartialEq)]
1071#[cfg_attr(feature = "visitor", derive(Visit))]
1072#[cfg_attr(
1073 feature = "serde",
1074 derive(serde::Serialize, serde::Deserialize),
1075 serde(tag = "kind", rename_all = "kebab-case")
1076)]
1077#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1078#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1079pub enum WebKitGradient {
1080 Linear {
1082 from: WebKitGradientPoint,
1084 to: WebKitGradientPoint,
1086 stops: Vec<WebKitColorStop>,
1088 },
1089 Radial {
1091 from: WebKitGradientPoint,
1093 r0: CSSNumber,
1095 to: WebKitGradientPoint,
1097 r1: CSSNumber,
1099 stops: Vec<WebKitColorStop>,
1101 },
1102}
1103
1104impl<'i> Parse<'i> for WebKitGradient {
1105 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1106 let location = input.current_source_location();
1107 let ident = input.expect_ident_cloned()?;
1108 input.expect_comma()?;
1109
1110 match_ignore_ascii_case! { &ident,
1111 "linear" => {
1112 let from = WebKitGradientPoint::parse(input)?;
1113 input.expect_comma()?;
1114 let to = WebKitGradientPoint::parse(input)?;
1115 input.expect_comma()?;
1116 let stops = input.parse_comma_separated(WebKitColorStop::parse)?;
1117 Ok(WebKitGradient::Linear {
1118 from,
1119 to,
1120 stops
1121 })
1122 },
1123 "radial" => {
1124 let from = WebKitGradientPoint::parse(input)?;
1125 input.expect_comma()?;
1126 let r0 = CSSNumber::parse(input)?;
1127 input.expect_comma()?;
1128 let to = WebKitGradientPoint::parse(input)?;
1129 input.expect_comma()?;
1130 let r1 = CSSNumber::parse(input)?;
1131 input.expect_comma()?;
1132 let stops = input.parse_comma_separated(WebKitColorStop::parse)?;
1133 Ok(WebKitGradient::Radial {
1134 from,
1135 r0,
1136 to,
1137 r1,
1138 stops
1139 })
1140 },
1141 _ => Err(location.new_unexpected_token_error(cssparser::Token::Ident(ident.clone())))
1142 }
1143 }
1144}
1145
1146impl ToCss for WebKitGradient {
1147 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1148 match self {
1149 WebKitGradient::Linear { from, to, stops } => {
1150 dest.write_str("linear")?;
1151 dest.delim(',', false)?;
1152 from.to_css(dest)?;
1153 dest.delim(',', false)?;
1154 to.to_css(dest)?;
1155 for stop in stops {
1156 dest.delim(',', false)?;
1157 stop.to_css(dest)?;
1158 }
1159 Ok(())
1160 }
1161 WebKitGradient::Radial {
1162 from,
1163 r0,
1164 to,
1165 r1,
1166 stops,
1167 } => {
1168 dest.write_str("radial")?;
1169 dest.delim(',', false)?;
1170 from.to_css(dest)?;
1171 dest.delim(',', false)?;
1172 r0.to_css(dest)?;
1173 dest.delim(',', false)?;
1174 to.to_css(dest)?;
1175 dest.delim(',', false)?;
1176 r1.to_css(dest)?;
1177 for stop in stops {
1178 dest.delim(',', false)?;
1179 stop.to_css(dest)?;
1180 }
1181 Ok(())
1182 }
1183 }
1184 }
1185}
1186
1187impl WebKitGradient {
1188 fn get_fallback(&self, kind: ColorFallbackKind) -> WebKitGradient {
1189 let stops = match self {
1190 WebKitGradient::Linear { stops, .. } => stops,
1191 WebKitGradient::Radial { stops, .. } => stops,
1192 };
1193
1194 let stops = stops.iter().map(|stop| stop.get_fallback(kind)).collect();
1195
1196 match self {
1197 WebKitGradient::Linear { from, to, .. } => WebKitGradient::Linear {
1198 from: from.clone(),
1199 to: to.clone(),
1200 stops,
1201 },
1202 WebKitGradient::Radial { from, r0, to, r1, .. } => WebKitGradient::Radial {
1203 from: from.clone(),
1204 r0: *r0,
1205 to: to.clone(),
1206 r1: *r1,
1207 stops,
1208 },
1209 }
1210 }
1211}
1212
1213#[derive(Debug, Clone, PartialEq)]
1215#[cfg_attr(feature = "visitor", derive(Visit))]
1216#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1217#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1218pub struct WebKitColorStop {
1219 pub color: CssColor,
1221 pub position: CSSNumber,
1223}
1224
1225impl<'i> Parse<'i> for WebKitColorStop {
1226 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1227 let location = input.current_source_location();
1228 let function = input.expect_function()?.clone();
1229 input.parse_nested_block(|input| {
1230 let position = match_ignore_ascii_case! { &function,
1231 "color-stop" => {
1232 let p = NumberOrPercentage::parse(input)?;
1233 input.expect_comma()?;
1234 (&p).into()
1235 },
1236 "from" => 0.0,
1237 "to" => 1.0,
1238 _ => return Err(location.new_unexpected_token_error(cssparser::Token::Ident(function.clone())))
1239 };
1240 let color = CssColor::parse(input)?;
1241 Ok(WebKitColorStop { color, position })
1242 })
1243 }
1244}
1245
1246impl ToCss for WebKitColorStop {
1247 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1248 if self.position == 0.0 {
1249 dest.write_str("from(")?;
1250 self.color.to_css(dest)?;
1251 } else if self.position == 1.0 {
1252 dest.write_str("to(")?;
1253 self.color.to_css(dest)?;
1254 } else {
1255 dest.write_str("color-stop(")?;
1256 self.position.to_css(dest)?;
1257 dest.delim(',', false)?;
1258 self.color.to_css(dest)?;
1259 }
1260 dest.write_char(')')?;
1261 Ok(())
1262 }
1263}
1264
1265impl WebKitColorStop {
1266 fn get_fallback(&self, kind: ColorFallbackKind) -> WebKitColorStop {
1267 WebKitColorStop {
1268 color: self.color.get_fallback(kind),
1269 position: self.position,
1270 }
1271 }
1272}
1273
1274#[derive(Debug, Clone, PartialEq)]
1276#[cfg_attr(feature = "visitor", derive(Visit))]
1277#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1278#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1279#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1280pub struct WebKitGradientPoint {
1281 pub x: WebKitGradientPointComponent<HorizontalPositionKeyword>,
1283 pub y: WebKitGradientPointComponent<VerticalPositionKeyword>,
1285}
1286
1287impl<'i> Parse<'i> for WebKitGradientPoint {
1288 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1289 let x = WebKitGradientPointComponent::parse(input)?;
1290 let y = WebKitGradientPointComponent::parse(input)?;
1291 Ok(WebKitGradientPoint { x, y })
1292 }
1293}
1294
1295impl ToCss for WebKitGradientPoint {
1296 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1297 self.x.to_css(dest)?;
1298 dest.write_char(' ')?;
1299 self.y.to_css(dest)
1300 }
1301}
1302
1303#[derive(Debug, Clone, PartialEq)]
1305#[cfg_attr(feature = "visitor", derive(Visit))]
1306#[cfg_attr(
1307 feature = "serde",
1308 derive(serde::Serialize, serde::Deserialize),
1309 serde(tag = "type", content = "value", rename_all = "kebab-case")
1310)]
1311#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1312#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1313pub enum WebKitGradientPointComponent<S> {
1314 Center,
1316 Number(NumberOrPercentage),
1318 Side(S),
1320}
1321
1322impl<'i, S: Parse<'i>> Parse<'i> for WebKitGradientPointComponent<S> {
1323 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1324 if input.try_parse(|i| i.expect_ident_matching("center")).is_ok() {
1325 return Ok(WebKitGradientPointComponent::Center);
1326 }
1327
1328 if let Ok(lp) = input.try_parse(NumberOrPercentage::parse) {
1329 return Ok(WebKitGradientPointComponent::Number(lp));
1330 }
1331
1332 let keyword = S::parse(input)?;
1333 Ok(WebKitGradientPointComponent::Side(keyword))
1334 }
1335}
1336
1337impl<S: ToCss + Clone + Into<LengthPercentage>> ToCss for WebKitGradientPointComponent<S> {
1338 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1339 use WebKitGradientPointComponent::*;
1340 match &self {
1341 Center => {
1342 if dest.options().minify {
1343 dest.write_str("50%")?;
1344 Ok(())
1345 } else {
1346 dest.write_str("center")?;
1347 Ok(())
1348 }
1349 }
1350 Number(lp) => {
1351 if matches!(lp, NumberOrPercentage::Percentage(Percentage(p)) if *p == 0.0) {
1352 dest.write_char('0')?;
1353 Ok(())
1354 } else {
1355 lp.to_css(dest)
1356 }
1357 }
1358 Side(s) => {
1359 if dest.options().minify {
1360 let lp: LengthPercentage = s.clone().into();
1361 lp.to_css(dest)?;
1362 } else {
1363 s.to_css(dest)?;
1364 }
1365 Ok(())
1366 }
1367 }
1368 }
1369}
1370
1371impl<S: Clone> WebKitGradientPointComponent<S> {
1372 fn from_position(pos: &PositionComponent<S>) -> Result<WebKitGradientPointComponent<S>, ()> {
1374 match pos {
1375 PositionComponent::Center => Ok(WebKitGradientPointComponent::Center),
1376 PositionComponent::Length(len) => {
1377 Ok(WebKitGradientPointComponent::Number(match len {
1378 LengthPercentage::Percentage(p) => NumberOrPercentage::Percentage(p.clone()),
1379 LengthPercentage::Dimension(d) => {
1380 if let Some(px) = d.to_px() {
1382 NumberOrPercentage::Number(px)
1383 } else {
1384 return Err(());
1385 }
1386 }
1387 _ => return Err(()),
1388 }))
1389 }
1390 PositionComponent::Side { side, offset } => {
1391 if offset.is_some() {
1392 return Err(());
1393 }
1394 Ok(WebKitGradientPointComponent::Side(side.clone()))
1395 }
1396 }
1397 }
1398}
1399
1400impl WebKitGradient {
1401 pub fn from_standard(gradient: &Gradient) -> Result<WebKitGradient, ()> {
1403 match gradient {
1404 Gradient::Linear(linear) => {
1405 let (from, to) = match &linear.direction {
1407 LineDirection::Horizontal(horizontal) => match horizontal {
1408 HorizontalPositionKeyword::Left => ((1.0, 0.0), (0.0, 0.0)),
1409 HorizontalPositionKeyword::Right => ((0.0, 0.0), (1.0, 0.0)),
1410 },
1411 LineDirection::Vertical(vertical) => match vertical {
1412 VerticalPositionKeyword::Top => ((0.0, 1.0), (0.0, 0.0)),
1413 VerticalPositionKeyword::Bottom => ((0.0, 0.0), (0.0, 1.0)),
1414 },
1415 LineDirection::Corner { horizontal, vertical } => match (horizontal, vertical) {
1416 (HorizontalPositionKeyword::Left, VerticalPositionKeyword::Top) => ((1.0, 1.0), (0.0, 0.0)),
1417 (HorizontalPositionKeyword::Left, VerticalPositionKeyword::Bottom) => ((1.0, 0.0), (0.0, 1.0)),
1418 (HorizontalPositionKeyword::Right, VerticalPositionKeyword::Top) => ((0.0, 1.0), (1.0, 0.0)),
1419 (HorizontalPositionKeyword::Right, VerticalPositionKeyword::Bottom) => ((0.0, 0.0), (1.0, 1.0)),
1420 },
1421 LineDirection::Angle(angle) => {
1422 let degrees = angle.to_degrees();
1423 if degrees == 0.0 {
1424 ((0.0, 1.0), (0.0, 0.0))
1425 } else if degrees == 90.0 {
1426 ((0.0, 0.0), (1.0, 0.0))
1427 } else if degrees == 180.0 {
1428 ((0.0, 0.0), (0.0, 1.0))
1429 } else if degrees == 270.0 {
1430 ((1.0, 0.0), (0.0, 0.0))
1431 } else {
1432 return Err(());
1433 }
1434 }
1435 };
1436
1437 Ok(WebKitGradient::Linear {
1438 from: WebKitGradientPoint {
1439 x: WebKitGradientPointComponent::Number(NumberOrPercentage::Percentage(Percentage(from.0))),
1440 y: WebKitGradientPointComponent::Number(NumberOrPercentage::Percentage(Percentage(from.1))),
1441 },
1442 to: WebKitGradientPoint {
1443 x: WebKitGradientPointComponent::Number(NumberOrPercentage::Percentage(Percentage(to.0))),
1444 y: WebKitGradientPointComponent::Number(NumberOrPercentage::Percentage(Percentage(to.1))),
1445 },
1446 stops: convert_stops_to_webkit(&linear.items)?,
1447 })
1448 }
1449 Gradient::Radial(radial) => {
1450 let radius = match &radial.shape {
1452 EndingShape::Circle(Circle::Radius(radius)) => {
1453 if let Some(r) = radius.0.to_px() {
1454 r
1455 } else {
1456 return Err(());
1457 }
1458 }
1459 _ => return Err(()),
1460 };
1461
1462 let x = WebKitGradientPointComponent::from_position(&radial.position.x)?;
1463 let y = WebKitGradientPointComponent::from_position(&radial.position.y)?;
1464 let point = WebKitGradientPoint { x, y };
1465 Ok(WebKitGradient::Radial {
1466 from: point.clone(),
1467 r0: 0.0,
1468 to: point,
1469 r1: radius,
1470 stops: convert_stops_to_webkit(&radial.items)?,
1471 })
1472 }
1473 _ => Err(()),
1474 }
1475 }
1476}
1477
1478fn convert_stops_to_webkit(items: &Vec<GradientItem<LengthPercentage>>) -> Result<Vec<WebKitColorStop>, ()> {
1479 let mut stops = Vec::with_capacity(items.len());
1480 for (i, item) in items.iter().enumerate() {
1481 match item {
1482 GradientItem::ColorStop(stop) => {
1483 let position = if let Some(pos) = &stop.position {
1485 if let LengthPercentage::Percentage(position) = pos {
1486 position.0
1487 } else {
1488 return Err(());
1489 }
1490 } else if i == 0 {
1491 0.0
1492 } else if i == items.len() - 1 {
1493 1.0
1494 } else {
1495 return Err(());
1496 };
1497
1498 stops.push(WebKitColorStop {
1499 color: stop.color.clone(),
1500 position,
1501 })
1502 }
1503 _ => return Err(()),
1504 }
1505 }
1506
1507 Ok(stops)
1508}