Skip to main content

glacier/
view.rs

1//! Views: compiled templates.
2//!
3//! Templates are compiled at build time by `#[derive(Template)]` (files in
4//! `src/views/`) or `html!("...")` (inline). Both produce a [`Rendered`]: the
5//! template's static text, fixed at compile time, interleaved with the
6//! dynamic values computed at render time. Keeping the two apart is what
7//! will let Live views send only the values that changed.
8//!
9//! # Syntax
10//!
11//! | | |
12//! | --- | --- |
13//! | `{{ expr }}` | any Rust expression, HTML-escaped (see [`Render`]) |
14//! | `{% if cond %} … {% else if cond %} … {% else %} … {% end %}` | `if let` works too |
15//! | `{% for pat in expr %} … {% end %}` | |
16//! | `{% let pat = expr %}` | scoped to the enclosing block |
17//! | `{# comment #}` | |
18//! | `{%-` / `-%}` (also `{{-`, `-}}`) | trim whitespace before / after the tag |
19//!
20//! In a `#[derive(Template)]` struct, fields are in scope by name, by value
21//! (so `{% if count > 0 %}` just works), along with the [`helpers`].
22//! Templates own their data: give them `Post` and `Vec<Post>`, not references.
23//!
24//! Looping over or `if let`-matching a plain variable or field borrows it
25//! rather than moving it, so `{% for post in posts %}` yields `&Post` and
26//! `posts` is still usable afterwards.
27//!
28//! ```
29//! use glacier::view::Template;
30//!
31//! #[derive(Template)]
32//! #[template(source = "<h1>{{ title }}</h1>{% for tag in tags %}<i>{{ tag }}</i>{% end %}")]
33//! struct Page {
34//!     title: String,
35//!     tags: Vec<String>,
36//! }
37//!
38//! let page = Page { title: "Rust & you".into(), tags: vec!["a".into(), "b".into()] };
39//! assert_eq!(page.render().to_html(), "<h1>Rust &amp; you</h1><i>a</i><i>b</i>");
40//! ```
41
42pub mod reload;
43pub mod vite;
44
45use std::borrow::Cow;
46use std::fmt;
47
48use crate::response::{IntoResponse, Response};
49
50pub use glacier_macros::{Template, html, render, views};
51
52/// Implemented by `#[derive(Template)]`. Rendering consumes the template,
53/// which owns its data.
54pub trait Template {
55    fn render(self) -> Rendered;
56}
57
58/// One field of a form, as Phoenix's `form[:title]`: what an input for it
59/// needs. `note.field("title")` (or a changeset's) makes one; the core
60/// `<.input field={note.field("title")} />` component draws it.
61#[derive(Debug, Clone, Default, PartialEq)]
62pub struct Field {
63    /// The param it's sent as: `title`.
64    pub name: String,
65    /// An id for the input, for its `<label for>`.
66    pub id: String,
67    /// What to show in it: the record's value, or the input that didn't
68    /// fit the field's type.
69    pub value: String,
70    /// "Title", from the name.
71    pub label: String,
72    /// Its errors from the last save: `["can't be blank"]`.
73    pub errors: Vec<String>,
74}
75
76impl Field {
77    pub(crate) fn new(name: &str, value: String, errors: Vec<String>) -> Self {
78        Field {
79            name: name.to_owned(),
80            id: name.to_owned(),
81            value,
82            label: crate::db::humanize(name),
83            errors,
84        }
85    }
86
87    /// A field for a form without a record: `Field::named("settings[theme]",
88    /// &theme)` is sent as `settings[theme]`, with the id `settings_theme`
89    /// and the label "Theme".
90    pub fn named(name: &str, value: impl ToString) -> Self {
91        let last = name
92            .trim_end_matches("[]")
93            .rsplit('[')
94            .next()
95            .unwrap_or(name)
96            .trim_end_matches(']');
97        let id = name
98            .replace("[]", "")
99            .replace(['[', ']'], "_")
100            .trim_end_matches('_')
101            .to_owned();
102        Field {
103            name: name.to_owned(),
104            id,
105            value: value.to_string(),
106            label: crate::db::humanize(last),
107            errors: Vec::new(),
108        }
109    }
110
111    pub fn has_errors(&self) -> bool {
112        !self.errors.is_empty()
113    }
114}
115
116#[cfg(test)]
117mod field_tests {
118    use super::Field;
119
120    #[test]
121    fn a_named_field_takes_its_id_and_label_from_its_name() {
122        let field = Field::named("settings[theme]", "dark");
123        assert_eq!(
124            (
125                field.id.as_str(),
126                field.label.as_str(),
127                field.value.as_str()
128            ),
129            ("settings_theme", "Theme", "dark")
130        );
131        assert_eq!(Field::named("email_address", "").label, "Email address");
132    }
133}
134
135/// A component's slot: the content its caller writes between its tags
136/// (`inner_block`), or in a named `<:header>…</:header>`. A slot prop
137/// with a default (`header: Slot = Slot::default()`) may be left out.
138/// `{{ inner_block }}` renders it.
139pub type Slot = Rendered;
140
141/// A rendered template: `statics.len() == dynamics.len() + 1`, and the HTML
142/// is `statics[0] + dynamics[0] + statics[1] + … + statics[n]`.
143#[derive(Debug, Clone, PartialEq)]
144pub struct Rendered {
145    statics: &'static [&'static str],
146    dynamics: Vec<Dynamic>,
147}
148
149/// One dynamic slot of a template.
150#[derive(Debug, Clone, PartialEq)]
151pub enum Dynamic {
152    /// Already-escaped HTML.
153    Text(String),
154    /// A nested template: a partial, a layout's content, or an `if` branch.
155    Nested(Rendered),
156    /// The iterations of a `for` loop, which all share the body's statics.
157    List(Vec<Rendered>),
158}
159
160impl Rendered {
161    /// HTML as it is, as a template's content: for pages Glacier builds
162    /// itself (the component gallery).
163    #[doc(hidden)]
164    pub fn raw(html: String) -> Self {
165        Self::new(&["", ""], vec![Dynamic::Text(html)])
166    }
167
168    #[doc(hidden)]
169    pub fn new(statics: &'static [&'static str], dynamics: Vec<Dynamic>) -> Self {
170        debug_assert_eq!(statics.len(), dynamics.len() + 1);
171        Self { statics, dynamics }
172    }
173
174    /// Renders nothing; what an `if` without a matching branch produces.
175    pub fn empty() -> Self {
176        Self::new(&[""], Vec::new())
177    }
178
179    pub fn statics(&self) -> &'static [&'static str] {
180        self.statics
181    }
182
183    pub fn dynamics(&self) -> &[Dynamic] {
184        &self.dynamics
185    }
186
187    pub fn write_html(&self, out: &mut String) {
188        for (i, s) in self.statics.iter().enumerate() {
189            out.push_str(s);
190            if let Some(dynamic) = self.dynamics.get(i) {
191                dynamic.write_html(out);
192            }
193        }
194    }
195
196    pub fn to_html(&self) -> String {
197        let mut out = String::new();
198        self.write_html(&mut out);
199        out
200    }
201}
202
203impl Dynamic {
204    pub fn write_html(&self, out: &mut String) {
205        match self {
206            Dynamic::Text(html) => out.push_str(html),
207            Dynamic::Nested(rendered) => rendered.write_html(out),
208            Dynamic::List(items) => items.iter().for_each(|item| item.write_html(out)),
209        }
210    }
211}
212
213/// Renders nothing, so layouts can derive `Default`.
214impl Default for Rendered {
215    fn default() -> Self {
216        Self::empty()
217    }
218}
219
220impl fmt::Display for Rendered {
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        f.write_str(&self.to_html())
223    }
224}
225
226impl IntoResponse for Rendered {
227    fn into_response(self) -> Response {
228        Response::html(self.to_html())
229    }
230}
231
232/// Values that can appear in `{{ … }}`. Text is HTML-escaped; use
233/// [`helpers::raw`] for trusted markup.
234///
235/// Implement it for your own types to make them renderable directly.
236pub trait Render {
237    fn to_dynamic(&self) -> Dynamic;
238}
239
240impl<T: Render + ?Sized> Render for &T {
241    fn to_dynamic(&self) -> Dynamic {
242        (**self).to_dynamic()
243    }
244}
245
246impl Render for str {
247    fn to_dynamic(&self) -> Dynamic {
248        if TEXT.with(std::cell::Cell::get) {
249            Dynamic::Text(self.to_owned())
250        } else {
251            Dynamic::Text(crate::html::escape(self))
252        }
253    }
254}
255
256thread_local! {
257    /// Set while a `.txt` template renders: values go in as they are.
258    static TEXT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
259}
260
261/// Renders a `.txt` template (a mail's text part): values aren't
262/// HTML-escaped. Templates are rendered synchronously, so a flag on the
263/// thread covers the template and its partials.
264#[doc(hidden)]
265pub fn as_text(render: impl FnOnce() -> Rendered) -> Rendered {
266    struct Restore(bool);
267    impl Drop for Restore {
268        fn drop(&mut self) {
269            TEXT.with(|text| text.set(self.0));
270        }
271    }
272    let _restore = Restore(TEXT.with(|text| text.replace(true)));
273    render()
274}
275
276impl Render for String {
277    fn to_dynamic(&self) -> Dynamic {
278        self.as_str().to_dynamic()
279    }
280}
281
282impl Render for Cow<'_, str> {
283    fn to_dynamic(&self) -> Dynamic {
284        self.as_ref().to_dynamic()
285    }
286}
287
288macro_rules! render_display {
289    ($($t:ty),*) => {$(
290        impl Render for $t {
291            fn to_dynamic(&self) -> Dynamic {
292                // Numbers and bools never need escaping.
293                Dynamic::Text(self.to_string())
294            }
295        }
296    )*};
297}
298
299render_display!(
300    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, bool
301);
302
303impl Render for char {
304    fn to_dynamic(&self) -> Dynamic {
305        self.encode_utf8(&mut [0; 4]).to_dynamic()
306    }
307}
308
309/// `None` renders nothing.
310impl<T: Render> Render for Option<T> {
311    fn to_dynamic(&self) -> Dynamic {
312        match self {
313            Some(value) => value.to_dynamic(),
314            None => Dynamic::Text(String::new()),
315        }
316    }
317}
318
319impl Render for Rendered {
320    fn to_dynamic(&self) -> Dynamic {
321        Dynamic::Nested(self.clone())
322    }
323}
324
325/// Trusted HTML, inserted without escaping. Build it with [`helpers::raw`].
326#[derive(Debug, Clone, PartialEq)]
327pub struct Raw(pub String);
328
329impl Render for Raw {
330    fn to_dynamic(&self) -> Dynamic {
331        Dynamic::Text(self.0.clone())
332    }
333}
334
335/// Functions available by name inside every template. The ones that need
336/// the request (flash, CSRF) read it from `glacier::request`.
337pub mod helpers {
338    use super::Raw;
339    use crate::db::Changeset;
340    use crate::model::Model;
341    use crate::router::ToPath;
342    use crate::{html, request};
343
344    pub use super::vite::vite;
345
346    /// Inserts `html` without escaping. Never pass user input.
347    pub fn raw(html: impl Into<String>) -> Raw {
348        Raw(html.into())
349    }
350
351    /// `html` with only safe markup kept, as Rails' `sanitize`: the tags
352    /// and attributes Rails' safe list allows (paragraphs, emphasis,
353    /// lists, headings, links, images…), links only to safe schemes, and
354    /// everything else (scripts, styles, event handlers, `javascript:`
355    /// links) removed. For HTML from users: a comment in Markdown, a
356    /// rich-text field.
357    pub fn sanitize(html: &str) -> Raw {
358        Raw(sanitizer().clean(html).to_string())
359    }
360
361    /// Markdown as HTML, safe to show: `{{ markdown(&page.body) }}`.
362    /// A `<.select>`'s options, each a value and its text:
363    /// `options([("light", "Light"), ("dark", "Dark")])`.
364    pub fn options<const N: usize>(
365        pairs: [(impl ToString, impl ToString); N],
366    ) -> Vec<(String, String)> {
367        pairs
368            .into_iter()
369            .map(|(value, text)| (value.to_string(), text.to_string()))
370            .collect()
371    }
372
373    /// CommonMark with GitHub's tables, strikethrough, task lists and
374    /// footnotes, then cleaned as [`sanitize`] cleans (tables kept), so
375    /// HTML written into the Markdown can't run scripts.
376    pub fn markdown(text: &str) -> Raw {
377        use pulldown_cmark::{Options, Parser, html::push_html};
378        let options = Options::ENABLE_TABLES
379            | Options::ENABLE_STRIKETHROUGH
380            | Options::ENABLE_TASKLISTS
381            | Options::ENABLE_FOOTNOTES;
382        let mut html = String::new();
383        push_html(&mut html, Parser::new_ext(text, options));
384        let mut cleaner = sanitizer();
385        cleaner
386            .add_tags([
387                "table", "thead", "tbody", "tr", "th", "td", "section", "input",
388            ])
389            .add_tag_attributes("input", ["type", "checked", "disabled"])
390            .add_tag_attributes("td", ["align"])
391            .add_tag_attributes("th", ["align"])
392            .add_generic_attributes(["id"]);
393        Raw(cleaner.clean(&html).to_string())
394    }
395
396    /// The text of `html` with every tag removed, as Rails' `strip_tags`:
397    /// `"<b>Bold</b> move"` → `"Bold move"`. Script and style contents go
398    /// too; the text stays escaped.
399    pub fn strip_tags(html: &str) -> Raw {
400        Raw(ammonia::Builder::empty().clean(html).to_string())
401    }
402
403    /// Rails' `SafeListSanitizer` defaults.
404    fn sanitizer() -> ammonia::Builder<'static> {
405        const TAGS: &[&str] = &[
406            "a",
407            "abbr",
408            "acronym",
409            "address",
410            "b",
411            "big",
412            "blockquote",
413            "br",
414            "cite",
415            "code",
416            "dd",
417            "del",
418            "dfn",
419            "div",
420            "dl",
421            "dt",
422            "em",
423            "h1",
424            "h2",
425            "h3",
426            "h4",
427            "h5",
428            "h6",
429            "hr",
430            "i",
431            "img",
432            "ins",
433            "kbd",
434            "li",
435            "mark",
436            "ol",
437            "p",
438            "pre",
439            "samp",
440            "small",
441            "span",
442            "strong",
443            "sub",
444            "sup",
445            "time",
446            "tt",
447            "ul",
448            "var",
449        ];
450        const ATTRIBUTES: &[&str] = &[
451            "abbr", "alt", "cite", "class", "datetime", "height", "href", "lang", "name", "src",
452            "title", "width", "xml:lang",
453        ];
454        let mut builder = ammonia::Builder::empty();
455        builder
456            .add_tags(TAGS)
457            .add_generic_attributes(ATTRIBUTES)
458            .url_schemes(["http", "https", "mailto", "tel", "ftp"].into())
459            .link_rel(None);
460        builder
461    }
462
463    /// Links to a list's other pages, as Kaminari's `paginate`: previous
464    /// and next, the first and last pages, and the pages around this one,
465    /// with a gap (`…`) between. Links keep the request's other query
466    /// params. Nothing when everything fits on one page.
467    ///
468    /// ```text
469    /// {{ paginate(page, total) }}
470    /// ```
471    ///
472    /// The markup: `<nav class="pagination">` holding `a` links, a
473    /// `span.current` for this page, `span.gap` and, at either end, a
474    /// `span.disabled` for a previous or next that doesn't exist.
475    pub fn paginate(page: &crate::pagination::Page, total: u64) -> Raw {
476        Raw(page.nav(total))
477    }
478
479    /// A flash message set by the previous request; `None` outside one.
480    pub fn flash(kind: &str) -> Option<String> {
481        request::flash(kind)
482    }
483
484    /// Hidden fields that tell people from bots, for a public form whose
485    /// action calls `glacier::spam::check(&params)?`.
486    pub fn spam_trap() -> Raw {
487        Raw(crate::spam::trap_html())
488    }
489
490    /// The hidden CSRF field for a form.
491    pub fn csrf_field() -> Raw {
492        Raw(html::csrf_field(&request::csrf_token()))
493    }
494
495    /// The session's CSRF token itself, for scripts that send it:
496    /// `<meta name="csrf-token" content="{{ csrf_token() }}">`, as Rails'
497    /// `csrf_meta_tags`.
498    pub fn csrf_token() -> String {
499        request::csrf_token()
500    }
501
502    /// A link to a path or a record: `{{ link_to("Edit", edit_post_path(post.id)) }}`,
503    /// `{{ link_to(post.title, post) }}`. The text is escaped.
504    pub fn link_to(text: impl AsRef<str>, target: impl ToPath) -> Raw {
505        Raw(format!(
506            r#"<a href="{}">{}</a>"#,
507            html::escape(&target.to_path()),
508            html::escape(text.as_ref())
509        ))
510    }
511
512    /// Opens the right form for a record or a changeset, as Rails'
513    /// `form_with model:` does: `POST /posts` for a new record, `PATCH
514    /// /posts/7` for a saved one, with the CSRF token. Close it with
515    /// `</form>`.
516    pub fn form_for(target: &impl FormTarget) -> Raw {
517        let (action, method) = target.form_action();
518        form_tag(action, method)
519    }
520
521    /// What [`form_for`] opens a form for: a record or a changeset.
522    pub trait FormTarget {
523        /// The form's action and method.
524        fn form_action(&self) -> (String, &'static str);
525    }
526
527    impl<M: Model> FormTarget for M {
528        fn form_action(&self) -> (String, &'static str) {
529            if self.is_new() {
530                (M::collection_path(), "post")
531            } else {
532                (self.path(), "patch")
533            }
534        }
535    }
536
537    impl<M: Model> FormTarget for Changeset<M> {
538        fn form_action(&self) -> (String, &'static str) {
539            match self.data() {
540                Some(record) => (record.path(), "patch"),
541                None => (M::collection_path(), "post"),
542            }
543        }
544    }
545
546    /// Opens a `<form>` with the CSRF field, plus a `_method` field for
547    /// PATCH, PUT and DELETE (handled by `MethodOverride`). Close it with
548    /// `</form>`.
549    ///
550    /// ```text
551    /// {{ form_tag(post_path(post.id), "delete") }}<button>Delete</button></form>
552    /// ```
553    pub fn form_tag(action: impl AsRef<str>, method: &str) -> Raw {
554        let method = method.to_ascii_lowercase();
555        let (form_method, override_field) = match method.as_str() {
556            "get" => ("get", String::new()),
557            "post" => ("post", String::new()),
558            other => ("post", html::method_field(other)),
559        };
560        let csrf = if form_method == "get" {
561            String::new()
562        } else {
563            html::csrf_field(&request::csrf_token())
564        };
565        Raw(format!(
566            r#"<form method="{form_method}" action="{}">{csrf}{override_field}"#,
567            html::escape(action.as_ref())
568        ))
569    }
570}
571
572#[cfg(test)]
573mod tests {
574    use super::*;
575
576    #[test]
577    fn interleaves_statics_and_dynamics() {
578        let inner = Rendered::new(&["<b>", "</b>"], vec!["x<y".to_dynamic()]);
579        let page = Rendered::new(
580            &["<p>", " ", " ", "</p>"],
581            vec![
582                42.to_dynamic(),
583                Dynamic::Nested(inner.clone()),
584                Dynamic::List(vec![inner.clone(), inner]),
585            ],
586        );
587        assert_eq!(
588            page.to_html(),
589            "<p>42 <b>x&lt;y</b> <b>x&lt;y</b><b>x&lt;y</b></p>"
590        );
591    }
592
593    #[test]
594    fn renders_common_values() {
595        let html = |d: Dynamic| {
596            let mut out = String::new();
597            d.write_html(&mut out);
598            out
599        };
600        assert_eq!(html("<&>".to_dynamic()), "&lt;&amp;&gt;");
601        assert_eq!(html(Some("a").to_dynamic()), "a");
602        assert_eq!(html(None::<&str>.to_dynamic()), "");
603        assert_eq!(html('"'.to_dynamic()), "&quot;");
604        assert_eq!(html(helpers::raw("<br>").to_dynamic()), "<br>");
605        assert_eq!(html(true.to_dynamic()), "true");
606    }
607
608    #[test]
609    fn sanitize_keeps_safe_markup_only() {
610        let clean = |html: &str| helpers::sanitize(html).0;
611        assert_eq!(
612            clean(
613                r#"<p class="lead">Hi <strong>there</strong> <a href="https://example.com" title="x">link</a></p>"#
614            ),
615            r#"<p class="lead">Hi <strong>there</strong> <a href="https://example.com" title="x">link</a></p>"#
616        );
617        assert_eq!(clean("<script>alert(1)</script>Hello"), "Hello");
618        assert_eq!(
619            clean(r#"<img src="a.png" onerror="alert(1)">"#),
620            r#"<img src="a.png">"#
621        );
622        assert_eq!(clean(r#"<a href="javascript:alert(1)">x</a>"#), "<a>x</a>");
623        assert_eq!(
624            clean(r#"<a href="/posts/1">relative</a>"#),
625            r#"<a href="/posts/1">relative</a>"#
626        );
627        assert_eq!(
628            clean(r#"<div style="color:red"><iframe src="x"></iframe>ok</div>"#),
629            "<div>ok</div>"
630        );
631        assert_eq!(clean("1 < 2 & 3"), "1 &lt; 2 &amp; 3");
632    }
633
634    #[test]
635    fn strip_tags_keeps_the_text() {
636        assert_eq!(helpers::strip_tags("<b>Bold</b> move").0, "Bold move");
637        assert_eq!(
638            helpers::strip_tags("<script>alert(1)</script>Hi <i>&amp;</i> bye").0,
639            "Hi &amp; bye"
640        );
641    }
642
643    #[test]
644    fn markdown_renders_safely() {
645        use super::helpers::markdown;
646        let html = markdown("# Title\n\nSome *emphasis* and ~~gone~~.\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n- [x] done\n\n<script>alert(1)</script>\n\n[link](javascript:alert(1))").0;
647        assert!(html.contains("<h1>Title</h1>"), "{html}");
648        assert!(html.contains("<em>emphasis</em>"), "{html}");
649        assert!(html.contains("<del>gone</del>"), "{html}");
650        assert!(html.contains("<table>"), "{html}");
651        assert!(html.contains("checked"), "{html}");
652        assert!(!html.contains("<script"), "{html}");
653        assert!(!html.contains("javascript:"), "{html}");
654    }
655}
656
657/// The page `/dev/components` shows in development: every component's
658/// examples, in the app's layout. `glacier::app!()` registers it from
659/// `src/components/<name>.preview.html`.
660#[derive(Clone, Copy)]
661pub struct ComponentGallery(pub fn() -> String);
662
663/// Each preview under its name, with a list of them first, as the
664/// gallery page's content.
665#[doc(hidden)]
666pub fn gallery_html(previews: Vec<(&'static str, Rendered)>) -> String {
667    let mut html = String::from("<h1>Components</h1>");
668    if previews.is_empty() {
669        html.push_str("<p>No previews yet: add <code>src/components/&lt;name&gt;.preview.html</code> beside a component, with its examples.</p>");
670        return html;
671    }
672    html.push_str("<nav><ul>");
673    for (name, _) in &previews {
674        let name = crate::html::escape(name);
675        html.push_str(&format!(r##"<li><a href="#{name}">{name}</a></li>"##));
676    }
677    html.push_str("</ul></nav>");
678    for (name, preview) in previews {
679        let name = crate::html::escape(name);
680        html.push_str(&format!(
681            r#"<section id="{name}"><h2><code>&lt;.{name}&gt;</code></h2>{}</section>"#,
682            preview.to_html()
683        ));
684    }
685    html
686}
687
688/// `/dev/components`.
689pub(crate) async fn component_gallery(ctx: crate::Context) -> crate::Response {
690    match ctx.state::<ComponentGallery>() {
691        Ok(gallery) => crate::Response::html((gallery.0)()),
692        Err(_) => crate::Response::html(gallery_html(Vec::new())),
693    }
694}