use std::borrow::Cow;
use std::fmt;
use crate::response::{IntoResponse, Response};
pub use glacier_macros::{Template, html, render, views};
pub trait Template {
fn render(self) -> Rendered;
}
#[derive(Debug, Clone, PartialEq)]
pub struct Rendered {
statics: &'static [&'static str],
dynamics: Vec<Dynamic>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Dynamic {
Text(String),
Nested(Rendered),
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 }
}
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)),
}
}
}
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())
}
}
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 {
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()
}
}
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())
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Raw(pub String);
impl Render for Raw {
fn to_dynamic(&self) -> Dynamic {
Dynamic::Text(self.0.clone())
}
}
pub mod helpers {
use super::Raw;
use crate::db::Changeset;
use crate::model::Model;
use crate::router::ToPath;
use crate::{html, request};
pub fn raw(html: impl Into<String>) -> Raw {
Raw(html.into())
}
pub fn flash(kind: &str) -> Option<String> {
request::flash(kind)
}
pub fn csrf_field() -> Raw {
Raw(html::csrf_field(&request::csrf_token()))
}
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())
))
}
pub fn form_for(target: &impl FormTarget) -> Raw {
let (action, method) = target.form_action();
form_tag(action, method)
}
pub trait FormTarget {
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"),
}
}
}
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<y</b> <b>x<y</b><b>x<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()), "<&>");
assert_eq!(html(Some("a").to_dynamic()), "a");
assert_eq!(html(None::<&str>.to_dynamic()), "");
assert_eq!(html('"'.to_dynamic()), """);
assert_eq!(html(helpers::raw("<br>").to_dynamic()), "<br>");
assert_eq!(html(true.to_dynamic()), "true");
}
}