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 {
if TEXT.with(std::cell::Cell::get) {
Dynamic::Text(self.to_owned())
} else {
Dynamic::Text(crate::html::escape(self))
}
}
}
thread_local! {
static TEXT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[doc(hidden)]
pub fn as_text(render: impl FnOnce() -> Rendered) -> Rendered {
struct Restore(bool);
impl Drop for Restore {
fn drop(&mut self) {
TEXT.with(|text| text.set(self.0));
}
}
let _restore = Restore(TEXT.with(|text| text.replace(true)));
render()
}
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 sanitize(html: &str) -> Raw {
Raw(sanitizer().clean(html).to_string())
}
pub fn strip_tags(html: &str) -> Raw {
Raw(ammonia::Builder::empty().clean(html).to_string())
}
fn sanitizer() -> ammonia::Builder<'static> {
const TAGS: &[&str] = &[
"a",
"abbr",
"acronym",
"address",
"b",
"big",
"blockquote",
"br",
"cite",
"code",
"dd",
"del",
"dfn",
"div",
"dl",
"dt",
"em",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"hr",
"i",
"img",
"ins",
"kbd",
"li",
"mark",
"ol",
"p",
"pre",
"samp",
"small",
"span",
"strong",
"sub",
"sup",
"time",
"tt",
"ul",
"var",
];
const ATTRIBUTES: &[&str] = &[
"abbr", "alt", "cite", "class", "datetime", "height", "href", "lang", "name", "src",
"title", "width", "xml:lang",
];
let mut builder = ammonia::Builder::empty();
builder
.add_tags(TAGS)
.add_generic_attributes(ATTRIBUTES)
.url_schemes(["http", "https", "mailto", "tel", "ftp"].into())
.link_rel(None);
builder
}
pub fn paginate(page: &crate::pagination::Page, total: u64) -> Raw {
Raw(page.nav(total))
}
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");
}
#[test]
fn sanitize_keeps_safe_markup_only() {
let clean = |html: &str| helpers::sanitize(html).0;
assert_eq!(
clean(
r#"<p class="lead">Hi <strong>there</strong> <a href="https://example.com" title="x">link</a></p>"#
),
r#"<p class="lead">Hi <strong>there</strong> <a href="https://example.com" title="x">link</a></p>"#
);
assert_eq!(clean("<script>alert(1)</script>Hello"), "Hello");
assert_eq!(
clean(r#"<img src="a.png" onerror="alert(1)">"#),
r#"<img src="a.png">"#
);
assert_eq!(clean(r#"<a href="javascript:alert(1)">x</a>"#), "<a>x</a>");
assert_eq!(
clean(r#"<a href="/posts/1">relative</a>"#),
r#"<a href="/posts/1">relative</a>"#
);
assert_eq!(
clean(r#"<div style="color:red"><iframe src="x"></iframe>ok</div>"#),
"<div>ok</div>"
);
assert_eq!(clean("1 < 2 & 3"), "1 < 2 & 3");
}
#[test]
fn strip_tags_keeps_the_text() {
assert_eq!(helpers::strip_tags("<b>Bold</b> move").0, "Bold move");
assert_eq!(
helpers::strip_tags("<script>alert(1)</script>Hi <i>&</i> bye").0,
"Hi & bye"
);
}
}