visualci-gallery 0.4.0

A screenshots page from VisualCI's public gallery, rendered in Rust (or an Askama template) and hydrated by the visualci-gallery script.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! The gallery's HTML from its model: the markup every renderer emits byte for byte (contract/SPEC.md, "The
//! markup"), a line-for-line port of the JS library's render.ts.

use std::collections::BTreeMap;

use crate::model::{Dimension, Group, Missing, Model, Preload, Screen, Shape, Variant};

/// & < > " ' as entities: the only escaping the contract allows, so every language's output is the same.
pub fn escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            c => out.push(c),
        }
    }
    out
}

/// One of the gallery's words (Text), escaped, with every `name` in it (`{title}`, `{link}`) replaced by `html`.
fn fill(text: &str, name: &str, html: &str) -> String {
    escape(text).replace(name, html)
}

/// A value key per dimension, in the dimensions' order.
type Choice = Vec<String>;

/// A dimension's switch: segmented buttons for two or three values, a select-only combobox for more.
fn dim_switch(d: &Dimension, keys: &[String], place: &str, current: &str, id: &str) -> String {
    let label = |k: &str| escape(&d.values.iter().find(|v| v.key == k).unwrap().label);
    let name = escape(&d.label);
    let key = &d.key;
    if keys.len() <= 3 {
        let buttons: String = keys
            .iter()
            .map(|k| format!(r#"<button type="button" data-vg-set="{k}" aria-pressed="false">{}</button>"#, label(k)))
            .collect();
        return format!(r#"<div class="vg-seg" role="group" aria-label="{name}" data-vg-dim="{key}">{buttons}</div>"#);
    }
    // "--" can't occur in a slug or a key, so these ids never meet another.
    let list = format!("{id}-{place}--{key}");
    let options: String = keys
        .iter()
        .map(|k| {
            format!(r#"<li role="option" id="{list}--{k}" data-vg-set="{k}" aria-selected="false">{}</li>"#, label(k))
        })
        .collect();
    format!(
        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>"#,
        label(current)
    )
}

/// A switch for each dimension with two or more of `values` (not the theme's without its switch).
fn switches(model: &Model, values: &BTreeMap<String, Vec<String>>, place: &str, current: &Choice, id: &str) -> String {
    model
        .dimensions
        .iter()
        .enumerate()
        .filter(|(_, d)| values[&d.key].len() > 1 && (d.key != "theme" || model.theme_switch))
        .map(|(i, d)| dim_switch(d, &values[&d.key], place, &current[i], id))
        .collect()
}

/// The sizes the preloader caps by, where the manifest gives them: of the card's image (`src`), of the full-size one
/// when the card shows a thumbnail, and of the 2x copy.
fn bytes_attrs(v: &Variant) -> String {
    let shown = match &v.thumb {
        Some(t) => t.bytes,
        None => v.bytes,
    };
    let mut out = String::new();
    if let Some(b) = shown {
        out.push_str(&format!(r#" data-vg-bytes="{b}""#));
    }
    if let (Some(_), Some(b)) = (&v.thumb, v.bytes) {
        out.push_str(&format!(r#" data-vg-full-bytes="{b}""#));
    }
    if let (Some(_), Some(b)) = (&v.url2x, v.bytes2x) {
        out.push_str(&format!(r#" data-vg-2x-bytes="{b}""#));
    }
    out
}

/// A variant's values in the dimensions' order, as a choice.
fn values_of(model: &Model, v: &Variant) -> Choice {
    model.dimensions.iter().map(|d| v.values[&d.key].clone()).collect()
}

/// A card's combination for a choice: its own first value of each dimension (but a "hide" one, where the card is off)
/// it lacks the chosen one of. A strip's card can lack an "error" dimension's value its group doesn't have.
fn card_combo(model: &Model, sc: &Screen, choice: &Choice) -> Choice {
    let dims = &model.dimensions;
    let has = |i: usize| sc.variants.iter().any(|v| v.values[&dims[i].key] == choice[i]);
    let mut out: Choice = dims
        .iter()
        .enumerate()
        .map(|(i, d)| {
            if !has(i) && d.missing != Missing::Hide {
                sc.variants[0].values[&d.key].clone()
            } else {
                choice[i].clone()
            }
        })
        .collect();
    // The card's first value must also go with the rest of the combination: take it from a variant that has the rest.
    for (i, d) in dims.iter().enumerate() {
        if d.missing == Missing::Hide || has(i) {
            continue;
        }
        let found = sc
            .variants
            .iter()
            .find(|v| dims.iter().enumerate().all(|(j, e)| j == i || v.values[&e.key] == out[j]))
            .map(|v| v.values[&d.key].clone());
        if let Some(k) = found {
            out[i] = k;
        }
    }
    out
}

/// Off for a choice: some "hide" dimension's chosen value isn't among the card's.
fn card_off(model: &Model, sc: &Screen, choice: &Choice) -> bool {
    model
        .dimensions
        .iter()
        .enumerate()
        .any(|(i, d)| d.missing == Missing::Hide && !sc.variants.iter().any(|v| v.values[&d.key] == choice[i]))
}

/// One card: a link to its image for the choice (which hydrate() turns into the full-size view), the images, its
/// title and caption.
fn card(
    model: &Model,
    g: &Group,
    sc: &Screen,
    choice: &Choice,
    variants: &[&Variant],
    heading: &str,
    caption: bool,
) -> String {
    let mut imgs: Vec<Vec<&Variant>> = Vec::new();
    for v in variants {
        let thumb = |x: &Variant| x.thumb.as_ref().map(|t| t.url.clone());
        match imgs.iter_mut().find(|i| i[0].url == v.url && i[0].url2x == v.url2x && thumb(i[0]) == thumb(v)) {
            Some(same) => same.push(v),
            None => imgs.push(vec![v]),
        }
    }
    let combo = card_combo(model, sc, choice);
    let holds = |i: &[&Variant], c: &Choice| i.iter().any(|v| values_of(model, v) == *c);
    let first = imgs.iter().find(|i| holds(i, &combo)).unwrap_or(&imgs[0]);
    let themes = &g.values["theme"];
    let follows = themes.iter().any(|t| t == "light") && themes.iter().any(|t| t == "dark");
    let theme_at = model.dimensions.iter().position(|d| d.key == "theme").unwrap();
    let shown = |i: &[&Variant]| -> Option<String> {
        if !follows {
            return holds(i, &combo).then(String::new);
        }
        let marks: Vec<&str> = ["light", "dark"]
            .into_iter()
            .filter(|t| {
                let mut c = choice.clone();
                c[theme_at] = t.to_string();
                holds(i, &card_combo(model, sc, &c))
            })
            .collect();
        (!marks.is_empty()).then(|| marks.join(" "))
    };
    let off = if card_off(model, sc, choice) { " data-vg-off" } else { "" };
    let fit = if g.fit == "contain" { r#" data-vg-fit="contain""# } else { "" };
    let images: String = imgs.iter().map(|i| image(model, g, &sc.title, i, shown(i))).collect();
    let caption = match (&sc.caption, caption) {
        (Some(c), true) => format!(r#"<p class="vg-caption">{}</p>"#, escape(c)),
        _ => String::new(),
    };
    format!(
        r#"<li class="vg-card" data-vg-screen="{}"{off}{fit}><a class="vg-thumb" href="{}" data-vg-open aria-label="{}">{images}</a><{heading} class="vg-card-title">{}</{heading}>{caption}</li>"#,
        escape(&sc.key),
        escape(&first[0].url),
        fill(&model.text.open, "{title}", &escape(&sc.title)),
        escape(&sc.title)
    )
}

/// An image, for the combinations its variants are; its alt text names the values that differ within the group.
fn image(model: &Model, g: &Group, title: &str, i: &[&Variant], shown: Option<String>) -> String {
    let v = i[0];
    let mut parts = vec![title.to_string()];
    for d in &model.dimensions {
        if g.values[&d.key].len() < 2 {
            continue;
        }
        let labels: Vec<&str> =
            d.values.iter().filter(|x| i.iter().any(|w| w.values[&d.key] == x.key)).map(|x| x.label.as_str()).collect();
        parts.push(labels.join(&model.text.and));
    }
    let combos: Vec<String> = i.iter().map(|w| values_of(model, w).join(".")).collect();
    let shown = shown.map(|s| format!(r#" data-vg-shown="{s}""#)).unwrap_or_default();
    let src = v.thumb.as_ref().map_or(v.url.as_str(), |t| t.url.as_str());
    let full = if v.thumb.is_some() { format!(r#" data-src-full="{}""#, escape(&v.url)) } else { String::new() };
    let x2 = v.url2x.as_deref().map(|u| format!(r#" data-src-2x="{}""#, escape(u))).unwrap_or_default();
    let bytes = bytes_attrs(v);
    format!(
        r#"<img class="vg-img" data-vg-for="{}"{shown} src="{}"{full}{x2}{bytes} width="{}" height="{}" alt="{}" loading="lazy" decoding="async">"#,
        combos.join(" "),
        escape(src),
        v.width,
        v.height,
        escape(&parts.join(", "))
    )
}

/// The starting choice: the first group's first value of each dimension (the grid), or the first value any group
/// has (the strip).
fn start_choice(model: &Model) -> Choice {
    model
        .dimensions
        .iter()
        .map(|d| {
            if model.layout == "strip" {
                d.values
                    .iter()
                    .find(|v| model.groups.iter().any(|g| g.values[&d.key].contains(&v.key)))
                    .unwrap()
                    .key
                    .clone()
            } else {
                model.groups[0].values[&d.key][0].clone()
            }
        })
        .collect()
}

/// A group's start: the choice's value of each dimension when the group has it, else the group's first.
fn group_choice(model: &Model, g: &Group, choice: &Choice) -> Choice {
    model
        .dimensions
        .iter()
        .enumerate()
        .map(|(i, d)| {
            let have = &g.values[&d.key];
            if have.contains(&choice[i]) { choice[i].clone() } else { have[0].clone() }
        })
        .collect()
}

fn size_dimension(model: &Model) -> (usize, &Dimension) {
    model.dimensions.iter().enumerate().find(|(_, d)| d.key == "size").unwrap()
}

/// The shape of a choice's size.
fn shape_of(model: &Model, choice: &Choice) -> &'static str {
    let (i, d) = size_dimension(model);
    d.values.iter().find(|v| v.key == choice[i]).unwrap().shape.map_or("landscape", Shape::as_str)
}

fn grid(model: &Model, id: &str, choice: &Choice, gh: &str, ch: &str, out: &mut Vec<String>) {
    let tabs = model.groups.len() > 1;
    if tabs {
        out.push(format!(r#"<div class="vg-tabs" role="tablist" aria-label="{}">"#, escape(&model.label)));
        for (i, g) in model.groups.iter().enumerate() {
            out.push(format!(
                r#"<button type="button" role="tab" id="{id}-tab-{slug}" aria-controls="{id}-panel-{slug}" aria-selected="{}" tabindex="{}">{}</button>"#,
                i == 0,
                if i == 0 { 0 } else { -1 },
                escape(&g.name),
                slug = g.slug
            ));
        }
        out.push("</div>".into());
    }
    for (i, g) in model.groups.iter().enumerate() {
        let start = group_choice(model, g, choice);
        let role =
            if tabs { format!(r#" role="tabpanel" aria-labelledby="{id}-tab-{}""#, g.slug) } else { String::new() };
        let hidden = if i > 0 { " hidden" } else { "" };
        out.push(format!(
            r#"<div class="vg-panel" id="{id}-panel-{}" data-vg-shape="{}"{role}{hidden}>"#,
            g.slug,
            shape_of(model, &start)
        ));
        let controls = switches(model, &g.values, &format!("panel-{}", g.slug), &start, id);
        let controls =
            if controls.is_empty() { controls } else { format!(r#"<div class="vg-controls">{controls}</div>"#) };
        out.push(format!(
            r#"<div class="vg-bar"><{gh} class="vg-group-title">{}</{gh}>{controls}</div>"#,
            escape(&g.title)
        ));
        out.push(r#"<ul class="vg-grid">"#.into());
        for sc in &g.screens {
            out.push(card(model, g, sc, &start, &sc.variants.iter().collect::<Vec<_>>(), ch, true));
        }
        out.push("</ul>".into());
        out.push("</div>".into());
    }
}

fn strip(model: &Model, id: &str, choice: &Choice, ch: &str, out: &mut Vec<String>) {
    out.push(format!(r#"<div class="vg-panel" id="{id}-strip" data-vg-shape="{}">"#, shape_of(model, choice)));
    out.push(format!(
        r#"<div class="vg-strip"><button type="button" class="vg-icon vg-strip-prev" data-vg-scroll="-1" aria-label="{}">‹</button>"#,
        escape(&model.text.back)
    ));
    out.push(r#"<ul class="vg-grid vg-track">"#.into());
    for g in &model.groups {
        for sc in &g.screens {
            if card_off(model, sc, choice) {
                continue;
            }
            let combo = card_combo(model, sc, choice);
            let variants: Vec<&Variant> = sc
                .variants
                .iter()
                .filter(|v| {
                    model.dimensions.iter().enumerate().all(|(i, d)| d.key == "theme" || v.values[&d.key] == combo[i])
                })
                .collect();
            out.push(card(model, g, sc, choice, &variants, ch, false));
        }
    }
    out.push("</ul>".into());
    out.push(format!(
        r#"<button type="button" class="vg-icon vg-strip-next" data-vg-scroll="1" aria-label="{}">›</button></div>"#,
        escape(&model.text.forward)
    ));
    out.push("</div>".into());
}

/// The gallery's markup: one line per block, no indentation, "\n" after each line.
pub fn render_model(model: &Model) -> String {
    let id = escape(&model.id);
    let h = |offset: u8| format!("h{}", (model.heading_level + offset).min(6));
    let below = if model.title.is_none() { 0 } else { 1 };
    let mut out: Vec<String> = Vec::new();
    let choice = start_choice(model);
    let dims = model
        .dimensions
        .iter()
        .map(|d| {
            let keys: Vec<&str> = d.values.iter().map(|v| v.key.as_str()).collect();
            format!("{}:{}:{}", d.key, d.missing.as_str(), keys.join(","))
        })
        .collect::<Vec<_>>()
        .join(" ");
    let portrait: Vec<&str> = size_dimension(model)
        .1
        .values
        .iter()
        .filter(|v| v.shape == Some(Shape::Portrait))
        .map(|v| v.key.as_str())
        .collect();
    let portrait =
        if portrait.is_empty() { String::new() } else { format!(r#" data-vg-portrait="{}""#, portrait.join(" ")) };
    let source = if model.theme_switch { "" } else { r#" data-vg-theme-source="page""# };
    // Preloading with the defaults needs no attribute; off, or with caps of the site's own, says so.
    let preload = match &model.preload {
        None => String::new(),
        Some(Preload::Off) => r#" data-vg-preload="off""#.to_string(),
        Some(Preload::Caps(p)) => {
            format!(r#" data-vg-preload="fold={} count={} bytes={} parallel={}""#, p.fold, p.count, p.bytes, p.parallel)
        }
    };
    let links = if model.deep_links { " data-vg-links" } else { "" };
    out.push(format!(
        r#"<section class="vg" data-vg data-vg-layout="{}" aria-label="{}" data-vg-dims="{dims}"{portrait}{source}{preload}{links}>"#,
        model.layout,
        escape(&model.label)
    ));
    if let Some(title) = &model.title {
        out.push(format!(r#"<{h} class="vg-title">{}</{h}>"#, escape(title), h = h(0)));
    }
    if model.layout == "strip" {
        strip(model, &id, &choice, &h(below), &mut out);
    } else {
        grid(model, &id, &choice, &h(below), &h(below + 1), &mut out);
    }
    if let Some(see) = &model.see_all {
        out.push(format!(r#"<p class="vg-see-all"><a href="{}">{}</a></p>"#, escape(&see.href), escape(&see.text)));
    }
    if model.credit {
        let link = r#"<a href="https://visualci.com">VisualCI</a>"#;
        out.push(format!(r#"<p class="vg-credit">{}</p>"#, fill(&model.text.credit, "{link}", link)));
    }
    let box_switches = if model.layout == "grid" {
        let all: BTreeMap<String, Vec<String>> = model
            .dimensions
            .iter()
            .map(|d| {
                let keys = d
                    .values
                    .iter()
                    .filter(|v| model.groups.iter().any(|g| g.values[&d.key].contains(&v.key)))
                    .map(|v| v.key.clone())
                    .collect();
                (d.key.clone(), keys)
            })
            .collect();
        let firsts: Choice = model.dimensions.iter().map(|d| all[&d.key][0].clone()).collect();
        switches(model, &all, "box", &firsts, &id)
    } else {
        String::new()
    };
    out.push(format!(r#"<dialog class="vg-box" aria-labelledby="{id}-box-title">"#));
    let hb = h(below);
    let (previous, next, close) = (escape(&model.text.previous), escape(&model.text.next), escape(&model.text.close));
    out.push(format!(
        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>"#
    ));
    out.push(r#"<div class="vg-box-view"></div>"#.into());
    out.push("</dialog>".into());
    out.push("</section>".into());
    out.join("\n") + "\n"
}