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

mod style_element {


use self::super::super::super::super::util::{concat_path, read_file};
use std::path::{PathBuf, is_separator as is_path_separator};
use self::super::{WrappedElement, ElementClass};
use self::super::super::super::super::Error;
use std::borrow::Cow;
use serde::de;
use std::fmt;


lazy_static! {
    static ref STYLE_LINK_HEAD: &'static str = include_str!("../../../../../../assets/element_wrappers/style/link.head").trim();
    static ref STYLE_LINK_FOOT: &'static str = include_str!("../../../../../../assets/element_wrappers/style/link.foot").trim_start();

    static ref STYLE_LITERAL_HEAD: &'static str = include_str!("../../../../../../assets/element_wrappers/style/literal.head").trim_start();
    static ref STYLE_LITERAL_FOOT: &'static str = include_str!("../../../../../../assets/element_wrappers/style/literal.foot");
}


/// A style specifier.
///
/// Can be a link or a literal, and a literal can be indirectly loaded from a file.
///
/// Consult the documentation for [`load()`](#fn.load) on handling filesystem interaxion.
///
/// # Deserialisation
///
/// There are two serialised forms, a verbose one:
///
/// ```
/// # extern crate toml;
/// # extern crate bloguen;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # use bloguen::ops::StyleElement;
/// #[derive(Deserialize, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
/// struct StyleContainer {
///     pub style: Vec<StyleElement>,
/// }
///
/// # fn main() {
/// let style_toml =
///     "[[style]]
///      class = 'link'
///      data = '//nabijaczleweli.xyz/kaschism/assets/column.css'
///
///      [[style]]
///      class = 'literal'
///      data = '.indented { text-indent: 1em; }'
///
///      [[style]]
///      class = 'file'
///      data = 'common.css'";
///
/// let StyleContainer { style } = toml::from_str(style_toml).unwrap();
/// assert_eq!(&style,
///            &[StyleElement::from_link("//nabijaczleweli.xyz/kaschism/assets/column.css"),
///              StyleElement::from_literal(".indented { text-indent: 1em; }"),
///              StyleElement::from_path("common.css")]);
/// # }
/// ```
///
/// And a compact one (the "literal" tag may be omitted if the content doesn't contain any colons):
///
/// ```
/// # extern crate toml;
/// # extern crate bloguen;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # use bloguen::ops::StyleElement;
/// #[derive(Deserialize, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
/// struct StyleContainer {
///     pub styles: Vec<StyleElement>,
/// }
///
/// # fn main() {
/// let styles_toml =
///     "styles = [
///          'link://nabijaczleweli.xyz/kaschism/assets/column.css',
///          'literal:.indented { text-indent: 1em; }',
///          'file:common.css',
///      ]";
///
/// let StyleContainer { styles } = toml::from_str(styles_toml).unwrap();
/// assert_eq!(&styles,
///            &[StyleElement::from_link("//nabijaczleweli.xyz/kaschism/assets/column.css"),
///              StyleElement::from_literal(".indented { text-indent: 1em; }"),
///              StyleElement::from_path("common.css")]);
/// # }
/// ```
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct StyleElement {
    class: ElementClass,
    data: Cow<'static, str>,
}

impl StyleElement {
    /// Create a style element linking to an external resource.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bloguen::ops::{WrappedElement, StyleElement};
    /// let lonk = StyleElement::from_link("//nabijaczleweli.xyz/kaschism/assets/column.css");
    /// assert_eq!(
    ///     format!("{}{}{}", lonk.head(), lonk.content(), lonk.foot()),
    ///     "<link href=\"//nabijaczleweli.xyz/kaschism/assets/column.css\" rel=\"stylesheet\" />\n")
    /// ```
    pub fn from_link<Dt: Into<Cow<'static, str>>>(link: Dt) -> StyleElement {
        StyleElement::from_link_impl(link.into())
    }

    fn from_link_impl(link: Cow<'static, str>) -> StyleElement {
        StyleElement {
            class: ElementClass::Link,
            data: link,
        }
    }

    /// Create a style element including the specified literal literally.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bloguen::ops::{WrappedElement, StyleElement};
    /// let lit = StyleElement::from_literal(".indented { text-indent: 1em; }");
    /// assert_eq!(
    ///     format!("{}{}{}", lit.head(), lit.content(), lit.foot()),
    ///     "<style type=\"text/css\">\n\n.indented { text-indent: 1em; }\n\n</style>\n")
    /// ```
    pub fn from_literal<Dt: Into<Cow<'static, str>>>(literal: Dt) -> StyleElement {
        StyleElement::from_literal_impl(literal.into())
    }

    fn from_literal_impl(literal: Cow<'static, str>) -> StyleElement {
        StyleElement {
            class: ElementClass::Literal,
            data: literal,
        }
    }

    /// Create a style element pointing to the specified relative path.
    ///
    /// Consult [`load()`](#fn.load) documentation for more data.
    ///
    /// # Examples
    ///
    /// Given `$ROOT/common.css` containing:
    ///
    /// ```css
    /// ul, ol {
    ///     margin-top: 0;
    ///     margin-bottom: 0;
    /// }
    ///
    /// a > i.fa {
    ///     color: black;
    /// }
    /// ```
    ///
    /// The following holds:
    ///
    /// ```
    /// # use bloguen::ops::{WrappedElement, StyleElement};
    /// # use std::fs::{self, File};
    /// # use std::env::temp_dir;
    /// # use std::io::Write;
    /// # use bloguen::Error;
    /// # let root = temp_dir().join("bloguen-doctest").join("ops-output-wrapped_element-style_element-from_path");
    /// # fs::create_dir_all(&root).unwrap();
    /// # File::create(root.join("common.css")).unwrap().write_all("\
    /// #     ul, ol {\n\
    /// #         margin-top: 0;\n\
    /// #         margin-bottom: 0;\n\
    /// #     }\n\
    /// #     \n\
    /// #     a > i.fa {\n\
    /// #         color: black;\n\
    /// #     }\n
    /// # ".as_bytes()).unwrap();
    /// # /*
    /// let root: PathBuf = /* obtained elsewhere */;
    /// # */
    ///
    /// let mut lit_p = StyleElement::from_path("common.css");
    /// assert_eq!(lit_p.load(&("$ROOT".to_string(), root.clone())), Ok(()));
    /// assert_eq!(format!("{}{}{}", lit_p.head(), lit_p.content(), lit_p.foot()),
    /// "<style type=\"text/css\">\n\n\
    ///      ul, ol {\n\
    ///          margin-top: 0;\n\
    ///          margin-bottom: 0;\n\
    ///      }\n\
    ///      \n\
    ///      a > i.fa {\n\
    ///          color: black;\n\
    ///      }\n\n\
    /// \n\n</style>\n");
    /// ```
    pub fn from_path<Dt: Into<Cow<'static, str>>>(path: Dt) -> StyleElement {
        StyleElement::from_path_impl(path.into())
    }

    fn from_path_impl(path: Cow<'static, str>) -> StyleElement {
        StyleElement {
            class: ElementClass::File,
            data: path.into(),
        }
    }

    /// Create a literal style element from the contents of the specified file.
    ///
    /// # Examples
    ///
    /// Given `$ROOT/common.css` containing:
    ///
    /// ```css
    /// ul, ol {
    ///     margin-top: 0;
    ///     margin-bottom: 0;
    /// }
    ///
    /// a > i.fa {
    ///     color: black;
    /// }
    /// ```
    ///
    /// The following holds:
    ///
    /// ```
    /// # use bloguen::ops::{WrappedElement, StyleElement};
    /// # use std::fs::{self, File};
    /// # use std::env::temp_dir;
    /// # use std::io::Write;
    /// # use bloguen::Error;
    /// # let root = temp_dir().join("bloguen-doctest").join("ops-output-wrapped_element-style_element-from_file");
    /// # fs::create_dir_all(&root).unwrap();
    /// # File::create(root.join("common.css")).unwrap().write_all("\
    /// #     ul, ol {\n\
    /// #         margin-top: 0;\n\
    /// #         margin-bottom: 0;\n\
    /// #     }\n\
    /// #     \n\
    /// #     a > i.fa {\n\
    /// #         color: black;\n\
    /// #     }\n
    /// # ".as_bytes()).unwrap();
    /// # /*
    /// let root: PathBuf = /* obtained elsewhere */;
    /// # */
    ///
    /// let lit_p = StyleElement::from_file(&("$ROOT/common.css".to_string(), root.join("common.css"))).unwrap();
    /// assert_eq!(format!("{}{}{}", lit_p.head(), lit_p.content(), lit_p.foot()),
    /// "<style type=\"text/css\">\n\n\
    ///      ul, ol {\n\
    ///          margin-top: 0;\n\
    ///          margin-bottom: 0;\n\
    ///      }\n\
    ///      \n\
    ///      a > i.fa {\n\
    ///          color: black;\n\
    ///      }\n\n\
    /// \n\n</style>\n");
    /// ```
    pub fn from_file(path: &(String, PathBuf)) -> Result<StyleElement, Error> {
        Ok(StyleElement {
            class: ElementClass::Literal,
            data: read_file(path, "literal style element from path")?.into(),
        })
    }

    /// Read data from the filesystem, if appropriate.
    ///
    /// Path elements are concatenated with the specified root, then [`read_file()`](../util/fn.read_file.html)d in, becoming
    /// literals.
    ///
    /// Non-path elements are unaffected.
    ///
    /// # Examples
    ///
    /// Given the following directory layout:
    ///
    /// ```plaintext
    /// $ROOT
    ///   common.css
    ///   assets
    ///     effects.css
    /// ```
    ///
    /// Given `$ROOT/common.css` containing:
    ///
    /// ```css
    /// ul, ol {
    ///     margin-top: 0;
    ///     margin-bottom: 0;
    /// }
    ///
    /// a > i.fa {
    ///     color: black;
    /// }
    /// ```
    ///
    /// Given `$ROOT/assets/effects.css` containing:
    ///
    /// ```css
    /// .ruby {
    ///     /* That's Ruby according to https://en.wikipedia.org/wiki/Ruby_(color). */
    ///     color: #E0115F;
    /// }
    /// ```
    ///
    /// The following holds:
    ///
    /// ```
    /// # use bloguen::ops::StyleElement;
    /// # use std::fs::{self, File};
    /// # use std::env::temp_dir;
    /// # use std::io::Write;
    /// # use bloguen::Error;
    /// # let root = temp_dir().join("bloguen-doctest").join("ops-output-wrapped_element-style_element-load");
    /// # fs::create_dir_all(root.join("assets")).unwrap();
    /// # File::create(root.join("common.css")).unwrap().write_all("\
    /// #     ul, ol {\n\
    /// #         margin-top: 0;\n\
    /// #         margin-bottom: 0;\n\
    /// #     }\n\
    /// #     \n\
    /// #     a > i.fa {\n\
    /// #         color: black;\n\
    /// #     }\n
    /// # ".as_bytes()).unwrap();
    /// # File::create(root.join("assets").join("effects.css")).unwrap().write_all(".ruby {\n\
    /// #     /* That's Ruby according to https://en.wikipedia.org/wiki/Ruby_(color). */\n\
    /// #     color: #E0115F;\n\
    /// # }\n
    /// # ".as_bytes()).unwrap();
    /// # /*
    /// let root: PathBuf = /* obtained elsewhere */;
    /// # */
    ///
    /// let mut elem = StyleElement::from_path("common.css");
    /// assert_eq!(elem.load(&("$ROOT".to_string(), root.clone())), Ok(()));
    /// assert_eq!(elem, StyleElement::from_literal("\
    ///     ul, ol {\n\
    ///         margin-top: 0;\n\
    ///         margin-bottom: 0;\n\
    ///     }\n\
    ///     \n\
    ///     a > i.fa {\n\
    ///         color: black;\n\
    ///     }\n
    /// "));
    ///
    /// let mut elem = StyleElement::from_path("assets/.././assets/effects.css");
    /// assert_eq!(elem.load(&("$ROOT".to_string(), root.clone())), Ok(()));
    /// assert_eq!(elem, StyleElement::from_literal("\
    ///    .ruby {\n\
    ///         /* That's Ruby according to https://en.wikipedia.org/wiki/Ruby_(color). */\n\
    ///         color: #E0115F;\n\
    ///     }\n
    /// "));
    ///
    /// let mut elem = StyleElement::from_path("assets/nonexistant.css");
    /// assert_eq!(elem.load(&("$ROOT".to_string(), root.clone())), Err(Error::FileNotFound {
    ///     who: "file style element",
    ///     path: "$ROOT/assets/nonexistant.css".into(),
    /// }));
    /// assert_eq!(elem, StyleElement::from_path("assets/nonexistant.css"));
    /// ```
    pub fn load(&mut self, base: &(String, PathBuf)) -> Result<(), Error> {
        if self.class == ElementClass::File {
            self.data = read_file(&(format!("{}{}{}",
                                            base.0,
                                            if !is_path_separator(base.0.as_bytes()[base.0.as_bytes().len() - 1] as char) &&
                                               !is_path_separator(self.data.as_bytes()[0] as char) {
                                                "/"
                                            } else {
                                                ""
                                            },
                                            self.data),
                                    concat_path(base.1.clone(), &self.data)),
                                  "file style element")
                ?
                .into();
            self.class = ElementClass::Literal;
        }

        Ok(())
    }
}

impl WrappedElement for StyleElement {
    fn head(&self) -> &str {
        match self.class {
            ElementClass::Link => &STYLE_LINK_HEAD,
            ElementClass::Literal => &STYLE_LITERAL_HEAD,
            ElementClass::File => "&lt;",
        }
    }

    fn content(&self) -> &str {
        &self.data
    }

    fn foot(&self) -> &str {
        match self.class {
            ElementClass::Link => &STYLE_LINK_FOOT,
            ElementClass::Literal => &STYLE_LITERAL_FOOT,
            ElementClass::File => "&gt;\n",
        }
    }
}


const STYLE_FIELDS: &[&str] = &["class", "data"];

struct StyleElementVisitor;

impl<'de> de::Visitor<'de> for StyleElementVisitor {
    type Value = StyleElement;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("struct StyleElement")
    }

    fn visit_str<E: de::Error>(self, v: &str) -> Result<StyleElement, E> {
        let mut itr = v.splitn(2, ":");
        Ok(match (itr.next(), itr.next()) {
            (Some(val), None) |
            (Some("literal"), Some(val)) => {
                StyleElement {
                    class: ElementClass::Literal,
                    data: val.to_string().into(),
                }
            }
            (Some("link"), Some(val)) => {
                StyleElement {
                    class: ElementClass::Link,
                    data: val.to_string().into(),
                }
            }
            (Some("file"), Some(val)) => {
                StyleElement {
                    class: ElementClass::File,
                    data: val.to_string().into(),
                }
            }

            (Some(tp), Some(_)) => return Err(de::Error::invalid_value(de::Unexpected::Str(tp), &r#""literal", "link", or "file""#)),
            (None, ..) => unreachable!(),
        })
    }

    fn visit_map<V: de::MapAccess<'de>>(self, mut map: V) -> Result<StyleElement, V::Error> {
        let mut class = None;
        let mut data = None;
        while let Some(key) = map.next_key()? {
            match key {
                "class" => {
                    if class.is_some() {
                        return Err(de::Error::duplicate_field("class"));
                    }
                    class = Some(match map.next_value()? {
                        "literal" => ElementClass::Literal,
                        "link" => ElementClass::Link,
                        "file" => ElementClass::File,
                        val => return Err(de::Error::invalid_value(de::Unexpected::Str(val), &r#""literal", "link", or "file""#)),
                    });
                }
                "data" => {
                    if data.is_some() {
                        return Err(de::Error::duplicate_field("data"));
                    }
                    data = Some(map.next_value()?);
                }
                _ => return Err(de::Error::unknown_field(key, STYLE_FIELDS)),
            }
        }

        Ok(StyleElement {
            class: class.ok_or_else(|| de::Error::missing_field("class"))?,
            data: data.ok_or_else(|| de::Error::missing_field("data"))?,
        })
    }
}

impl<'de> de::Deserialize<'de> for StyleElement {
    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_struct("StyleElement", STYLE_FIELDS, StyleElementVisitor)
    }
}


}