1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
use crate::{
paint::{
IntoResources,
Resource,
ResourceIri,
},
primitives::{
ColorInterpolation,
GradientTransform,
GradientUnits,
IntoOptionalLength,
Length,
Stop,
},
utils::{
ElementWriter,
IsDefault,
},
};
use smart_default::SmartDefault;
use std::fmt::{
Display,
Formatter,
};
type GradientUnit = Length<false, true>;
/// The radial gradient element.
#[derive(Debug, Hash, Eq, PartialEq, Clone, SmartDefault)]
pub struct RadialGradient {
#[default(GradientUnit::percent(50.0))]
cx: GradientUnit,
#[default(GradientUnit::percent(50.0))]
cy: GradientUnit,
fx: Option<GradientUnit>,
fy: Option<GradientUnit>,
fr: GradientUnit,
#[default(GradientUnit::percent(50.0))]
r: GradientUnit,
stops: Vec<Stop>,
units: GradientUnits,
transform: GradientTransform,
#[default(ColorInterpolation::SRgb)]
color_interpolation: ColorInterpolation,
}
impl RadialGradient {
/// Creates a new [`RadialGradient`] instance.
///
/// # Returns
/// - [`Self`]
pub fn new() -> Self {
RadialGradient::default()
}
/// Sets the radius of the radial gradient.
///
/// # Arguments
/// - `value`: The radius value.
///
/// # Returns
/// - [`Self`]
pub fn r<T>(mut self, value: T) -> Self
where
T: IntoOptionalLength<false, true>,
{
self.r = value
.into_optional_length()
.unwrap_or(GradientUnit::percent(50.0));
self
}
/// Sets the x coordinate of the end circle of gradient.
///
/// # Arguments
/// - `value`: The x coordinate value.
///
/// # Returns
/// - [`Self`]
pub fn cx<T>(mut self, value: T) -> Self
where
T: IntoOptionalLength<false, true>,
{
self.cx = value
.into_optional_length()
.unwrap_or(GradientUnit::percent(50.0));
self
}
/// Sets the y coordinate of the end circle of gradient.
///
/// # Arguments
/// - `value`: The y coordinate value.
///
/// # Returns
/// - [`Self`]
pub fn cy<T>(mut self, value: T) -> Self
where
T: IntoOptionalLength<false, true>,
{
self.cy = value
.into_optional_length()
.unwrap_or(GradientUnit::percent(50.0));
self
}
/// Sets the x coordinate of the start circle of gradient.
///
/// # Arguments
/// - `value`: The x coordinate value.
///
/// # Returns
/// - [`Self`]
pub fn fx<T>(mut self, value: T) -> Self
where
T: IntoOptionalLength<false, true>,
{
self.fx = value.into_optional_length();
self
}
/// Sets the y coordinate of the start circle of gradient.
///
/// # Arguments
/// - `value`: The y coordinate value.
///
/// # Returns
/// - [`Self`]
pub fn fy<T>(mut self, value: T) -> Self
where
T: IntoOptionalLength<false, true>,
{
self.fy = value.into_optional_length();
self
}
/// Sets the radius of the start circle.
///
/// # Arguments
/// - `value`: The radius value.
///
/// # Returns
/// - [`Self`]
pub fn fr<T>(mut self, value: T) -> Self
where
T: IntoOptionalLength<false, true>,
{
self.fr = value.into_optional_length().unwrap_or_default();
self
}
/// Adds a color stop to the gradient.
///
/// # Arguments
/// - `value`: The [`Stop`] value.
///
/// # Returns
/// - [`Self`]
pub fn stop<T>(mut self, value: T) -> Self
where
T: Into<Stop>,
{
self.stops.push(value.into());
self
}
// noinspection DuplicatedCode (used by linear gradient too)
/// Adds multiple color stops to the gradient.
///
/// # Arguments
/// - `stops`: Iterable collection of [`Stop`] values.
///
/// # Returns
/// - [`Self`]
pub fn stops<I, T>(mut self, stops: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<Stop>,
{
self.stops.extend(stops.into_iter().map(Into::into));
self
}
// noinspection DuplicatedCode (used by linear gradient too)
/// Sets the coordinate system used for resolving gradient geometry.
///
/// # Arguments
/// - `value`: The [`GradientUnits`] value.
///
/// # Returns
/// - [`Self`]
pub fn units<T>(mut self, value: T) -> Self
where
T: Into<Option<GradientUnits>>,
{
self.units = value.into().unwrap_or_default();
self
}
// noinspection DuplicatedCode (used by linear gradient too)
/// Applies a transformation to the gradient.
///
/// # Arguments
/// - `value`: The [`GradientTransform`] to apply.
///
/// # Returns
/// - [`Self`]
pub fn transform<T>(mut self, value: T) -> Self
where
T: Into<Option<GradientTransform>>,
{
self.transform = value.into().unwrap_or_default();
self
}
// noinspection DuplicatedCode (used by linear gradient too)
/// Sets the color interpolation space used by the gradient.
///
/// # Arguments
/// - `value`: The [`ColorInterpolation`] space to apply.
///
/// # Returns
/// - [`Self`]
pub fn color_interpolation<T>(mut self, value: T) -> Self
where
T: Into<Option<ColorInterpolation>>,
{
self.color_interpolation = value.into().unwrap_or(ColorInterpolation::SRgb);
self
}
}
impl ResourceIri for RadialGradient {}
impl IntoResources for RadialGradient {
fn into_resources(self) -> Vec<Resource> {
vec![self.into()]
}
}
impl Display for RadialGradient {
// noinspection DuplicatedCode (used by linear gradient too)
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let gradient = ElementWriter::new(f, "radialGradient")?
.attr("id", (self.iri(),))?
.attr_if("r", self.r, self.r != GradientUnit::percent(50.0))?
.attr_if("cx", self.cx, self.cx != GradientUnit::percent(50.0))?
.attr_if("cy", self.cy, self.cy != GradientUnit::percent(50.0))?
.attrs([("fx", self.fx), ("fy", self.fy)])?
.attr_if("fr", self.fr, !self.fr.is_zero())?
.attr_if("gradientUnits", (&self.units,), !self.units.is_default())?
.attr_if(
"color-interpolation",
(&self.color_interpolation,),
self.color_interpolation != ColorInterpolation::SRgb,
)?
.write(|out| self.transform.write(out, "gradientTransform"))?;
if self.stops.is_empty() {
gradient.close()
} else {
gradient
.content(|out| self.stops.iter().try_for_each(|stop| stop.fmt(out)))?
.close()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::assert_xml;
#[test]
fn renders_default_gradient() {
let lg = RadialGradient::new();
assert_xml(
lg.to_string(),
format!(r#"<radialGradient id="{}" />"#, lg.iri()),
);
}
#[test]
fn self_closes_when_no_stops() {
let lg = RadialGradient::new();
assert_xml(
lg.to_string(),
format!(r#"<radialGradient id="{}" />"#, lg.iri()),
);
}
#[test]
fn renders_stops() {
let lg = RadialGradient::new()
.stop(Stop::new().offset(0.0).color("#000"))
.stop(Stop::new().offset(1.0).color("#fff"));
assert_xml(
lg.to_string(),
format!(
r#"
<radialGradient id="{}">
<stop stop-color="rgb(0,0,0)" offset="0" />
<stop stop-color="rgb(255,255,255)" offset="1" />
</radialGradient>"#,
lg.iri()
),
);
}
#[test]
fn renders_with_attrs() {
let gradient_units = GradientUnits::UserSpaceOnUse;
let color_interpolation = ColorInterpolation::LinearRgb;
let lg = RadialGradient::new()
.r(25.0)
.cx(10.0)
.cy(15.0)
.fx(4.5)
.fy(6.5)
.fr(8.5)
.units(gradient_units)
.transform(GradientTransform::new().translate_x(10.0))
.color_interpolation(color_interpolation);
assert_xml(
lg.to_string(),
format!(
r#"
<radialGradient
id="{}"
r="25"
cx="10"
cy="15"
fx="4.5"
fy="6.5"
fr="8.5"
gradientUnits="{gradient_units}"
gradientTransform="matrix(1 0 0 1 10 0)"
color-interpolation="{color_interpolation}"
/>
"#,
lg.iri(),
),
);
}
}