1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//! CSS properties used in SVG.

use crate::error::{ParserError, PrinterError};
use crate::macros::enum_property;
use crate::printer::Printer;
use crate::targets::Browsers;
use crate::traits::{FallbackValues, Parse, ToCss};
use crate::values::length::LengthPercentage;
use crate::values::{color::CssColor, url::Url};
use cssparser::*;

/// An SVG [`<paint>`](https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint) value
/// used in the `fill` and `stroke` properties.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum SVGPaint<'i> {
  /// No paint.
  None,
  /// A URL reference to a paint server element, e.g. `linearGradient`, `radialGradient`, and `pattern`.
  /// The fallback is used in case the paint server cannot be resolved.
  Url(
    #[cfg_attr(feature = "serde", serde(borrow))] Url<'i>,
    Option<SVGPaintFallback>,
  ),
  /// A solid color paint.
  Color(CssColor),
  /// Use the paint value of fill from a context element.
  ContextFill,
  /// Use the paint value of stroke from a context element.
  ContextStroke,
}

/// A fallback for an SVG paint in case a paint server `url()` cannot be resolved.
///
/// See [SVGPaint](SVGPaint).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum SVGPaintFallback {
  /// No fallback.
  None,
  /// A solid color.
  Color(CssColor),
}

impl<'i> Parse<'i> for SVGPaint<'i> {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    if let Ok(url) = input.try_parse(Url::parse) {
      let fallback = input.try_parse(SVGPaintFallback::parse).ok();
      return Ok(SVGPaint::Url(url, fallback));
    }

    if let Ok(color) = input.try_parse(CssColor::parse) {
      return Ok(SVGPaint::Color(color));
    }

    let location = input.current_source_location();
    let keyword = input.expect_ident()?;
    match_ignore_ascii_case! { &keyword,
      "none" => Ok(SVGPaint::None),
      "context-fill" => Ok(SVGPaint::ContextFill),
      "context-stroke" => Ok(SVGPaint::ContextStroke),
      _ => Err(location.new_unexpected_token_error(
        cssparser::Token::Ident(keyword.clone())
      ))
    }
  }
}

impl<'i> ToCss for SVGPaint<'i> {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    match self {
      SVGPaint::None => dest.write_str("none"),
      SVGPaint::Url(url, fallback) => {
        url.to_css(dest)?;
        if let Some(fallback) = fallback {
          dest.write_char(' ')?;
          fallback.to_css(dest)?;
        }
        Ok(())
      }
      SVGPaint::Color(color) => color.to_css(dest),
      SVGPaint::ContextFill => dest.write_str("context-fill"),
      SVGPaint::ContextStroke => dest.write_str("context-stroke"),
    }
  }
}

impl<'i> Parse<'i> for SVGPaintFallback {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    if input.try_parse(|input| input.expect_ident_matching("none")).is_ok() {
      return Ok(SVGPaintFallback::None);
    }

    Ok(SVGPaintFallback::Color(CssColor::parse(input)?))
  }
}

impl ToCss for SVGPaintFallback {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    match self {
      SVGPaintFallback::None => dest.write_str("none"),
      SVGPaintFallback::Color(color) => color.to_css(dest),
    }
  }
}

impl<'i> FallbackValues for SVGPaint<'i> {
  fn get_fallbacks(&mut self, targets: Browsers) -> Vec<Self> {
    match self {
      SVGPaint::Color(color) => color
        .get_fallbacks(targets)
        .into_iter()
        .map(|color| SVGPaint::Color(color))
        .collect(),
      SVGPaint::Url(url, Some(SVGPaintFallback::Color(color))) => color
        .get_fallbacks(targets)
        .into_iter()
        .map(|color| SVGPaint::Url(url.clone(), Some(SVGPaintFallback::Color(color))))
        .collect(),
      _ => Vec::new(),
    }
  }
}

enum_property! {
  /// A value for the [stroke-linecap](https://www.w3.org/TR/SVG2/painting.html#LineCaps) property.
  pub enum StrokeLinecap {
    /// The stroke does not extend beyond its endpoints.
    Butt,
    /// The ends of the stroke are rounded.
    Round,
    /// The ends of the stroke are squared.
    Square,
  }
}

enum_property! {
  /// A value for the [stroke-linejoin](https://www.w3.org/TR/SVG2/painting.html#LineJoin) property.
  pub enum StrokeLinejoin {
    /// A sharp corner is to be used to join path segments.
    "miter": Miter,
    /// Same as `miter` but clipped beyond `stroke-miterlimit`.
    "miter-clip": MiterClip,
    /// A round corner is to be used to join path segments.
    "round": Round,
    /// A bevelled corner is to be used to join path segments.
    "bevel": Bevel,
    /// An arcs corner is to be used to join path segments.
    "arcs": Arcs,
  }
}

/// A value for the [stroke-dasharray](https://www.w3.org/TR/SVG2/painting.html#StrokeDashing) property.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum StrokeDasharray {
  /// No dashing is used.
  None,
  /// Specifies a dashing pattern to use.
  Values(Vec<LengthPercentage>),
}

impl<'i> Parse<'i> for StrokeDasharray {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    if input.try_parse(|input| input.expect_ident_matching("none")).is_ok() {
      return Ok(StrokeDasharray::None);
    }

    input.skip_whitespace();
    let mut results = vec![LengthPercentage::parse(input)?];
    loop {
      input.skip_whitespace();
      let comma_location = input.current_source_location();
      let comma = input.try_parse(|i| i.expect_comma()).is_ok();
      if let Ok(item) = input.try_parse(LengthPercentage::parse) {
        results.push(item);
      } else if comma {
        return Err(comma_location.new_unexpected_token_error(Token::Comma));
      } else {
        break;
      }
    }

    Ok(StrokeDasharray::Values(results))
  }
}

impl ToCss for StrokeDasharray {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    match self {
      StrokeDasharray::None => dest.write_str("none"),
      StrokeDasharray::Values(values) => {
        let mut first = true;
        for value in values {
          if first {
            first = false;
          } else {
            dest.write_char(' ')?;
          }
          value.to_css_unitless(dest)?;
        }
        Ok(())
      }
    }
  }
}

/// A value for the [marker](https://www.w3.org/TR/SVG2/painting.html#VertexMarkerProperties) properties.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum Marker<'i> {
  /// No marker.
  None,
  /// A url reference to a `<marker>` element.
  #[cfg_attr(feature = "serde", serde(borrow))]
  Url(Url<'i>),
}

impl<'i> Parse<'i> for Marker<'i> {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    if let Ok(url) = input.try_parse(Url::parse) {
      return Ok(Marker::Url(url));
    }

    input.expect_ident_matching("none")?;
    Ok(Marker::None)
  }
}

impl<'i> ToCss for Marker<'i> {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    match self {
      Marker::None => dest.write_str("none"),
      Marker::Url(url) => url.to_css(dest),
    }
  }
}

enum_property! {
  /// A value for the [color-interpolation](https://www.w3.org/TR/SVG2/painting.html#ColorInterpolation) property.
  pub enum ColorInterpolation {
    /// The UA can choose between sRGB or linearRGB.
    Auto,
    /// Color interpolation occurs in the sRGB color space.
    SRGB,
    /// Color interpolation occurs in the linearized RGB color space
    LinearRGB,
  }
}

enum_property! {
  /// A value for the [color-rendering](https://www.w3.org/TR/SVG2/painting.html#ColorRendering) property.
  pub enum ColorRendering {
    /// The UA can choose a tradeoff between speed and quality.
    Auto,
    /// The UA shall optimize speed over quality.
    OptimizeSpeed,
    /// The UA shall optimize quality over speed.
    OptimizeQuality,
  }
}

enum_property! {
  /// A value for the [shape-rendering](https://www.w3.org/TR/SVG2/painting.html#ShapeRendering) property.
  pub enum ShapeRendering {
    /// The UA can choose an appropriate tradeoff.
    Auto,
    /// The UA shall optimize speed.
    OptimizeSpeed,
    /// The UA shall optimize crisp edges.
    CrispEdges,
    /// The UA shall optimize geometric precision.
    GeometricPrecision,
  }
}

enum_property! {
  /// A value for the [text-rendering](https://www.w3.org/TR/SVG2/painting.html#TextRendering) property.
  pub enum TextRendering {
    /// The UA can choose an appropriate tradeoff.
    Auto,
    /// The UA shall optimize speed.
    OptimizeSpeed,
    /// The UA shall optimize legibility.
    OptimizeLegibility,
    /// The UA shall optimize geometric precision.
    GeometricPrecision,
  }
}

enum_property! {
  /// A value for the [image-rendering](https://www.w3.org/TR/SVG2/painting.html#ImageRendering) property.
  pub enum ImageRendering {
    /// The UA can choose a tradeoff between speed and quality.
    Auto,
    /// The UA shall optimize speed over quality.
    OptimizeSpeed,
    /// The UA shall optimize quality over speed.
    OptimizeQuality,
  }
}