glacier-web 0.1.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Views: compiled templates.
//!
//! Templates are compiled at build time by `#[derive(Template)]` (files in
//! `src/views/`) or `html!("...")` (inline). Both produce a [`Rendered`]: the
//! template's static text, fixed at compile time, interleaved with the
//! dynamic values computed at render time. Keeping the two apart is what
//! will let Live views send only the values that changed.
//!
//! # Syntax
//!
//! | | |
//! | --- | --- |
//! | `{{ expr }}` | any Rust expression, HTML-escaped (see [`Render`]) |
//! | `{% if cond %} … {% else if cond %} … {% else %} … {% end %}` | `if let` works too |
//! | `{% for pat in expr %} … {% end %}` | |
//! | `{% let pat = expr %}` | scoped to the enclosing block |
//! | `{# comment #}` | |
//! | `{%-` / `-%}` (also `{{-`, `-}}`) | trim whitespace before / after the tag |
//!
//! In a `#[derive(Template)]` struct, fields are in scope by name, by value
//! (so `{% if count > 0 %}` just works), along with the [`helpers`].
//! Templates own their data: give them `Post` and `Vec<Post>`, not references.
//!
//! Looping over or `if let`-matching a plain variable or field borrows it
//! rather than moving it, so `{% for post in posts %}` yields `&Post` and
//! `posts` is still usable afterwards.
//!
//! ```
//! use glacier::view::Template;
//!
//! #[derive(Template)]
//! #[template(source = "<h1>{{ title }}</h1>{% for tag in tags %}<i>{{ tag }}</i>{% end %}")]
//! struct Page {
//!     title: String,
//!     tags: Vec<String>,
//! }
//!
//! let page = Page { title: "Rust & you".into(), tags: vec!["a".into(), "b".into()] };
//! assert_eq!(page.render().to_html(), "<h1>Rust &amp; you</h1><i>a</i><i>b</i>");
//! ```

use std::borrow::Cow;
use std::fmt;

use crate::response::{IntoResponse, Response};

pub use glacier_macros::{Template, html, render, views};

/// Implemented by `#[derive(Template)]`. Rendering consumes the template,
/// which owns its data.
pub trait Template {
    fn render(self) -> Rendered;
}

/// A rendered template: `statics.len() == dynamics.len() + 1`, and the HTML
/// is `statics[0] + dynamics[0] + statics[1] + … + statics[n]`.
#[derive(Debug, Clone, PartialEq)]
pub struct Rendered {
    statics: &'static [&'static str],
    dynamics: Vec<Dynamic>,
}

/// One dynamic slot of a template.
#[derive(Debug, Clone, PartialEq)]
pub enum Dynamic {
    /// Already-escaped HTML.
    Text(String),
    /// A nested template: a partial, a layout's content, or an `if` branch.
    Nested(Rendered),
    /// The iterations of a `for` loop, which all share the body's statics.
    List(Vec<Rendered>),
}

impl Rendered {
    #[doc(hidden)]
    pub fn new(statics: &'static [&'static str], dynamics: Vec<Dynamic>) -> Self {
        debug_assert_eq!(statics.len(), dynamics.len() + 1);
        Self { statics, dynamics }
    }

    /// Renders nothing; what an `if` without a matching branch produces.
    pub fn empty() -> Self {
        Self::new(&[""], Vec::new())
    }

    pub fn statics(&self) -> &'static [&'static str] {
        self.statics
    }

    pub fn dynamics(&self) -> &[Dynamic] {
        &self.dynamics
    }

    pub fn write_html(&self, out: &mut String) {
        for (i, s) in self.statics.iter().enumerate() {
            out.push_str(s);
            if let Some(dynamic) = self.dynamics.get(i) {
                dynamic.write_html(out);
            }
        }
    }

    pub fn to_html(&self) -> String {
        let mut out = String::new();
        self.write_html(&mut out);
        out
    }
}

impl Dynamic {
    pub fn write_html(&self, out: &mut String) {
        match self {
            Dynamic::Text(html) => out.push_str(html),
            Dynamic::Nested(rendered) => rendered.write_html(out),
            Dynamic::List(items) => items.iter().for_each(|item| item.write_html(out)),
        }
    }
}

/// Renders nothing, so layouts can derive `Default`.
impl Default for Rendered {
    fn default() -> Self {
        Self::empty()
    }
}

impl fmt::Display for Rendered {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_html())
    }
}

impl IntoResponse for Rendered {
    fn into_response(self) -> Response {
        Response::html(self.to_html())
    }
}

/// Values that can appear in `{{ … }}`. Text is HTML-escaped; use
/// [`helpers::raw`] for trusted markup.
///
/// Implement it for your own types to make them renderable directly.
pub trait Render {
    fn to_dynamic(&self) -> Dynamic;
}

impl<T: Render + ?Sized> Render for &T {
    fn to_dynamic(&self) -> Dynamic {
        (**self).to_dynamic()
    }
}

impl Render for str {
    fn to_dynamic(&self) -> Dynamic {
        Dynamic::Text(crate::html::escape(self))
    }
}

impl Render for String {
    fn to_dynamic(&self) -> Dynamic {
        self.as_str().to_dynamic()
    }
}

impl Render for Cow<'_, str> {
    fn to_dynamic(&self) -> Dynamic {
        self.as_ref().to_dynamic()
    }
}

macro_rules! render_display {
    ($($t:ty),*) => {$(
        impl Render for $t {
            fn to_dynamic(&self) -> Dynamic {
                // Numbers and bools never need escaping.
                Dynamic::Text(self.to_string())
            }
        }
    )*};
}

render_display!(
    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, bool
);

impl Render for char {
    fn to_dynamic(&self) -> Dynamic {
        self.encode_utf8(&mut [0; 4]).to_dynamic()
    }
}

/// `None` renders nothing.
impl<T: Render> Render for Option<T> {
    fn to_dynamic(&self) -> Dynamic {
        match self {
            Some(value) => value.to_dynamic(),
            None => Dynamic::Text(String::new()),
        }
    }
}

impl Render for Rendered {
    fn to_dynamic(&self) -> Dynamic {
        Dynamic::Nested(self.clone())
    }
}

/// Trusted HTML, inserted without escaping. Build it with [`helpers::raw`].
#[derive(Debug, Clone, PartialEq)]
pub struct Raw(pub String);

impl Render for Raw {
    fn to_dynamic(&self) -> Dynamic {
        Dynamic::Text(self.0.clone())
    }
}

/// Functions available by name inside every template. The ones that need
/// the request (flash, CSRF) read it from `glacier::request`.
pub mod helpers {
    use super::Raw;
    use crate::db::Changeset;
    use crate::model::Model;
    use crate::router::ToPath;
    use crate::{html, request};

    /// Inserts `html` without escaping. Never pass user input.
    pub fn raw(html: impl Into<String>) -> Raw {
        Raw(html.into())
    }

    /// A flash message set by the previous request; `None` outside one.
    pub fn flash(kind: &str) -> Option<String> {
        request::flash(kind)
    }

    /// The hidden CSRF field for a form.
    pub fn csrf_field() -> Raw {
        Raw(html::csrf_field(&request::csrf_token()))
    }

    /// A link to a path or a record: `{{ link_to("Edit", edit_post_path(post.id)) }}`,
    /// `{{ link_to(post.title, post) }}`. The text is escaped.
    pub fn link_to(text: impl AsRef<str>, target: impl ToPath) -> Raw {
        Raw(format!(
            r#"<a href="{}">{}</a>"#,
            html::escape(&target.to_path()),
            html::escape(text.as_ref())
        ))
    }

    /// Opens the right form for a record or a changeset, as Rails'
    /// `form_with model:` does: `POST /posts` for a new record, `PATCH
    /// /posts/7` for a saved one, with the CSRF token. Close it with
    /// `</form>`.
    pub fn form_for(target: &impl FormTarget) -> Raw {
        let (action, method) = target.form_action();
        form_tag(action, method)
    }

    /// What [`form_for`] opens a form for: a record or a changeset.
    pub trait FormTarget {
        /// The form's action and method.
        fn form_action(&self) -> (String, &'static str);
    }

    impl<M: Model> FormTarget for M {
        fn form_action(&self) -> (String, &'static str) {
            if self.is_new() {
                (M::collection_path(), "post")
            } else {
                (self.path(), "patch")
            }
        }
    }

    impl<M: Model> FormTarget for Changeset<M> {
        fn form_action(&self) -> (String, &'static str) {
            match self.data() {
                Some(record) => (record.path(), "patch"),
                None => (M::collection_path(), "post"),
            }
        }
    }

    /// Opens a `<form>` with the CSRF field, plus a `_method` field for
    /// PATCH, PUT and DELETE (handled by `MethodOverride`). Close it with
    /// `</form>`.
    ///
    /// ```text
    /// {{ form_tag(post_path(post.id), "delete") }}<button>Delete</button></form>
    /// ```
    pub fn form_tag(action: impl AsRef<str>, method: &str) -> Raw {
        let method = method.to_ascii_lowercase();
        let (form_method, override_field) = match method.as_str() {
            "get" => ("get", String::new()),
            "post" => ("post", String::new()),
            other => ("post", html::method_field(other)),
        };
        let csrf = if form_method == "get" {
            String::new()
        } else {
            html::csrf_field(&request::csrf_token())
        };
        Raw(format!(
            r#"<form method="{form_method}" action="{}">{csrf}{override_field}"#,
            html::escape(action.as_ref())
        ))
    }
}

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

    #[test]
    fn interleaves_statics_and_dynamics() {
        let inner = Rendered::new(&["<b>", "</b>"], vec!["x<y".to_dynamic()]);
        let page = Rendered::new(
            &["<p>", " ", " ", "</p>"],
            vec![
                42.to_dynamic(),
                Dynamic::Nested(inner.clone()),
                Dynamic::List(vec![inner.clone(), inner]),
            ],
        );
        assert_eq!(
            page.to_html(),
            "<p>42 <b>x&lt;y</b> <b>x&lt;y</b><b>x&lt;y</b></p>"
        );
    }

    #[test]
    fn renders_common_values() {
        let html = |d: Dynamic| {
            let mut out = String::new();
            d.write_html(&mut out);
            out
        };
        assert_eq!(html("<&>".to_dynamic()), "&lt;&amp;&gt;");
        assert_eq!(html(Some("a").to_dynamic()), "a");
        assert_eq!(html(None::<&str>.to_dynamic()), "");
        assert_eq!(html('"'.to_dynamic()), "&quot;");
        assert_eq!(html(helpers::raw("<br>").to_dynamic()), "<br>");
        assert_eq!(html(true.to_dynamic()), "true");
    }
}