Skip to main content

rustango_cms/block/
layout.rs

1//! Layout blocks: **Cards**, **Slider** and **Gallery**, each a list of
2//! items an editor adds one by one (`BlockField::Repeat` over an item
3//! block: `card`, `slide`, `gallery_image`).
4//!
5//! The templates (`blocks/<type>.html`) emit plain markup with
6//! `rcms-block-*` classes and no styles, so a site's own stylesheet lays
7//! them out; the starter themes style all three. A slider works without
8//! JavaScript (it scrolls sideways with snap points); a theme may add
9//! previous/next buttons on top.
10//!
11//! Item links go through the `safe_href` filter ([`safe_href`]), so an
12//! editor's link can be a site path or a web, mail or phone address,
13//! never `javascript:` or another scheme.
14
15use crate::block::BlockFieldMeta;
16use crate::{register_block, Block, BlockField};
17
18/// A link fit for an `href`: a site path (`/about`, not `//host`), a
19/// fragment, or an `http(s)`, `mailto` or `tel` address. Anything else
20/// (`javascript:`, `data:`, a bare word) is `None`.
21#[must_use]
22pub fn safe_href(link: &str) -> Option<&str> {
23    let link = link.trim();
24    let lower = link.to_ascii_lowercase();
25    let ok = (link.starts_with('/') && !link.starts_with("//") && !link.starts_with("/\\"))
26        || link.starts_with('#')
27        || ["https://", "http://", "mailto:", "tel:"].iter().any(|s| lower.starts_with(s));
28    ok.then_some(link)
29}
30
31/// `{{ value.url | safe_href }}`: the link when [`safe_href`] accepts it,
32/// else an empty string (so `{% if href %}` drops the link).
33pub(crate) fn register_tera_filter(tera: &mut tera::Tera) {
34    tera.register_filter(
35        "safe_href",
36        |value: &tera::Value, _: &std::collections::HashMap<String, tera::Value>| {
37            Ok(tera::Value::String(
38                value.as_str().and_then(safe_href).unwrap_or_default().to_owned(),
39            ))
40        },
41    );
42}
43
44/// A select that always has a value: `default` until the editor picks.
45fn choice<const N: usize>(name: &str, label: &str, default: &str, options: [(&str, &str); N]) -> BlockField {
46    BlockField::choice(name, label, options)
47        .required()
48        .with_meta(BlockFieldMeta::default().default_value(default))
49}
50
51const LINK_HELP: &str = "A page on this site like /about, or a full link (https://…, mailto:…, tel:…).";
52
53fn link_fields(label_help: &str) -> [BlockField; 2] {
54    [
55        BlockField::char("link_label", "Link text").with_help(label_help),
56        BlockField::char("url", "Link").with_help(LINK_HELP),
57    ]
58}
59
60/// One card of a **Cards** block.
61#[derive(Default)]
62pub struct CardBlock;
63
64impl Block for CardBlock {
65    fn type_name(&self) -> &'static str {
66        "card"
67    }
68    fn verbose_name(&self) -> &'static str {
69        "Card"
70    }
71    fn icon(&self) -> Option<&'static str> {
72        Some("crop_portrait")
73    }
74    fn label_format(&self) -> Option<&'static str> {
75        Some("{title}")
76    }
77    fn fields(&self) -> Vec<BlockField> {
78        let mut fields = vec![
79            BlockField::widget("image", "Image", crate::widget::WidgetKind::MediaPicker),
80            BlockField::char("title", "Title").required(),
81            BlockField::text("text", "Text"),
82        ];
83        fields.extend(link_fields("Shown under the text. Without it, the title is the link."));
84        fields
85    }
86}
87
88/// `cards`: a grid of cards, each with an image, a title, text and a link.
89#[derive(Default)]
90pub struct CardsBlock;
91
92impl Block for CardsBlock {
93    fn type_name(&self) -> &'static str {
94        "cards"
95    }
96    fn verbose_name(&self) -> &'static str {
97        "Cards"
98    }
99    fn icon(&self) -> Option<&'static str> {
100        Some("view_module")
101    }
102    fn description(&self) -> Option<&'static str> {
103        Some("A grid of cards, each with an image, a title, text and a link.")
104    }
105    fn label_format(&self) -> Option<&'static str> {
106        Some("{heading}")
107    }
108    fn fields(&self) -> Vec<BlockField> {
109        vec![
110            BlockField::char("heading", "Heading"),
111            choice("columns", "Cards per row", "3", [("2", "2"), ("3", "3"), ("4", "4")]),
112            BlockField::repeat("cards", "Cards", "card").with_min(1).with_max(12),
113        ]
114    }
115}
116
117/// One slide of a **Slider** block.
118#[derive(Default)]
119pub struct SlideBlock;
120
121impl Block for SlideBlock {
122    fn type_name(&self) -> &'static str {
123        "slide"
124    }
125    fn verbose_name(&self) -> &'static str {
126        "Slide"
127    }
128    fn icon(&self) -> Option<&'static str> {
129        Some("view_carousel")
130    }
131    fn label_format(&self) -> Option<&'static str> {
132        Some("{heading}")
133    }
134    fn fields(&self) -> Vec<BlockField> {
135        let mut fields = vec![
136            BlockField::widget("image", "Image", crate::widget::WidgetKind::MediaPicker),
137            BlockField::char("alt", "Image description")
138                .with_help("What the image shows, for people who can't see it."),
139            BlockField::char("heading", "Heading"),
140            BlockField::text("text", "Text"),
141        ];
142        fields.extend(link_fields("A button on the slide. Leave empty for no button."));
143        fields
144    }
145}
146
147/// `slider`: slides that scroll sideways, one at a time or several in a row.
148#[derive(Default)]
149pub struct SliderBlock;
150
151impl Block for SliderBlock {
152    fn type_name(&self) -> &'static str {
153        "slider"
154    }
155    fn verbose_name(&self) -> &'static str {
156        "Slider"
157    }
158    fn icon(&self) -> Option<&'static str> {
159        Some("view_carousel")
160    }
161    fn description(&self) -> Option<&'static str> {
162        Some("Slides that scroll sideways: one large slide at a time, or a row of several.")
163    }
164    fn label_format(&self) -> Option<&'static str> {
165        Some("{heading}")
166    }
167    fn fields(&self) -> Vec<BlockField> {
168        vec![
169            BlockField::char("heading", "Heading"),
170            choice(
171                "style",
172                "Style",
173                "slides",
174                [("slides", "One slide at a time"), ("scroller", "A row of several")],
175            ),
176            BlockField::repeat("slides", "Slides", "slide").with_min(1).with_max(20),
177        ]
178    }
179}
180
181/// One picture of a **Gallery** block.
182#[derive(Default)]
183pub struct GalleryImageBlock;
184
185impl Block for GalleryImageBlock {
186    fn type_name(&self) -> &'static str {
187        "gallery_image"
188    }
189    fn verbose_name(&self) -> &'static str {
190        "Picture"
191    }
192    fn icon(&self) -> Option<&'static str> {
193        Some("image")
194    }
195    fn label_format(&self) -> Option<&'static str> {
196        Some("{caption}")
197    }
198    fn fields(&self) -> Vec<BlockField> {
199        vec![
200            BlockField::widget("image", "Image", crate::widget::WidgetKind::MediaPicker).required(),
201            BlockField::char("alt", "Image description")
202                .with_help("What the image shows, for people who can't see it."),
203            BlockField::char("caption", "Caption"),
204        ]
205    }
206}
207
208/// `gallery`: any number of pictures in a grid; each opens full size.
209#[derive(Default)]
210pub struct GalleryBlock;
211
212impl Block for GalleryBlock {
213    fn type_name(&self) -> &'static str {
214        "gallery"
215    }
216    fn verbose_name(&self) -> &'static str {
217        "Gallery"
218    }
219    fn icon(&self) -> Option<&'static str> {
220        Some("photo_library")
221    }
222    fn description(&self) -> Option<&'static str> {
223        Some("Pictures in a grid, each opening full size.")
224    }
225    fn label_format(&self) -> Option<&'static str> {
226        Some("{caption}")
227    }
228    fn fields(&self) -> Vec<BlockField> {
229        vec![
230            choice("columns", "Pictures per row", "3", [("2", "2"), ("3", "3"), ("4", "4")]),
231            BlockField::repeat("images", "Pictures", "gallery_image").with_min(1).with_max(48),
232            BlockField::char("caption", "Caption").with_help("Shown under the whole gallery."),
233        ]
234    }
235}
236
237register_block!(CardBlock);
238register_block!(CardsBlock);
239register_block!(SlideBlock);
240register_block!(SliderBlock);
241register_block!(GalleryImageBlock);
242register_block!(GalleryBlock);
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    #[test]
249    fn only_site_paths_and_web_mail_phone_links_pass() {
250        for ok in ["/contact", "/a/b?c=1#d", "#top", "https://x.org", "HTTP://X.ORG", "mailto:a@b.c", "tel:+1 555", " /padded "] {
251            assert!(safe_href(ok).is_some(), "{ok}");
252        }
253        for bad in ["javascript:alert(1)", "JaVaScRiPt:x", "data:text/html,x", "//evil.org", "/\\evil.org", "vbscript:x", "contact", ""] {
254            assert!(safe_href(bad).is_none(), "{bad}");
255        }
256    }
257
258    #[test]
259    fn every_list_names_a_registered_item_block() {
260        for (list, item) in [("cards", "card"), ("slider", "slide"), ("gallery", "gallery_image")] {
261            assert!(crate::block::find_block(list).is_some(), "{list}");
262            assert!(crate::block::find_block(item).is_some(), "{item}");
263        }
264    }
265}