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 std::collections::BTreeMap;
5
6use crate::model::{Dimension, Group, Missing, Model, Preload, Screen, Shape, Variant, Version, Versions};
7
8/// & < > " ' as entities: the only escaping the contract allows, so every language's output is the same.
9pub fn escape(s: &str) -> String {
10    let mut out = String::with_capacity(s.len());
11    for c in s.chars() {
12        match c {
13            '&' => out.push_str("&amp;"),
14            '<' => out.push_str("&lt;"),
15            '>' => out.push_str("&gt;"),
16            '"' => out.push_str("&quot;"),
17            '\'' => out.push_str("&#39;"),
18            c => out.push(c),
19        }
20    }
21    out
22}
23
24/// One of the gallery's words (Text), escaped, with every `name` in it (`{title}`, `{link}`) replaced by `html`.
25fn fill(text: &str, name: &str, html: &str) -> String {
26    escape(text).replace(name, html)
27}
28
29/// A value key per dimension, in the dimensions' order.
30type Choice = Vec<String>;
31
32/// A dimension's switch: segmented buttons for two or three values, a select-only combobox for more.
33fn dim_switch(d: &Dimension, keys: &[String], place: &str, current: &str, id: &str) -> String {
34    let label = |k: &str| escape(&d.values.iter().find(|v| v.key == k).unwrap().label);
35    let name = escape(&d.label);
36    let key = &d.key;
37    if keys.len() <= 3 {
38        let buttons: String = keys
39            .iter()
40            .map(|k| format!(r#"<button type="button" data-vg-set="{k}" aria-pressed="false">{}</button>"#, label(k)))
41            .collect();
42        return format!(r#"<div class="vg-seg" role="group" aria-label="{name}" data-vg-dim="{key}">{buttons}</div>"#);
43    }
44    // "--" can't occur in a slug or a key, so these ids never meet another.
45    let list = format!("{id}-{place}--{key}");
46    let options: String = keys
47        .iter()
48        .map(|k| {
49            format!(r#"<li role="option" id="{list}--{k}" data-vg-set="{k}" aria-selected="false">{}</li>"#, label(k))
50        })
51        .collect();
52    format!(
53        r#"<div class="vg-combo" data-vg-dim="{key}"><button type="button" class="vg-combo-button" role="combobox" aria-label="{name}" aria-haspopup="listbox" aria-expanded="false" aria-controls="{list}">{}</button><ul class="vg-combo-list" role="listbox" id="{list}" aria-label="{name}" hidden>{options}</ul></div>"#,
54        label(current)
55    )
56}
57
58/// The Version switch: Latest, then each reported version, the one shown chosen in the markup.
59fn version_switch(model: &Model, versions: &Versions, id: &str) -> String {
60    let latest = Version { key: "latest".into(), label: model.text.latest.clone(), manifest: versions.latest.clone() };
61    let all: Vec<&Version> = std::iter::once(&latest).chain(&versions.list).collect();
62    let name = escape(&model.text.version);
63    let attrs = |x: &Version| format!(r#"data-vg-set="{}" data-vg-manifest="{}""#, x.key, escape(&x.manifest));
64    if all.len() <= 3 {
65        let buttons: String = all
66            .iter()
67            .map(|x| {
68                format!(
69                    r#"<button type="button" {} aria-pressed="{}">{}</button>"#,
70                    attrs(x),
71                    x.key == versions.current,
72                    escape(&x.label)
73                )
74            })
75            .collect();
76        return format!(
77            r#"<div class="vg-seg" role="group" aria-label="{name}" data-vg-dim="@version">{buttons}</div>"#
78        );
79    }
80    let list = format!("{id}-version");
81    let current = all.iter().find(|x| x.key == versions.current).unwrap_or(&all[0]);
82    let options: String = all
83        .iter()
84        .map(|x| {
85            format!(
86                r#"<li role="option" id="{list}--{}" {} aria-selected="{}">{}</li>"#,
87                x.key,
88                attrs(x),
89                x.key == versions.current,
90                escape(&x.label)
91            )
92        })
93        .collect();
94    format!(
95        r#"<div class="vg-combo" data-vg-dim="@version"><button type="button" class="vg-combo-button" role="combobox" aria-label="{name}" aria-haspopup="listbox" aria-expanded="false" aria-controls="{list}">{}</button><ul class="vg-combo-list" role="listbox" id="{list}" aria-label="{name}" hidden>{options}</ul></div>"#,
96        escape(&current.label)
97    )
98}
99
100/// A switch for each dimension with two or more of `values` (not the theme's without its switch).
101fn switches(model: &Model, values: &BTreeMap<String, Vec<String>>, place: &str, current: &Choice, id: &str) -> String {
102    model
103        .dimensions
104        .iter()
105        .enumerate()
106        .filter(|(_, d)| values[&d.key].len() > 1 && (d.key != "theme" || model.theme_switch))
107        .map(|(i, d)| dim_switch(d, &values[&d.key], place, &current[i], id))
108        .collect()
109}
110
111/// The sizes the preloader caps by, where the manifest gives them: of the card's image (`src`), of the full-size one
112/// when the card shows a thumbnail, and of the 2x copy.
113fn bytes_attrs(v: &Variant) -> String {
114    let shown = match &v.thumb {
115        Some(t) => t.bytes,
116        None => v.bytes,
117    };
118    let mut out = String::new();
119    if let Some(b) = shown {
120        out.push_str(&format!(r#" data-vg-bytes="{b}""#));
121    }
122    if let (Some(_), Some(b)) = (&v.thumb, v.bytes) {
123        out.push_str(&format!(r#" data-vg-full-bytes="{b}""#));
124    }
125    if let (Some(_), Some(b)) = (&v.url2x, v.bytes2x) {
126        out.push_str(&format!(r#" data-vg-2x-bytes="{b}""#));
127    }
128    out
129}
130
131/// A variant's values in the dimensions' order, as a choice.
132fn values_of(model: &Model, v: &Variant) -> Choice {
133    model.dimensions.iter().map(|d| v.values[&d.key].clone()).collect()
134}
135
136/// A card's combination for a choice: its own first value of each dimension (but a "hide" one, where the card is off)
137/// it lacks the chosen one of. A strip's card can lack an "error" dimension's value its group doesn't have.
138fn card_combo(model: &Model, sc: &Screen, choice: &Choice) -> Choice {
139    let dims = &model.dimensions;
140    let has = |i: usize| sc.variants.iter().any(|v| v.values[&dims[i].key] == choice[i]);
141    let mut out: Choice = dims
142        .iter()
143        .enumerate()
144        .map(|(i, d)| {
145            if !has(i) && d.missing != Missing::Hide {
146                sc.variants[0].values[&d.key].clone()
147            } else {
148                choice[i].clone()
149            }
150        })
151        .collect();
152    // The card's first value must also go with the rest of the combination: take it from a variant that has the rest.
153    for (i, d) in dims.iter().enumerate() {
154        if d.missing == Missing::Hide || has(i) {
155            continue;
156        }
157        let found = sc
158            .variants
159            .iter()
160            .find(|v| dims.iter().enumerate().all(|(j, e)| j == i || v.values[&e.key] == out[j]))
161            .map(|v| v.values[&d.key].clone());
162        if let Some(k) = found {
163            out[i] = k;
164        }
165    }
166    out
167}
168
169/// Off for a choice: some "hide" dimension's chosen value isn't among the card's.
170fn card_off(model: &Model, sc: &Screen, choice: &Choice) -> bool {
171    model
172        .dimensions
173        .iter()
174        .enumerate()
175        .any(|(i, d)| d.missing == Missing::Hide && !sc.variants.iter().any(|v| v.values[&d.key] == choice[i]))
176}
177
178/// One card: a link to its image for the choice (which hydrate() turns into the full-size view), the images, its
179/// title and caption.
180fn card(
181    model: &Model,
182    g: &Group,
183    sc: &Screen,
184    choice: &Choice,
185    variants: &[&Variant],
186    heading: &str,
187    caption: bool,
188) -> String {
189    let mut imgs: Vec<Vec<&Variant>> = Vec::new();
190    for v in variants {
191        let thumb = |x: &Variant| x.thumb.as_ref().map(|t| t.url.clone());
192        match imgs.iter_mut().find(|i| i[0].url == v.url && i[0].url2x == v.url2x && thumb(i[0]) == thumb(v)) {
193            Some(same) => same.push(v),
194            None => imgs.push(vec![v]),
195        }
196    }
197    let combo = card_combo(model, sc, choice);
198    let holds = |i: &[&Variant], c: &Choice| i.iter().any(|v| values_of(model, v) == *c);
199    let first = imgs.iter().find(|i| holds(i, &combo)).unwrap_or(&imgs[0]);
200    let themes = &g.values["theme"];
201    let follows = themes.iter().any(|t| t == "light") && themes.iter().any(|t| t == "dark");
202    let theme_at = model.dimensions.iter().position(|d| d.key == "theme").unwrap();
203    let shown = |i: &[&Variant]| -> Option<String> {
204        if !follows {
205            return holds(i, &combo).then(String::new);
206        }
207        let marks: Vec<&str> = ["light", "dark"]
208            .into_iter()
209            .filter(|t| {
210                let mut c = choice.clone();
211                c[theme_at] = t.to_string();
212                holds(i, &card_combo(model, sc, &c))
213            })
214            .collect();
215        (!marks.is_empty()).then(|| marks.join(" "))
216    };
217    let off = if card_off(model, sc, choice) { " data-vg-off" } else { "" };
218    let fit = if g.fit == "contain" { r#" data-vg-fit="contain""# } else { "" };
219    let images: String = imgs.iter().map(|i| image(model, g, &sc.title, i, shown(i))).collect();
220    let (since, badge) = match (&model.new_badges, &sc.since) {
221        (Some(_), Some(s)) => (
222            format!(r#" data-vg-since="{}""#, escape(s)),
223            match &sc.change {
224                Some(href) => format!(
225                    r#"<a class="vg-new" href="{}" aria-label="{}" hidden>{}</a>"#,
226                    escape(href),
227                    fill(&model.text.change, "{title}", &escape(&sc.title)),
228                    escape(&model.text.new)
229                ),
230                None => format!(r#"<span class="vg-new" hidden>{}</span>"#, escape(&model.text.new)),
231            },
232        ),
233        _ => (String::new(), String::new()),
234    };
235    let caption = match (&sc.caption, caption) {
236        (Some(c), true) => format!(r#"<p class="vg-caption">{}</p>"#, escape(c)),
237        _ => String::new(),
238    };
239    format!(
240        r#"<li class="vg-card" data-vg-screen="{}"{off}{fit}{since}><a class="vg-thumb" href="{}" data-vg-open aria-label="{}">{images}</a>{badge}<{heading} class="vg-card-title">{}</{heading}>{caption}</li>"#,
241        escape(&sc.key),
242        escape(&first[0].url),
243        fill(&model.text.open, "{title}", &escape(&sc.title)),
244        escape(&sc.title)
245    )
246}
247
248/// An image, for the combinations its variants are; its alt text names the values that differ within the group.
249fn image(model: &Model, g: &Group, title: &str, i: &[&Variant], shown: Option<String>) -> String {
250    let v = i[0];
251    let mut parts = vec![title.to_string()];
252    for d in &model.dimensions {
253        if g.values[&d.key].len() < 2 {
254            continue;
255        }
256        let labels: Vec<&str> =
257            d.values.iter().filter(|x| i.iter().any(|w| w.values[&d.key] == x.key)).map(|x| x.label.as_str()).collect();
258        parts.push(labels.join(&model.text.and));
259    }
260    let combos: Vec<String> = i.iter().map(|w| values_of(model, w).join(".")).collect();
261    let shown = shown.map(|s| format!(r#" data-vg-shown="{s}""#)).unwrap_or_default();
262    let src = v.thumb.as_ref().map_or(v.url.as_str(), |t| t.url.as_str());
263    let full = if v.thumb.is_some() { format!(r#" data-src-full="{}""#, escape(&v.url)) } else { String::new() };
264    let x2 = v.url2x.as_deref().map(|u| format!(r#" data-src-2x="{}""#, escape(u))).unwrap_or_default();
265    let bytes = bytes_attrs(v);
266    format!(
267        r#"<img class="vg-img" data-vg-for="{}"{shown} src="{}"{full}{x2}{bytes} width="{}" height="{}" alt="{}" loading="lazy" decoding="async">"#,
268        combos.join(" "),
269        escape(src),
270        v.width,
271        v.height,
272        escape(&parts.join(", "))
273    )
274}
275
276/// The starting choice: the first group's first value of each dimension (the grid), or the first value any group
277/// has (the strip).
278fn start_choice(model: &Model) -> Choice {
279    model
280        .dimensions
281        .iter()
282        .map(|d| {
283            if model.layout == "strip" {
284                d.values
285                    .iter()
286                    .find(|v| model.groups.iter().any(|g| g.values[&d.key].contains(&v.key)))
287                    .unwrap()
288                    .key
289                    .clone()
290            } else {
291                model.groups[0].values[&d.key][0].clone()
292            }
293        })
294        .collect()
295}
296
297/// A group's start: the choice's value of each dimension when the group has it, else the group's first.
298fn group_choice(model: &Model, g: &Group, choice: &Choice) -> Choice {
299    model
300        .dimensions
301        .iter()
302        .enumerate()
303        .map(|(i, d)| {
304            let have = &g.values[&d.key];
305            if have.contains(&choice[i]) { choice[i].clone() } else { have[0].clone() }
306        })
307        .collect()
308}
309
310fn size_dimension(model: &Model) -> (usize, &Dimension) {
311    model.dimensions.iter().enumerate().find(|(_, d)| d.key == "size").unwrap()
312}
313
314/// The shape of a choice's size.
315fn shape_of(model: &Model, choice: &Choice) -> &'static str {
316    let (i, d) = size_dimension(model);
317    d.values.iter().find(|v| v.key == choice[i]).unwrap().shape.map_or("landscape", Shape::as_str)
318}
319
320fn grid(model: &Model, id: &str, choice: &Choice, gh: &str, ch: &str, out: &mut Vec<String>) {
321    let tabs = model.groups.len() > 1;
322    if tabs {
323        out.push(format!(r#"<div class="vg-tabs" role="tablist" aria-label="{}">"#, escape(&model.label)));
324        for (i, g) in model.groups.iter().enumerate() {
325            out.push(format!(
326                r#"<button type="button" role="tab" id="{id}-tab-{slug}" aria-controls="{id}-panel-{slug}" aria-selected="{}" tabindex="{}">{}</button>"#,
327                i == 0,
328                if i == 0 { 0 } else { -1 },
329                escape(&g.name),
330                slug = g.slug
331            ));
332        }
333        out.push("</div>".into());
334    }
335    for (i, g) in model.groups.iter().enumerate() {
336        let start = group_choice(model, g, choice);
337        let role =
338            if tabs { format!(r#" role="tabpanel" aria-labelledby="{id}-tab-{}""#, g.slug) } else { String::new() };
339        let hidden = if i > 0 { " hidden" } else { "" };
340        out.push(format!(
341            r#"<div class="vg-panel" id="{id}-panel-{}" data-vg-shape="{}"{role}{hidden}>"#,
342            g.slug,
343            shape_of(model, &start)
344        ));
345        let controls = switches(model, &g.values, &format!("panel-{}", g.slug), &start, id);
346        let controls =
347            if controls.is_empty() { controls } else { format!(r#"<div class="vg-controls">{controls}</div>"#) };
348        out.push(format!(
349            r#"<div class="vg-bar"><{gh} class="vg-group-title">{}</{gh}>{controls}</div>"#,
350            escape(&g.title)
351        ));
352        out.push(r#"<ul class="vg-grid">"#.into());
353        for sc in &g.screens {
354            out.push(card(model, g, sc, &start, &sc.variants.iter().collect::<Vec<_>>(), ch, true));
355        }
356        out.push("</ul>".into());
357        out.push("</div>".into());
358    }
359    if model.search {
360        out.push(format!(r#"<p class="vg-empty" role="status" hidden>{}</p>"#, escape(&model.text.empty)));
361    }
362}
363
364fn strip(model: &Model, id: &str, choice: &Choice, ch: &str, out: &mut Vec<String>) {
365    out.push(format!(r#"<div class="vg-panel" id="{id}-strip" data-vg-shape="{}">"#, shape_of(model, choice)));
366    out.push(format!(
367        r#"<div class="vg-strip"><button type="button" class="vg-icon vg-strip-prev" data-vg-scroll="-1" aria-label="{}">‹</button>"#,
368        escape(&model.text.back)
369    ));
370    out.push(r#"<ul class="vg-grid vg-track">"#.into());
371    for g in &model.groups {
372        for sc in &g.screens {
373            if card_off(model, sc, choice) {
374                continue;
375            }
376            let combo = card_combo(model, sc, choice);
377            let variants: Vec<&Variant> = sc
378                .variants
379                .iter()
380                .filter(|v| {
381                    model.dimensions.iter().enumerate().all(|(i, d)| d.key == "theme" || v.values[&d.key] == combo[i])
382                })
383                .collect();
384            out.push(card(model, g, sc, choice, &variants, ch, false));
385        }
386    }
387    out.push("</ul>".into());
388    out.push(format!(
389        r#"<button type="button" class="vg-icon vg-strip-next" data-vg-scroll="1" aria-label="{}">›</button></div>"#,
390        escape(&model.text.forward)
391    ));
392    out.push("</div>".into());
393}
394
395/// The gallery's markup: one line per block, no indentation, "\n" after each line.
396pub fn render_model(model: &Model) -> String {
397    let id = escape(&model.id);
398    let h = |offset: u8| format!("h{}", (model.heading_level + offset).min(6));
399    let below = if model.title.is_none() { 0 } else { 1 };
400    let mut out: Vec<String> = Vec::new();
401    let choice = start_choice(model);
402    let dims = model
403        .dimensions
404        .iter()
405        .map(|d| {
406            let keys: Vec<&str> = d.values.iter().map(|v| v.key.as_str()).collect();
407            format!("{}:{}:{}", d.key, d.missing.as_str(), keys.join(","))
408        })
409        .collect::<Vec<_>>()
410        .join(" ");
411    let portrait: Vec<&str> = size_dimension(model)
412        .1
413        .values
414        .iter()
415        .filter(|v| v.shape == Some(Shape::Portrait))
416        .map(|v| v.key.as_str())
417        .collect();
418    let portrait =
419        if portrait.is_empty() { String::new() } else { format!(r#" data-vg-portrait="{}""#, portrait.join(" ")) };
420    let source = if model.theme_switch { "" } else { r#" data-vg-theme-source="page""# };
421    // Preloading with the defaults needs no attribute; off, or with caps of the site's own, says so.
422    let preload = match &model.preload {
423        None => String::new(),
424        Some(Preload::Off) => r#" data-vg-preload="off""#.to_string(),
425        Some(Preload::Caps(p)) => {
426            format!(r#" data-vg-preload="fold={} count={} bytes={} parallel={}""#, p.fold, p.count, p.bytes, p.parallel)
427        }
428    };
429    let links = if model.deep_links { " data-vg-links" } else { "" };
430    let zoom = if model.zoom { "" } else { r#" data-vg-zoom="off""# };
431    let new = model.new_badges.map_or(String::new(), |days| format!(r#" data-vg-new="{days}""#));
432    out.push(format!(
433        r#"<section class="vg" data-vg data-vg-layout="{}" aria-label="{}" data-vg-dims="{dims}"{portrait}{source}{preload}{links}{zoom}{new}>"#,
434        model.layout,
435        escape(&model.label)
436    ));
437    if let Some(title) = &model.title {
438        out.push(format!(r#"<{h} class="vg-title">{}</{h}>"#, escape(title), h = h(0)));
439    }
440    if let Some(versions) = &model.versions {
441        out.push(format!(
442            r#"<div class="vg-versions" data-vg-options="{}">{}</div>"#,
443            escape(&versions.options),
444            version_switch(model, versions, &id)
445        ));
446    }
447    if model.search {
448        let words = escape(&model.text.search);
449        out.push(format!(
450            r#"<div class="vg-search"><input type="search" class="vg-search-input" id="{id}-search" aria-label="{words}" placeholder="{words}" autocomplete="off"></div>"#
451        ));
452    }
453    if model.layout == "strip" {
454        strip(model, &id, &choice, &h(below), &mut out);
455    } else {
456        grid(model, &id, &choice, &h(below), &h(below + 1), &mut out);
457    }
458    if let Some(see) = &model.see_all {
459        out.push(format!(r#"<p class="vg-see-all"><a href="{}">{}</a></p>"#, escape(&see.href), escape(&see.text)));
460    }
461    if model.credit {
462        let link = r#"<a href="https://visualci.com">VisualCI</a>"#;
463        out.push(format!(r#"<p class="vg-credit">{}</p>"#, fill(&model.text.credit, "{link}", link)));
464    }
465    let box_switches = if model.layout == "grid" {
466        let all: BTreeMap<String, Vec<String>> = model
467            .dimensions
468            .iter()
469            .map(|d| {
470                let keys = d
471                    .values
472                    .iter()
473                    .filter(|v| model.groups.iter().any(|g| g.values[&d.key].contains(&v.key)))
474                    .map(|v| v.key.clone())
475                    .collect();
476                (d.key.clone(), keys)
477            })
478            .collect();
479        let firsts: Choice = model.dimensions.iter().map(|d| all[&d.key][0].clone()).collect();
480        switches(model, &all, "box", &firsts, &id)
481    } else {
482        String::new()
483    };
484    out.push(format!(r#"<dialog class="vg-box" aria-labelledby="{id}-box-title">"#));
485    let hb = h(below);
486    let (previous, next, close) = (escape(&model.text.previous), escape(&model.text.next), escape(&model.text.close));
487    out.push(format!(
488        r#"<div class="vg-box-bar"><{hb} class="vg-box-title" id="{id}-box-title"></{hb}><div class="vg-controls">{box_switches}<button type="button" class="vg-icon" data-vg-step="-1" aria-label="{previous}">‹</button><button type="button" class="vg-icon" data-vg-step="1" aria-label="{next}">›</button></div><button type="button" class="vg-icon" data-vg-close aria-label="{close}">×</button></div>"#
489    ));
490    out.push(r#"<div class="vg-box-view"></div>"#.into());
491    out.push("</dialog>".into());
492    out.push("</section>".into());
493    out.join("\n") + "\n"
494}