Skip to main content

visualci_gallery/
render.rs

1//! The gallery's HTML from its model: the markup every renderer emits byte for byte (contract/SPEC.md, "The
2//! markup"), a line-for-line port of the JS library's render.ts.
3
4use crate::model::{Model, Preload, Screen, Variant};
5
6/// & < > " ' as entities: the only escaping the contract allows, so every language's output is the same.
7pub fn escape(s: &str) -> String {
8    let mut out = String::with_capacity(s.len());
9    for c in s.chars() {
10        match c {
11            '&' => out.push_str("&amp;"),
12            '<' => out.push_str("&lt;"),
13            '>' => out.push_str("&gt;"),
14            '"' => out.push_str("&quot;"),
15            '\'' => out.push_str("&#39;"),
16            c => out.push(c),
17        }
18    }
19    out
20}
21
22fn size_label(size: &str) -> &'static str {
23    if size == "phone" { "Phone" } else { "Desktop" }
24}
25
26fn theme_switch() -> String {
27    concat!(
28        r#"<div class="vg-seg" role="group" aria-label="Theme">"#,
29        r#"<button type="button" data-vg-set-theme="light" aria-pressed="false">Light</button>"#,
30        r#"<button type="button" data-vg-set-theme="dark" aria-pressed="false">Dark</button>"#,
31        "</div>"
32    )
33    .to_string()
34}
35
36fn size_switch(sizes: &[&str], extra: &str) -> String {
37    let buttons: String = sizes
38        .iter()
39        .map(|s| {
40            format!(r#"<button type="button" data-vg-set-size="{s}" aria-pressed="false">{}</button>"#, size_label(s))
41        })
42        .collect();
43    format!(r#"<div class="vg-seg{extra}" role="group" aria-label="Screen size">{buttons}</div>"#)
44}
45
46/// The sizes the preloader caps by, where the manifest gives them: of the card's image (`src`), of the full-size one
47/// when the card shows a thumbnail, and of the 2x copy.
48fn bytes_attrs(v: &Variant) -> String {
49    let shown = match &v.thumb {
50        Some(t) => t.bytes,
51        None => v.bytes,
52    };
53    let mut out = String::new();
54    if let Some(b) = shown {
55        out.push_str(&format!(r#" data-vg-bytes="{b}""#));
56    }
57    if let (Some(_), Some(b)) = (&v.thumb, v.bytes) {
58        out.push_str(&format!(r#" data-vg-full-bytes="{b}""#));
59    }
60    if let (Some(_), Some(b)) = (&v.url2x, v.bytes2x) {
61        out.push_str(&format!(r#" data-vg-2x-bytes="{b}""#));
62    }
63    out
64}
65
66fn image(title: &str, v: &Variant, themes: &[&str]) -> String {
67    let alt = format!("{title}, {}, {}", size_label(&v.size).to_lowercase(), themes.join(" and "));
68    let src = v.thumb.as_ref().map_or(v.url.as_str(), |t| t.url.as_str());
69    let full = if v.thumb.is_some() { format!(r#" data-src-full="{}""#, escape(&v.url)) } else { String::new() };
70    let x2 = v.url2x.as_deref().map(|u| format!(r#" data-src-2x="{}""#, escape(u))).unwrap_or_default();
71    let bytes = bytes_attrs(v);
72    format!(
73        r#"<img class="vg-img" data-vg-size="{}" data-vg-theme="{}" src="{}"{full}{x2}{bytes} width="{}" height="{}" alt="{}" loading="lazy" decoding="async">"#,
74        v.size,
75        themes.join(" "),
76        escape(src),
77        v.width,
78        v.height,
79        escape(&alt)
80    )
81}
82
83fn card(sc: &Screen, sizes: &[String], heading: &str, caption: bool, fit: &str) -> String {
84    let mut imgs = String::new();
85    let mut shown: Vec<&str> = Vec::new();
86    let mut first: Option<&Variant> = None;
87    for size in sizes {
88        let at: Vec<&Variant> = sc.variants.iter().filter(|v| &v.size == size).collect();
89        if at.is_empty() {
90            continue;
91        }
92        shown.push(size);
93        first.get_or_insert(at[0]);
94        // Every size has both themes (the model refuses a screen without); the same image for both is shown once.
95        if at[0].url == at[1].url
96            && at[0].url2x == at[1].url2x
97            && at[0].thumb.as_ref().map(|t| &t.url) == at[1].thumb.as_ref().map(|t| &t.url)
98        {
99            imgs.push_str(&image(&sc.title, at[0], &["light", "dark"]));
100        } else {
101            for v in &at {
102                imgs.push_str(&image(&sc.title, v, &[v.theme.as_str()]));
103            }
104        }
105    }
106    let first = first.expect("a screen has a variant at one of its sizes");
107    let fit = if fit == "contain" { r#" data-vg-fit="contain""# } else { "" };
108    let caption = match (&sc.caption, caption) {
109        (Some(c), true) => format!(r#"<p class="vg-caption">{}</p>"#, escape(c)),
110        _ => String::new(),
111    };
112    format!(
113        r#"<li class="vg-card" data-vg-screen="{}" data-vg-sizes="{}"{fit}><a class="vg-thumb" href="{}" data-vg-open aria-label="{}: view full size">{imgs}</a><{heading} class="vg-card-title">{}</{heading}>{caption}</li>"#,
114        escape(&sc.key),
115        shown.join(" "),
116        escape(&first.url),
117        escape(&sc.title),
118        escape(&sc.title)
119    )
120}
121
122/// Every screen of every group at one size (desktop when any group has it) in one row.
123fn strip_size(model: &Model) -> &'static str {
124    if model.groups.iter().any(|g| g.sizes.iter().any(|s| s == "desktop")) { "desktop" } else { "phone" }
125}
126
127fn grid(model: &Model, id: &str, gh: &str, ch: &str, out: &mut Vec<String>) {
128    let tabs = model.groups.len() > 1;
129    if tabs {
130        out.push(format!(r#"<div class="vg-tabs" role="tablist" aria-label="{}">"#, escape(&model.label)));
131        for (i, g) in model.groups.iter().enumerate() {
132            out.push(format!(
133                r#"<button type="button" role="tab" id="{id}-tab-{slug}" aria-controls="{id}-panel-{slug}" aria-selected="{}" tabindex="{}">{}</button>"#,
134                i == 0,
135                if i == 0 { 0 } else { -1 },
136                escape(&g.name),
137                slug = g.slug
138            ));
139        }
140        out.push("</div>".into());
141    }
142    for (i, g) in model.groups.iter().enumerate() {
143        let role =
144            if tabs { format!(r#" role="tabpanel" aria-labelledby="{id}-tab-{}""#, g.slug) } else { String::new() };
145        let hidden = if i > 0 { " hidden" } else { "" };
146        out.push(format!(
147            r#"<div class="vg-panel" id="{id}-panel-{}" data-vg-sizes="{}"{role}{hidden}>"#,
148            g.slug,
149            g.sizes.join(" ")
150        ));
151        let mut controls = if model.theme_switch { theme_switch() } else { String::new() };
152        if g.sizes.len() > 1 {
153            controls.push_str(&size_switch(&g.sizes.iter().map(String::as_str).collect::<Vec<_>>(), ""));
154        }
155        let controls =
156            if controls.is_empty() { controls } else { format!(r#"<div class="vg-controls">{controls}</div>"#) };
157        out.push(format!(
158            r#"<div class="vg-bar"><{gh} class="vg-group-title">{}</{gh}>{controls}</div>"#,
159            escape(&g.title)
160        ));
161        out.push(r#"<ul class="vg-grid">"#.into());
162        for sc in &g.screens {
163            out.push(card(sc, &g.sizes, ch, true, &g.fit));
164        }
165        out.push("</ul>".into());
166        out.push("</div>".into());
167    }
168}
169
170fn strip(model: &Model, id: &str, ch: &str, out: &mut Vec<String>) {
171    let size = strip_size(model);
172    out.push(format!(r#"<div class="vg-panel" id="{id}-strip" data-vg-sizes="{size}">"#));
173    out.push(r#"<div class="vg-strip"><button type="button" class="vg-icon vg-strip-prev" data-vg-scroll="-1" aria-label="Scroll back">‹</button>"#.into());
174    out.push(r#"<ul class="vg-grid vg-track">"#.into());
175    let sizes = [size.to_string()];
176    for g in &model.groups {
177        for sc in &g.screens {
178            if sc.variants.iter().any(|v| v.size == size) {
179                out.push(card(sc, &sizes, ch, false, &g.fit));
180            }
181        }
182    }
183    out.push("</ul>".into());
184    out.push(r#"<button type="button" class="vg-icon vg-strip-next" data-vg-scroll="1" aria-label="Scroll forward">›</button></div>"#.into());
185    out.push("</div>".into());
186}
187
188/// The gallery's markup: one line per block, no indentation, "\n" after each line.
189pub fn render_model(model: &Model) -> String {
190    let id = escape(&model.id);
191    let h = |offset: u8| format!("h{}", (model.heading_level + offset).min(6));
192    let below = if model.title.is_none() { 0 } else { 1 };
193    let mut out: Vec<String> = Vec::new();
194
195    // The size shown before the script runs: the first panel's (only it shows without the script).
196    let size = if model.layout == "strip" { strip_size(model).to_string() } else { model.groups[0].sizes[0].clone() };
197    let source = if model.theme_switch { "" } else { r#" data-vg-theme-source="page""# };
198    // Preloading with the defaults needs no attribute; off, or with caps of the site's own, says so.
199    let preload = match &model.preload {
200        None => String::new(),
201        Some(Preload::Off) => r#" data-vg-preload="off""#.to_string(),
202        Some(Preload::Caps(p)) => {
203            format!(r#" data-vg-preload="fold={} count={} bytes={} parallel={}""#, p.fold, p.count, p.bytes, p.parallel)
204        }
205    };
206    out.push(format!(
207        r#"<section class="vg" data-vg data-vg-layout="{}" aria-label="{}" data-vg-size="{size}"{source}{preload}>"#,
208        model.layout,
209        escape(&model.label)
210    ));
211    if let Some(title) = &model.title {
212        out.push(format!(r#"<{h} class="vg-title">{}</{h}>"#, escape(title), h = h(0)));
213    }
214    if model.layout == "strip" {
215        strip(model, &id, &h(below), &mut out);
216    } else {
217        grid(model, &id, &h(below), &h(below + 1), &mut out);
218    }
219    if let Some(see) = &model.see_all {
220        out.push(format!(r#"<p class="vg-see-all"><a href="{}">{}</a></p>"#, escape(&see.href), escape(&see.text)));
221    }
222    if model.credit {
223        out.push(r#"<p class="vg-credit">Screenshots by <a href="https://visualci.com">VisualCI</a></p>"#.into());
224    }
225    out.push(format!(r#"<dialog class="vg-box" aria-labelledby="{id}-box-title">"#));
226    let hb = h(below);
227    out.push(format!(
228        r#"<div class="vg-box-bar"><{hb} class="vg-box-title" id="{id}-box-title"></{hb}><div class="vg-controls">{}{}<button type="button" class="vg-icon" data-vg-step="-1" aria-label="Previous screen">‹</button><button type="button" class="vg-icon" data-vg-step="1" aria-label="Next screen">›</button></div><button type="button" class="vg-icon" data-vg-close aria-label="Close">×</button></div>"#,
229        if model.theme_switch { theme_switch() } else { String::new() },
230        if model.layout == "grid" { size_switch(&["desktop", "phone"], " vg-box-sizes") } else { String::new() },
231    ));
232    out.push(r#"<div class="vg-box-view"></div>"#.into());
233    out.push("</dialog>".into());
234    out.push("</section>".into());
235    out.join("\n") + "\n"
236}