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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
// Authors: Robert Lopez

mod constants;
pub mod error;
#[cfg(test)]
mod tests;

use crate::error::WasmCssError;
use constants::VALID_CSS_KEYS;
use std::collections::{HashMap, VecDeque};
use web_sys::window;

/// Arguments: `$format:expr $(, $arg:expr)*` *(Formatter)*
///
/// ---
///
/// Builds a `crate::error::WasmCssError` via `format!`
macro_rules! format_error {
    ($format:expr $(, $arg:expr)*) => {
        $crate::error::WasmCssError(vec![format!($format $(, $arg)*)])
    };
}

/// Represents a CSS `Style`
#[derive(Debug, Clone)]
pub struct Style {
    pub css: String,
    pub class: String,
    pub global: bool,
    pub effects: HashMap<String, String>,
    pub components: HashMap<String, String>,
}

impl Style {
    /// Parse a effect into a ID and value
    ///
    /// Example:
    ///
    /// ```
    /// &:hover { font-size: 10rem; }
    ///
    /// ID = &:hover
    ///
    /// VALUE = { font-size: 10rem; }
    ///
    /// ```
    fn _parse_effect<E: Into<String>>(effect: E) -> (String, String) {
        let css = effect.into();
        let mut id_chars = vec![];
        let mut value_chars = vec![];

        let mut css_chars_queue = VecDeque::from_iter(css.trim().chars());

        // Parse ID
        let mut previous_char = None;
        while let Some(char) = css_chars_queue.pop_front() {
            if char == '\n' {
                continue;
            }

            if char == '{' {
                break;
            }

            if let Some(previous_char) = previous_char {
                if char == ' ' && previous_char == ' ' {
                    continue;
                }
            }

            id_chars.push(char.clone());
            previous_char = Some(char);
        }

        // Parse Value
        let mut previous_char = None;
        while let Some(char) = css_chars_queue.pop_front() {
            if char == '\n' {
                continue;
            }

            if let Some(previous_char) = previous_char {
                if char == ' ' && previous_char == ' ' {
                    continue;
                }
            }

            value_chars.push(char.clone());
            previous_char = Some(char);
        }
        value_chars.pop();

        let id = id_chars.into_iter().collect::<String>().trim().to_string();
        let value = value_chars
            .into_iter()
            .collect::<String>()
            .trim()
            .to_string();

        (id, value)
    }

    /// Parse raw `css` string into `Style`
    ///
    /// TODO: Validation beyond invalid keys or key: value format
    fn _build(css: String, class: String, global: bool) -> Self {
        let lines = css.split(";").collect::<Vec<&str>>();
        let mut filtered_css = format!("{}{} {{ ", if global { "" } else { "." }, class);

        let mut components = HashMap::new();

        for line in lines {
            let line = line.trim();
            let component_split = line.split(":").collect::<Vec<&str>>();

            if component_split.len() != 2 || !VALID_CSS_KEYS.contains(&component_split[0]) {
                continue;
            }

            components.insert(
                component_split[0].to_string(),
                component_split[1].trim().to_string(),
            );

            filtered_css += line;
            filtered_css += "; ";
        }

        filtered_css += "}";

        Self {
            css: filtered_css,
            class,
            global,
            effects: HashMap::new(),
            components,
        }
    }

    fn _build_css_from_components(&self) -> String {
        let mut css = format!("{}{} {{ ", if self.global { "" } else { "." }, self.class);

        for (key, value) in self.components.iter() {
            css += key;
            css += ": ";
            css += value;
            css += "; ";
        }

        for (key, value) in self.effects.iter() {
            css += key;
            css += " { ";
            css += value;
            css += " } ";
        }

        css += "}";
        css
    }

    fn _generate_class_uuid() -> Result<String, WasmCssError> {
        let window = window().ok_or(format_error!("Failed to obtain Window object"))?;
        let crypto = window
            .crypto()
            .map_err(|_| format_error!("Failed to obtain Crypto object"))?;

        let mut uuid = crypto.random_uuid();
        unsafe {
            uuid.as_bytes_mut()[0] = b'z';
        }

        Ok(uuid)
    }

    fn _update_class(&self) -> Result<(), WasmCssError> {
        let window = window().ok_or(format_error!("Failed to obtain Window object"))?;
        let document = window
            .document()
            .ok_or(format_error!("Failed to obtain Document object"))?;

        let head = document
            .head()
            .ok_or(format_error!("Failed to obtain HtmlHeadElement object"))?;

        if let Some(existing_style) = document.get_element_by_id(&self.class) {
            existing_style.set_id(&self.class);
            existing_style.set_class_name(&self.class);
            existing_style.set_inner_html(&self.css);
        }

        let style = document
            .create_element("style")
            .map_err(|_| format_error!("Failed to create new style Element"))?;

        style.set_id(&self.class);
        style.set_class_name(&self.class);
        style.set_inner_html(&self.css);

        head.append_child(&style)
            .map_err(|_| format_error!("Failed to add new style Element to HtmlHeadElement"))?;

        Ok(())
    }

    /// Construct a `Style` from a CSS string
    ///
    /// `global` simply removes the `.` from the class name, making
    /// it a global style, and requires you provide a `target` E.x. "html"
    ///
    /// - See `style!` and `global_style!` for built-in formatting
    ///
    /// - Generates random class name if one is not provided
    ///
    /// - Returns `WasmCssError` if unable to locate Crypto when generating uuid
    ///
    /// - Returns `WasmCssError` if unable to locate Document/Window/Head
    ///
    /// - Returns `WasmCssError` if `global` is true and `target` is `None`
    ///
    /// ---
    ///
    /// Example Usage:
    /// ```
    ///
    /// let style: Style = Style::new(
    ///     "
    ///         gap: 10rem;
    ///         display: flex;
    ///         flex-direction: column;
    ///     ",
    ///     None,
    /// )?;
    /// ```
    pub fn new(css: String, target: Option<String>, global: bool) -> Result<Self, WasmCssError> {
        if target.is_none() && global {
            return Err(format_error!("Global cannot be provided with no target"));
        }

        let class = target.unwrap_or(Self::_generate_class_uuid()?);
        let style = Self::_build(css, class, global);
        style._update_class()?;

        Ok(style)
    }

    /// Returns this `Style`s class name
    pub fn class(&self) -> &String {
        &self.class
    }

    /// Append another `Style` to this one, overwriting any fields on
    /// `self` matching with `source`, or adding them if they did not
    /// previously exist, updating the Style
    ///
    /// ---
    ///
    /// Example Usage:
    /// ```
    ///
    /// let mut style_one = style!("color: red; font-size: 10rem;")?;
    ///
    /// let style_two = style!("font-size: 30rem; background-color: red;")?;
    ///
    /// style_one.append(&style_two)?;
    ///
    /// // style_one.css: "color: red; font-size: 30rem; background-color: red;"
    /// ```
    pub fn append(&mut self, source: &Style) -> Result<(), WasmCssError> {
        self.components
            .extend(source.components.clone().into_iter());
        self.css = self._build_css_from_components();
        self._update_class()?;

        Ok(())
    }

    /// Insert a new CSS line into the `Style`
    ///
    /// - Skips invalid keys
    ///
    /// ---
    ///
    /// Example Usage:
    /// ```
    ///
    /// let mut style = style!("color: red; font-size: 10rem;")?;
    ///
    /// style.insert("font-weight", "bold");
    /// ```
    pub fn insert<V: Into<String>>(&mut self, key: &str, value: V) -> Result<(), WasmCssError> {
        if !VALID_CSS_KEYS.contains(&key) {
            return Ok(());
        }

        self.components.insert(key.into(), value.into());
        self.css = self._build_css_from_components();
        self._update_class()?;

        Ok(())
    }

    /// Remove a CSS line from `Style`
    ///
    /// ---
    ///
    /// Example Usage:
    /// ```
    ///
    /// let mut style = style!("color: red; font-size: 10rem;")?;
    ///
    /// style.remove("color", "red")?;
    /// ```
    pub fn remove(&mut self, key: &str) -> Result<(), WasmCssError> {
        self.components.remove(key);
        self.css = self._build_css_from_components();
        self._update_class()?;

        Ok(())
    }

    /// Insert many CSS lines into the `Style`
    ///
    /// - Skips invalid keys
    ///
    /// ---
    ///
    /// Example Usage:
    /// ```
    ///
    /// let mut style = style!("color: red; font-size: 10rem;")?;
    ///
    /// style.insert_many(vec![
    ///     ("font-weight", "bold"),
    ///     ("background-color", "red")
    /// ])?;
    /// ```
    pub fn insert_many<V: Into<String>>(
        &mut self,
        components: Vec<(&str, V)>,
    ) -> Result<(), WasmCssError> {
        for (key, value) in components {
            if !VALID_CSS_KEYS.contains(&key) {
                continue;
            }

            self.components.insert(key.into(), value.into());
        }

        self.css = self._build_css_from_components();
        self._update_class()?;

        Ok(())
    }

    /// Remove CSS lines from `Style`
    ///
    /// ---
    ///
    /// Example Usage:
    /// ```
    ///
    /// let mut style = style!("color: red; font-size: 10rem;")?;
    ///
    /// style.remove("color", "red")?;
    /// ```
    pub fn remove_many(&mut self, keys: Vec<&str>) -> Result<(), WasmCssError> {
        for key in keys {
            self.components.remove(key);
        }

        self.css = self._build_css_from_components();
        self._update_class()?;

        Ok(())
    }

    /// Add a `effect` to the `Style`
    ///
    /// Effect meaning sub-components to a class like
    /// MediaQuery, Hover, Etc.
    ///
    /// The `ID` of the effect becomes its tag component.
    ///
    /// ---
    ///
    /// Example Usage:
    /// ```
    ///
    /// let mut style = style!("color: red;")?;
    ///
    /// // Effect ID = '&:hover'
    /// style.insert_effect("&:hover { font-size: 10rem; }")?;
    /// ```
    pub fn insert_effect<E: Into<String>>(&mut self, effect: E) -> Result<(), WasmCssError> {
        let (id, value) = Self::_parse_effect(effect);
        self.effects.insert(id, value);
        self.css = self._build_css_from_components();
        self._update_class()?;

        Ok(())
    }

    /// Remove a `effect` from the `Style`
    ///
    /// Effect meaning sub-components to a class like
    /// MediaQuery, Hover, Etc.
    ///
    /// The `ID` or name of the added effect is just its `tag`.
    ///
    /// ---
    ///
    /// Example Usage:
    /// ```
    ///
    /// let mut style = style!("color: red;")?;
    ///
    /// // Effect ID = '&:hover'
    /// style.insert_effect("&:hover { font-size: 10rem; };")?;
    ///
    /// style.remove_effect("&:hover")?;
    /// ```
    pub fn remove_effect(&mut self, id: &str) -> Result<(), WasmCssError> {
        self.effects.remove(id);
        self.css = self._build_css_from_components();
        self._update_class()?;

        Ok(())
    }

    /// Add many `effect`s to the `Style`
    ///
    /// Effect meaning sub-components to a class like
    /// MediaQuery, Hover, Etc.
    ///
    /// The `ID` of the effect becomes its tag component.
    ///
    /// ---
    ///
    /// Example Usage:
    /// ```
    ///
    /// let mut style = style!("color: red;")?;
    ///
    /// // Effect IDs = '&:hover' & '@media (max-width: 400px)'
    /// style.insert_effect_many(vec![
    ///     "&:hover { font-size: 10rem; }",
    ///     "@media (max-width: 400px) { color: blue; }"
    /// ])?;
    /// ```
    pub fn insert_effect_many<E: Into<String>>(
        &mut self,
        effects: Vec<E>,
    ) -> Result<(), WasmCssError> {
        for effect in effects {
            let (id, value) = Self::_parse_effect(effect);
            self.effects.insert(id, value);
        }

        self.css = self._build_css_from_components();
        self._update_class()?;

        Ok(())
    }

    /// Remove many `effect`s from the `Style`
    ///
    /// Effect meaning sub-components to a class like
    /// MediaQuery, Hover, Etc.
    ///
    /// The `ID` of the effect becomes its tag component.
    ///
    /// ---
    ///
    /// Example Usage:
    /// ```
    ///
    /// let mut style = style!("color: red;")?;
    ///
    /// // Effect IDs = '&:hover' & '@media (max-width: 400px)'
    /// style.insert_effect_many(vec![
    ///     "&:hover { font-size: 10rem; }",
    ///     "@media (max-width: 400px) { color: blue; }"
    /// ])?;
    ///
    /// style.remove_effect_many(vec!["&:hover", "@media (max-width: 400px)"])?;
    /// ```
    pub fn remove_effect_many(&mut self, effect_ids: Vec<&str>) -> Result<(), WasmCssError> {
        for effect_id in effect_ids {
            self.effects.remove(effect_id);
        }

        self.css = self._build_css_from_components();
        self._update_class()?;

        Ok(())
    }
}

/// Construct a `Style` from a CSS string with formatting
///
/// - Returns `WasmCssError` if unable to locate Crypto when generating uuid
///
/// - Returns `WasmCssError` if unable to locate Document/Window/Head
///
/// ---
///
/// ```
///
/// style!(css: &str) -> Result<Style, WasmCssError>
/// ```
///
/// ---
///
/// Example Usage:
/// ```
///
/// style!(
///     "
///         gap: {}rem;
///         display: flex;
///         flex-direction: column;
///     ",
///     gap_size
/// )?;
/// ```
#[macro_export]
macro_rules! style {
    ($css:expr $(, $arg:expr)*) => {{
        let formatted_css = format!($css $(, $arg)*);

        $crate::Style::new(formatted_css, None, false)
    }};
}

/// Construct a `Style` from a CSS string with formatting
///
/// - Returns `WasmCssError` if unable to locate Crypto when generating uuid
///
/// - Returns `WasmCssError` if unable to locate Document/Window/Head
///
/// ---
///
/// ```
///
/// named_style!(class_name: Into<String>, css: &str) -> Result<Style, WasmCssError>
/// ```
///
/// ---
///
/// Example Usage:
///
/// ```
///
/// named_style!(
///     "my_class",
///     "
///         gap: {}rem;
///         display: flex;
///         flex-direction: column;
///     ",
///     gap_size
/// )?;
/// ```
#[macro_export]
macro_rules! named_style {
    ($name:expr, $css:expr $(, $arg:expr)*) => {{
        let formatted_css = format!($css $(, $arg)*);

        $crate::Style::new(formatted_css, Some($name.into()), false)
    }};
}

/// Construct a global `Style` from a CSS string with formatting
///
/// - Returns `WasmCssError` if unable to locate Crypto when generating uuid
///
/// - Returns `WasmCssError` if unable to locate Document/Window/Head
///
/// ---
///
/// ```
///
/// global_style!(target: Into<String>, css: &str) -> Result<Style, WasmCssError>
/// ```
///
/// ---
///
/// Example Usage:
/// ```
///
/// global_style!(
///     "html",
///     "
///         gap: {}rem;
///         display: flex;
///         flex-direction: column;
///     ",
///     gap_size
/// )?;
/// ```
#[macro_export]
macro_rules! global_style {
    ($target:expr, $css:expr $(, $arg:expr)*) => {{
        let formatted_css = format!($css $(, $arg)*);

        $crate::Style::new(formatted_css, Some($target.into()), true)
    }};
}

/// Add a `effect`(s) to the `Style` with formatting
///
/// Effect meaning sub-components to a class like
/// MediaQuery, Hover, Etc.
///
/// The `ID` of the effect becomes its tag component.
///
/// ---
///
/// ```
///
/// add_effects!(style: &mut Style, effect formats) -> Result<(), WasmCssError>
/// ```
///
/// ---
///
/// Example Usage:
/// ```
///
/// let mut style = style!("color: red;")?;
///
/// add_effects!(
///     &mut style,
///     (" // Effect ID = &:hover
///         &:hover {{
///             color: black;
///         }}
///     "),
///     (" // Effect ID = @media (max-width: 400px)
///         @media (max-width: {}px) {{
///             font-size: 10rem;
///         }}
///     ",
///         400
///     )
/// )?;
/// ```
#[macro_export]
macro_rules! add_effects {
    ($style:expr,  $(($fmt:expr $(, $($arg:expr)*)?)),*) => {{
        let mut formatted_effects = Vec::new();
        $(
            formatted_effects.push(format!($fmt $(, $($arg)*)?));
        )*

        $style.insert_effect_many(formatted_effects)
    }}
}