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
#![deny(warnings)]

//! Provides convenient functions and macro to build dynamic css
#![doc = include_str!("../README.md")]

#[doc(hidden)]
pub use json;

pub mod prelude {
    pub use crate::*;
    pub use units::*;
}

pub mod style;
pub mod units;

/// Creates css using json notation
/// ```rust
/// use jss::jss;
/// let css = jss!(
///     ".layer": {
///         background_color: "red",
///         border: "1px solid green",
///     },
///
///     ".hide .layer": {
///         opacity: 0,
///     },
/// );
///
/// let expected =
///     r#".layer{background-color:red;border:1px solid green;}.hide .layer{opacity:0;}"#;
/// assert_eq!(expected, css);
/// ```
#[macro_export]
macro_rules! jss {
    ($($tokens:tt)+) => {
        {
            let json = $crate::json::object!($($tokens)*);
            $crate::process_css(None, &json, false)
        }
    };

}

/// Create css using jss macro with nice indentions
/// ```rust
/// let css = jss::jss_pretty!(
///     ".layer": {
///         background_color: "red",
///         border: "1px solid green",
///     },
///
///     ".hide .layer": {
///         opacity: 0,
///     },
/// );
///
/// let expected = "\
/// .layer {\
/// \n    background-color: red;\
/// \n    border: 1px solid green;\
/// \n}\
/// \n.hide .layer {\
/// \n    opacity: 0;\
/// \n}";
///         assert_eq!(expected, css);
/// ```
#[macro_export]
macro_rules! jss_pretty {
    ($($tokens:tt)+) => {
        {
            let json = $crate::json::object!($($tokens)*);
            $crate::process_css(None, &json, true)
        }
    };

}

/// Create a css string using json notation and use namespace on the class selectors
/// ```rust
/// use jss::units::percent;
/// let css = jss::jss_ns!("frame",
///     ".": {
///         display: "block",
///     },
///
///     ".layer": {
///         background_color: "red",
///         border: "1px solid green",
///     },
///
///     "@media screen and (max-width: 800px)": {
///       ".layer": {
///         width: percent(100),
///       }
///     },
///
///     ".hide .layer": {
///         opacity: 0,
///     },
/// );
///
/// let expected = r#".frame{display:block;}.frame__layer{background-color:red;border:1px solid green;}@media screen and (max-width: 800px){.frame__layer{width:100%;}}.frame__hide .frame__layer{opacity:0;}"#;
/// assert_eq!(expected, css);
/// ```
#[macro_export]
macro_rules! jss_ns {
    ($namespace: tt, $($tokens:tt)+) => {
        {
            let json = $crate::json::object!{$($tokens)*};
            $crate::process_css(Some($namespace), &json, false)
        }
    };
}

/// create css using jss with namespace macro with correct indentions
///  ```rust
/// let css = jss::jss_ns_pretty!("frame",
///     ".": {
///         display: "block",
///     },
///
///     ".layer": {
///         "background-color": "red",
///         border: "1px solid green",
///     },
///
///     ".hide .layer": {
///         opacity: 0,
///     },
/// );
///
/// let expected = "\
///     .frame {\
///    \n    display: block;\
///    \n}\
///    \n.frame__layer {\
///    \n    background-color: red;\
///    \n    border: 1px solid green;\
///    \n}\
///    \n.frame__hide .frame__layer {\
///    \n    opacity: 0;\
///    \n}";
/// println!("{}", css);
/// assert_eq!(expected, css);
/// ```
#[macro_export]
macro_rules! jss_ns_pretty {
    ($namespace: tt, $($tokens:tt)+) => {
        {
            let json = $crate::json::object!($($tokens)*);
            $crate::process_css(Some($namespace), &json, true)
        }
    };
}

/// process json to css transforming the selector
/// if class name is specified
pub fn process_css(namespace: Option<&str>, json: &json::JsonValue, use_indents: bool) -> String {
    process_css_selector_map(0, namespace, json, use_indents)
}

/// This assumes that the key objects in json are selectors and the value is an object with the
/// style names and their corresponding values
fn process_css_selector_map(
    indent: usize,
    namespace: Option<&str>,
    css_map: &json::JsonValue,
    use_indents: bool,
) -> String {
    let mut buffer = String::new();
    for (i, (classes, style_properties)) in css_map.entries().enumerate() {
        if i > 0 && use_indents {
            buffer += "\n";
        }
        if let Some(namespace) = &namespace {
            buffer += &format!(
                "{}{}",
                make_indent(indent, use_indents),
                selector_namespaced(namespace.to_string(), classes)
            );
        } else {
            buffer += &format!("{}{}", make_indent(indent, use_indents), classes);
        }
        if use_indents {
            buffer += " ";
        }
        buffer += "{";
        if use_indents {
            buffer += "\n";
        }
        buffer += &process_css_properties(
            indent,
            namespace,
            Some(classes),
            style_properties,
            use_indents,
        );
        buffer += &make_indent(indent, use_indents);
        buffer += "}";
    }
    buffer
}

/// This process the values used inside a css selector
pub fn process_css_properties(
    indent: usize,
    namespace: Option<&str>,
    _classes: Option<&str>,
    style_properties: &json::JsonValue,
    use_indents: bool,
) -> String {
    let mut buffer = String::new();

    for (prop, value) in style_properties.entries() {
        if value.is_object() {
            // recursive call to process_css_selector_map to support multiple layer of json object used in
            // complex css such as animation and media queries
            buffer +=
                &process_css_selector_map(indent + 1, namespace, style_properties, use_indents);
            if use_indents {
                buffer += "\n";
            }
        } else {
            let style_name = if let Some(style_name) = style::from_ident(prop) {
                style_name
            } else {
                let matched_property = style::match_name(prop);
                if let Some(matched_property) = matched_property {
                    matched_property
                } else {
                    // if strict, do a panic
                    #[cfg(feature = "strict")]
                    {
                        panic!(
                            "invalid style name: `{}` {}",
                            prop,
                            if let Some(classes) = _classes {
                                format!("in selector: `{}`", classes)
                            } else {
                                "".to_string()
                            }
                        );
                    }
                    // if not strict return the prop as is
                    #[cfg(not(feature = "strict"))]
                    {
                        prop
                    }
                }
            };
            let value_str = match value {
                json::JsonValue::String(s) => s.to_string(),
                json::JsonValue::Short(s) => s.to_string(),
                json::JsonValue::Number(v) => v.to_string(),
                json::JsonValue::Boolean(v) => v.to_string(),
                _ => {
                    panic!(
                        "supported values are String, Number or Bool only, found: {:?}",
                        value
                    )
                }
            };
            if use_indents {
                buffer += &format!(
                    "{}{}: {};",
                    make_indent(indent + 1, use_indents),
                    style_name,
                    value_str
                );
            } else {
                buffer += &format!(
                    "{}{}:{};",
                    make_indent(indent + 1, use_indents),
                    style_name,
                    value_str
                );
            }
            if use_indents {
                buffer += "\n";
            }
        }
    }

    buffer
}

/// convenient function to create indent
fn make_indent(n: usize, use_indents: bool) -> String {
    if use_indents {
        "    ".repeat(n)
    } else {
        String::from("")
    }
}

/// Prepend a namespace to the selector classes,
/// It does not affect other selectors such element selector, #id selector
/// example:
/// ```rust
/// use jss::selector_namespaced;
///
/// assert_eq!(".frame__text-anim", selector_namespaced("frame", ".text-anim"));
///
/// assert_eq!(
///     ".frame__hide .frame__corner",
///     selector_namespaced("frame", ".hide .corner")
/// );
///
/// assert_eq!(".frame__hide button", selector_namespaced("frame", ".hide button"));
/// assert_eq!(".frame__expand_corners,.frame__hovered", selector_namespaced("frame", ".expand_corners,.hovered"));
/// assert_eq!(".frame__expand_corners,.frame__hovered button .frame__highlight", selector_namespaced("frame", ".expand_corners,.hovered button .highlight"));
/// assert_eq!(".frame__expand_corners.frame__hovered button .frame__highlight", selector_namespaced("frame", ".expand_corners.hovered button .highlight"));
/// ```
pub fn selector_namespaced(namespace: impl ToString, selector_classes: impl ToString) -> String {
    let namespace = namespace.to_string();
    let selector_classes = selector_classes.to_string();
    let selector_trimmed = selector_classes.trim();

    if selector_trimmed == "." {
        format!(".{}", namespace)
    } else {
        selector_trimmed
            .split(" ")
            .map(|part| {
                let part = part.trim();
                if part.starts_with(".") {
                    let class_name = part.trim_start_matches(".");
                    class_name
                        .split(",")
                        .map(|cs_class| {
                            let cs_class = cs_class.trim_start_matches(".");
                            cs_class
                                .split(".")
                                .map(|dot_class| format!(".{}__{}", namespace, dot_class))
                                .collect::<Vec<_>>()
                                .join("")
                        })
                        .collect::<Vec<_>>()
                        .join(",")
                } else {
                    format!("{}", part)
                }
            })
            .collect::<Vec<_>>()
            .join(" ")
    }
}

/// Prepend namespace to this class name.
/// This is used in assigning the class name in an element.
///
/// #Examples:
/// ```rust
/// use jss::class_namespaced;
///
/// assert_eq!("frame__text-anim", class_namespaced("frame", "text-anim"));
/// ```
pub fn class_namespaced(namespace: impl ToString, class_names: impl ToString) -> String {
    let namespace = namespace.to_string();
    let class_names = class_names.to_string();
    let class_trimmed = class_names.trim();

    if class_trimmed.is_empty() {
        namespace
    } else {
        class_trimmed
            .split(" ")
            .map(|part| format!("{}__{}", namespace, part.trim()))
            .collect::<Vec<_>>()
            .join(" ")
    }
}

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

    #[test]
    fn test_selector_ns() {
        assert_eq!(".frame", selector_namespaced("frame", "."));
        assert_eq!(
            ".frame__hide .frame__corner",
            selector_namespaced("frame", ".hide .corner")
        );
    }
}