[][src]Struct bloguen::ops::ScriptElement

pub struct ScriptElement { /* fields omitted */ }

A script specifier.

Can be a link or a literal, and a literal can be indirectly loaded from a file.

Consult the documentation for load() on handling filesystem interaxion.

Deserialisation

There are two serialised forms, a verbose one:

#[derive(Deserialize, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
struct ScriptContainer {
    pub script: Vec<ScriptElement>,
}

let script_toml =
    "[[script]]
     class = 'link'
     data = '/content/assets/syllable.js'

     [[script]]
     class = 'literal'
     data = 'document.getElementById(\"title\").innerText = \"Наган\";'

     [[script]]
     class = 'file'
     data = 'MathJax-config.js'";

let ScriptContainer { script } = toml::from_str(script_toml).unwrap();
assert_eq!(&script,
           &[ScriptElement::from_link("/content/assets/syllable.js"),
             ScriptElement::from_literal("document.getElementById(\"title\").innerText = \"Наган\";"),
             ScriptElement::from_path("MathJax-config.js")]);

And a compact one (the "literal" tag may be omitted if the content doesn't contain any colons):

#[derive(Deserialize, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
struct ScriptContainer {
    pub scripts: Vec<ScriptElement>,
}

let scripts_toml =
    "scripts = [
         'link:/content/assets/syllable.js',
         'literal:document.getElementById(\"title\").innerText = \"Наган\";',
         'file:MathJax-config.js',
     ]";

let ScriptContainer { scripts } = toml::from_str(scripts_toml).unwrap();
assert_eq!(&scripts,
           &[ScriptElement::from_link("/content/assets/syllable.js"),
             ScriptElement::from_literal("document.getElementById(\"title\").innerText = \"Наган\";"),
             ScriptElement::from_path("MathJax-config.js")]);

Methods

impl ScriptElement[src]

Create a script element linking to an external resource.

Examples

let lonk = ScriptElement::from_link("/content/assets/syllable.js");
assert_eq!(
    format!("{}{}{}", lonk.head(), lonk.content(), lonk.foot()),
    "<script type=\"text/javascript\" src=\"/content/assets/syllable.js\"></script>\n")

pub fn from_literal<Dt: Into<Cow<'static, str>>>(literal: Dt) -> ScriptElement[src]

Create a script element including the specified literal literally.

Examples

let lit = ScriptElement::from_literal("document.getElementById(\"title\").innerText = \"Наган\";");
assert_eq!(
    format!("{}{}{}", lit.head(), lit.content(), lit.foot()),
    "<script type=\"text/javascript\">\n\ndocument.getElementById(\"title\").innerText = \"Наган\";\n\n</script>\n")

pub fn from_path<Dt: Into<Cow<'static, str>>>(path: Dt) -> ScriptElement[src]

Create a script element pointing to the specified relative path.

Consult load() documentation for more data.

Examples

Given $ROOT/MathJax-config.js containing:

MathJax.Hub.Config({
  jax: ["input/AsciiMath", "output/HTML-CSS"],
  extensions: ["asciimath2jax.js"],
  asciimath2jax: {
    delimiters: [['[​[​', '​]​]']],
    preview: "[[maths]]"
  },
  AsciiMath: {
    decimal: "."
  },
  "HTML-CSS": {
    undefinedFamily: "STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif"
  }
});

The following holds:

let root: PathBuf = /* obtained elsewhere */;

let mut lit_p = ScriptElement::from_path("MathJax-config.js");
assert_eq!(lit_p.load(&("$ROOT".to_string(), root.clone())), Ok(()));
assert_eq!(format!("{}{}{}", lit_p.head(), lit_p.content(), lit_p.foot()),
"<script type=\"text/javascript\">\n\n\
    MathJax.Hub.Config({\n\
      jax: [\"input/AsciiMath\", \"output/HTML-CSS\"],\n\
      extensions: [\"asciimath2jax.js\"],\n\
      asciimath2jax: {\n\
        delimiters: [['[​[​', '​]​]']],\n\
        preview: \"[[maths]]\"\n\
      },\n\
      AsciiMath: {\n\
        decimal: \".\"\n\
      },\n\
      \"HTML-CSS\": {\n\
        undefinedFamily: \"STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif\"\n\
      }\n\
    });\n\
\n\n</script>\n");

pub fn from_file(path: &(String, PathBuf)) -> Result<ScriptElement, Error>[src]

Create a literal script element from the contents of the specified file.

Examples

Given $ROOT/MathJax-config.js containing:

MathJax.Hub.Config({
  jax: ["input/AsciiMath", "output/HTML-CSS"],
  extensions: ["asciimath2jax.js"],
  asciimath2jax: {
    delimiters: [['[​[​', '​]​]']],
    preview: "[[maths]]"
  },
  AsciiMath: {
    decimal: "."
  },
  "HTML-CSS": {
    undefinedFamily: "STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif"
  }
});

The following holds:

let root: PathBuf = /* obtained elsewhere */;

let lit_p = ScriptElement::from_file(&("$ROOT/MathJax-config.js".to_string(), root.join("MathJax-config.js"))).unwrap();
assert_eq!(format!("{}{}{}", lit_p.head(), lit_p.content(), lit_p.foot()),
"<script type=\"text/javascript\">\n\n\
    MathJax.Hub.Config({\n\
      jax: [\"input/AsciiMath\", \"output/HTML-CSS\"],\n\
      extensions: [\"asciimath2jax.js\"],\n\
      asciimath2jax: {\n\
        delimiters: [['[​[​', '​]​]']],\n\
        preview: \"[[maths]]\"\n\
      },\n\
      AsciiMath: {\n\
        decimal: \".\"\n\
      },\n\
      \"HTML-CSS\": {\n\
        undefinedFamily: \"STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif\"\n\
      }\n\
    });\n\
\n\n</script>\n");

pub fn load(&mut self, base: &(String, PathBuf)) -> Result<(), Error>[src]

Read data from the filesystem, if appropriate.

Path elements are concatenated with the specified root, then read_file()d in, becoming literals.

Non-path elements are unaffected.

Examples

Given the following directory layout:

$ROOT
  MathJax-config.js
  assets
    octicons.js

Given $ROOT/MathJax-config.js containing:

MathJax.Hub.Config({
  jax: ["input/AsciiMath", "output/HTML-CSS"],
  extensions: ["asciimath2jax.js"],
  asciimath2jax: {
    delimiters: [['[​[​', '​]​]']],
    preview: "[[maths]]"
  },
  AsciiMath: {
    decimal: "."
  },
  "HTML-CSS": {
    undefinedFamily: "STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif"
  }
});

Given $ROOT/assets/octicons.js containing:

window.addEventListener("load", function() {
    const PLACEHOLDER = document.getElementById("octicons-placeholder");

    const request = new XMLHttpRequest();
    request.open("GET", "/content/assets/octicons/sprite.octicons.svg");
    request.onload = function(load) {
        PLACEHOLDER.outerHTML = load.target.responseText.replace("<svg", "<svg class=\"hidden\"");
    };
    request.send();
});

The following holds:

let root: PathBuf = /* obtained elsewhere */;

let mut elem = ScriptElement::from_path("MathJax-config.js");
assert_eq!(elem.load(&("$ROOT".to_string(), root.clone())), Ok(()));
assert_eq!(elem, ScriptElement::from_literal("\
    MathJax.Hub.Config({\n\
      jax: [\"input/AsciiMath\", \"output/HTML-CSS\"],\n\
      extensions: [\"asciimath2jax.js\"],\n\
      asciimath2jax: {\n\
        delimiters: [['[​[​', '​]​]']],\n\
        preview: \"[[maths]]\"\n\
      },\n\
      AsciiMath: {\n\
        decimal: \".\"\n\
      },\n\
      \"HTML-CSS\": {\n\
        undefinedFamily: \"STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif\"\n\
      }\n\
    });\n\
"));

let mut elem = ScriptElement::from_path("assets/.././assets/octicons.js");
assert_eq!(elem.load(&("$ROOT".to_string(), root.clone())), Ok(()));
assert_eq!(elem, ScriptElement::from_literal("\
window.addEventListener(\"load\", function() {\n\
    const PLACEHOLDER = document.getElementById(\"octicons-placeholder\");\n\
    \n\
    const request = new XMLHttpRequest();\n\
    request.open(\"GET\", \"/content/assets/octicons/sprite.octicons.svg\");\n\
    request.onload = function(load) {\n\
        PLACEHOLDER.outerHTML = load.target.responseText.replace(\"<svg\", \"<svg class=\\\"hidden\\\"\");\n\
    };\n\
    request.send();\n\
});\n\
"));

let mut elem = ScriptElement::from_path("assets/nonexistant.js");
assert_eq!(elem.load(&("$ROOT".to_string(), root.clone())), Err(Error::FileNotFound {
    who: "file script element",
    path: "$ROOT/assets/nonexistant.js".into(),
}));
assert_eq!(elem, ScriptElement::from_path("assets/nonexistant.js"));

Trait Implementations

impl WrappedElement for ScriptElement[src]

fn head_b(&self) -> &[u8][src]

Byte representation of pre-content.

fn content_b(&self) -> &[u8][src]

Byte representation of the content.

fn foot_b(&self) -> &[u8][src]

Byte representation of post-content.

impl Eq for ScriptElement[src]

impl Clone for ScriptElement[src]

fn clone_from(&mut self, source: &Self)1.0.0[src]

Performs copy-assignment from source. Read more

impl PartialOrd<ScriptElement> for ScriptElement[src]

impl PartialEq<ScriptElement> for ScriptElement[src]

impl Ord for ScriptElement[src]

fn max(self, other: Self) -> Self1.21.0[src]

Compares and returns the maximum of two values. Read more

fn min(self, other: Self) -> Self1.21.0[src]

Compares and returns the minimum of two values. Read more

fn clamp(self, min: Self, max: Self) -> Self[src]

🔬 This is a nightly-only experimental API. (clamp)

Restrict a value to a certain interval. Read more

impl Hash for ScriptElement[src]

fn hash_slice<H>(data: &[Self], state: &mut H) where
    H: Hasher
1.3.0[src]

Feeds a slice of this type into the given [Hasher]. Read more

impl Debug for ScriptElement[src]

impl<'de> Deserialize<'de> for ScriptElement[src]

Auto Trait Implementations

impl Unpin for ScriptElement

impl Sync for ScriptElement

impl Send for ScriptElement

impl UnwindSafe for ScriptElement

impl RefUnwindSafe for ScriptElement

Blanket Implementations

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> DeserializeOwned for T where
    T: Deserialize<'de>, 
[src]

impl<V, T> VZip<V> for T where
    V: MultiLane<T>, 
[src]