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

use std::fmt;

const SHADOW_KEYWORDS: [&str; 5] = ["none", "inherit", "initial", "revert", "unset"];

#[derive(Debug, PartialEq)]
enum Shadow<'a> {
    Raw([&'a str; 6]),
    Keyword(&'a str),
    Variable(&'a str),
    Shorthand1 {
        is_inset: bool,
        offset_x: &'a str,
        offset_y: &'a str,
        color: &'a str,
    },
    Shorthand2 {
        is_inset: bool,
        offset_x: &'a str,
        offset_y: &'a str,
        blur_radius: &'a str,
        color: &'a str,
    },
    Full {
        is_inset: bool,
        offset_x: &'a str,
        offset_y: &'a str,
        blur_radius: &'a str,
        spread_radius: &'a str,
        color: &'a str,
    },
}

impl<'a> Shadow<'a> {
    fn new_raw() -> Self {
        Self::Raw([""; 6])
    }

    /// Parse a real [`Shadow`] from a [`Shadow::Raw`] variant.
    fn parse(&self) -> Option<Self> {
        if let Shadow::Raw(shadow) = self {
            // Handle inset shadows
            let (is_inset, shadow) = if shadow[0].is_empty() {
                (false, &shadow[..])
            } else if shadow[0] == "inset" {
                (true, &shadow[1..])
            } else {
                (false, &shadow[..])
            };

            // Check the number of parts
            if shadow.is_empty()
                && ((is_inset && shadow.len() > 6) || (!is_inset && shadow.len() > 5))
            {
                return None;
            }

            let len = shadow.iter().position(|p| p.is_empty()).unwrap_or(6);
            if len == 1 {
                // Keyword value
                if SHADOW_KEYWORDS.contains(&shadow[0]) {
                    Some(Shadow::Keyword(shadow[0]))
                } else if is_matching_var(shadow[0]) {
                    Some(Shadow::Variable(shadow[0]))
                } else {
                    None
                }
            } else if len == 3 {
                // Shorthand 1: offset-x | offset-y | color
                if is_matching_length(shadow[0])
                    && is_matching_length(shadow[1])
                    && is_matching_color(shadow[2])
                {
                    Some(Shadow::Shorthand1 {
                        is_inset,
                        offset_x: shadow[0],
                        offset_y: shadow[1],
                        color: shadow[2],
                    })
                } else {
                    None
                }
            } else if len == 4 {
                // Shorthand 2: offset-x | offset-y | blur-radius | color
                if is_matching_length(shadow[0])
                    && is_matching_length(shadow[1])
                    && is_matching_length(shadow[2])
                    && is_matching_color(shadow[3])
                {
                    Some(Shadow::Shorthand2 {
                        is_inset,
                        offset_x: shadow[0],
                        offset_y: shadow[1],
                        blur_radius: shadow[2],
                        color: shadow[3],
                    })
                } else {
                    None
                }
            } else if len == 5 {
                // Full: offset-x | offset-y | blur-radius | spread-radius | color
                if is_matching_length(shadow[0])
                    && is_matching_length(shadow[1])
                    && is_matching_length(shadow[2])
                    && is_matching_length(shadow[3])
                    && is_matching_color(shadow[4])
                {
                    Some(Shadow::Full {
                        is_inset,
                        offset_x: shadow[0],
                        offset_y: shadow[1],
                        blur_radius: shadow[2],
                        spread_radius: shadow[3],
                        color: shadow[4],
                    })
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        }
    }
}

impl<'a> fmt::Display for Shadow<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Shadow::Raw(s) => write!(f, "{}", s.join(" ")),
            Shadow::Keyword(keyword) => write!(f, "{keyword}"),
            Shadow::Variable(variable) => write!(f, "{variable}"),
            Shadow::Shorthand1 {
                is_inset,
                offset_x,
                offset_y,
                color,
            } => write!(
                f,
                "{}{offset_x} {offset_y} {color}",
                if *is_inset { "inset " } else { "" }
            ),
            Shadow::Shorthand2 {
                is_inset,
                offset_x,
                offset_y,
                blur_radius,
                color,
            } => write!(
                f,
                "{}{offset_x} {offset_y} {blur_radius} {color}",
                if *is_inset { "inset " } else { "" }
            ),
            Shadow::Full {
                is_inset,
                offset_x,
                offset_y,
                blur_radius,
                spread_radius,
                color,
            } => write!(
                f,
                "{}{offset_x} {offset_y} {blur_radius} {spread_radius} {color}",
                if *is_inset { "inset " } else { "" }
            ),
        }
    }
}

/// A list of shadows, used in the [`box-shadow`](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow) CSS property.
#[derive(Debug, PartialEq)]
pub struct ShadowList<'a>(Vec<Shadow<'a>>);

impl<'a> ShadowList<'a> {
    /// Parse an arbitrary string into a [`ShadowList`].
    ///
    /// # Example
    ///
    /// ```
    /// use encre_css::utils::shadow::ShadowList;
    /// assert_eq!(ShadowList::parse("10px 20px 30px 40px rgb(12 12 12)").unwrap().to_string(), "10px 20px 30px 40px rgb(12 12 12)".to_string());
    /// assert_eq!(ShadowList::parse("1px 2px 3px 4px"), None);
    /// ```
    pub fn parse(value: &'a str) -> Option<Self> {
        let mut parenthesis_level = 0;
        let mut last_index = 0;
        let mut shadows = vec![Shadow::new_raw()];

        for (ch_index, ch) in value.char_indices() {
            match ch {
                '(' => {
                    parenthesis_level += 1;
                }
                ')' => {
                    parenthesis_level -= 1;
                }
                ' ' if parenthesis_level == 0 => {
                    let Shadow::Raw(shadow) = shadows.last_mut()? else {
                        // Shadow already parsed but a space was encountered
                        return None;
                    };

                    if !value[last_index..ch_index].is_empty() {
                        // Find the index of the first free part
                        let index = shadow.iter().position(|p| p.is_empty()).unwrap_or(5);

                        // Insert the part
                        shadow[index] = &value[last_index..ch_index];
                    }

                    // Update the index (and ignore the space)
                    last_index = ch_index + 1;
                }
                ',' if parenthesis_level == 0 => {
                    // Add the last part (not suffixed by `_`)
                    let Shadow::Raw(shadow) = shadows.last_mut()? else {
                        // Shadow already parsed but a space was encountered
                        return None;
                    };

                    // Find the index of the first free part
                    let index = shadow.iter().position(|p| p.is_empty()).unwrap_or(5);

                    // Insert the part
                    shadow[index] = &value[last_index..ch_index];

                    // Ignore the shadow if it is empty
                    if !shadow.iter().all(|p| p.is_empty()) {
                        // Parse the shadow
                        let parsed_shadow = shadows.last()?.parse()?;
                        *shadows.last_mut()? = parsed_shadow;

                        // Start the next shadow
                        shadows.push(Shadow::new_raw());
                    }

                    // Update the index (and ignore the comma)
                    last_index = ch_index + 1;
                }
                _ => (),
            }
        }

        // Add the last part (not suffixed by `,`)
        if last_index != value.len() - 1 {
            // Find the index of the first free part
            let Shadow::Raw(shadow) = shadows.last_mut()? else {
                return None;
            };
            let index = shadow.iter().position(|p| p.is_empty()).unwrap_or(5);

            // Insert the part
            shadow[index] = &value[last_index..value.len()];

            // Parse the shadow
            let parsed_shadow = shadows.last()?.parse()?;
            *shadows.last_mut()? = parsed_shadow;
        }

        Some(Self(shadows))
    }

    /// Replace the color of all shadows with the color given as the first argument.
    pub fn replace_all_colors(&mut self, new_color: &'a str) {
        self.0.iter_mut().for_each(|shadow| match shadow {
            Shadow::Shorthand1 { ref mut color, .. }
            | Shadow::Shorthand2 { ref mut color, .. }
            | Shadow::Full { ref mut color, .. } => *color = new_color,
            _ => (),
        });
    }
}

impl<'a> fmt::Display for ShadowList<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (i, v) in self.0.iter().enumerate() {
            write!(f, "{}{}", v, if i == self.0.len() - 1 { "" } else { "," })?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_shadow_test() {
        let shadow = "20px 35px 60px -15px rgba(0,0,0,0.3),0 72px rgba(0,2,42,0.2),inset 23px 42em 42px rgba(255,0,0,1)";
        let result = ShadowList::parse(shadow).unwrap();
        assert_eq!(
            result,
            ShadowList(vec![
                Shadow::Full {
                    is_inset: false,
                    offset_x: "20px",
                    offset_y: "35px",
                    blur_radius: "60px",
                    spread_radius: "-15px",
                    color: "rgba(0,0,0,0.3)",
                },
                Shadow::Shorthand1 {
                    is_inset: false,
                    offset_x: "0",
                    offset_y: "72px",
                    color: "rgba(0,2,42,0.2)",
                },
                Shadow::Shorthand2 {
                    is_inset: true,
                    offset_x: "23px",
                    offset_y: "42em",
                    blur_radius: "42px",
                    color: "rgba(255,0,0,1)",
                }
            ])
        );

        assert_eq!(
            ShadowList::parse("var(--a, 0 0 1px rgb(0, 0, 0)),1px 2px 3rem rgb(0, 0, 0)").unwrap(),
            ShadowList(vec![
                Shadow::Variable("var(--a, 0 0 1px rgb(0, 0, 0))"),
                Shadow::Shorthand2 {
                    is_inset: false,
                    offset_x: "1px",
                    offset_y: "2px",
                    blur_radius: "3rem",
                    color: "rgb(0, 0, 0)",
                },
            ])
        );

        assert_eq!(
            ShadowList::parse("none").unwrap(),
            ShadowList(vec![Shadow::Keyword("none")])
        );
    }

    #[test]
    fn format_shadow() {
        let shadow = "20px 35px 60px -15px rgba(0,0,0,0.3),0 72px rgba(0,2,42,0.2),inset 23px 42em rgba(255,0,0,1)";
        let result = ShadowList::parse(shadow).unwrap();
        assert_eq!(&result.to_string(), shadow);
    }
}