visualci-gallery 0.2.2

A screenshots page from VisualCI's public gallery, rendered in Rust (or an Askama template) and hydrated by the visualci-gallery script.
Documentation
//! 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 crate::model::{Model, Preload, Screen, 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
}

fn size_label(size: &str) -> &'static str {
    if size == "phone" { "Phone" } else { "Desktop" }
}

fn theme_switch() -> String {
    concat!(
        r#"<div class="vg-seg" role="group" aria-label="Theme">"#,
        r#"<button type="button" data-vg-set-theme="light" aria-pressed="false">Light</button>"#,
        r#"<button type="button" data-vg-set-theme="dark" aria-pressed="false">Dark</button>"#,
        "</div>"
    )
    .to_string()
}

fn size_switch(sizes: &[&str], extra: &str) -> String {
    let buttons: String = sizes
        .iter()
        .map(|s| {
            format!(r#"<button type="button" data-vg-set-size="{s}" aria-pressed="false">{}</button>"#, size_label(s))
        })
        .collect();
    format!(r#"<div class="vg-seg{extra}" role="group" aria-label="Screen size">{buttons}</div>"#)
}

/// 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
}

fn image(title: &str, v: &Variant, themes: &[&str]) -> String {
    let alt = format!("{title}, {}, {}", size_label(&v.size).to_lowercase(), themes.join(" and "));
    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-size="{}" data-vg-theme="{}" src="{}"{full}{x2}{bytes} width="{}" height="{}" alt="{}" loading="lazy" decoding="async">"#,
        v.size,
        themes.join(" "),
        escape(src),
        v.width,
        v.height,
        escape(&alt)
    )
}

fn card(sc: &Screen, sizes: &[String], heading: &str, caption: bool, fit: &str) -> String {
    let mut imgs = String::new();
    let mut shown: Vec<&str> = Vec::new();
    let mut first: Option<&Variant> = None;
    for size in sizes {
        let at: Vec<&Variant> = sc.variants.iter().filter(|v| &v.size == size).collect();
        if at.is_empty() {
            continue;
        }
        shown.push(size);
        first.get_or_insert(at[0]);
        // Every size has both themes (the model refuses a screen without); the same image for both is shown once.
        if at[0].url == at[1].url
            && at[0].url2x == at[1].url2x
            && at[0].thumb.as_ref().map(|t| &t.url) == at[1].thumb.as_ref().map(|t| &t.url)
        {
            imgs.push_str(&image(&sc.title, at[0], &["light", "dark"]));
        } else {
            for v in &at {
                imgs.push_str(&image(&sc.title, v, &[v.theme.as_str()]));
            }
        }
    }
    let first = first.expect("a screen has a variant at one of its sizes");
    let fit = if fit == "contain" { r#" data-vg-fit="contain""# } else { "" };
    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="{}" 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>"#,
        escape(&sc.key),
        shown.join(" "),
        escape(&first.url),
        escape(&sc.title),
        escape(&sc.title)
    )
}

/// Every screen of every group at one size (desktop when any group has it) in one row.
fn strip_size(model: &Model) -> &'static str {
    if model.groups.iter().any(|g| g.sizes.iter().any(|s| s == "desktop")) { "desktop" } else { "phone" }
}

fn grid(model: &Model, id: &str, 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 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-sizes="{}"{role}{hidden}>"#,
            g.slug,
            g.sizes.join(" ")
        ));
        let mut controls = if model.theme_switch { theme_switch() } else { String::new() };
        if g.sizes.len() > 1 {
            controls.push_str(&size_switch(&g.sizes.iter().map(String::as_str).collect::<Vec<_>>(), ""));
        }
        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(sc, &g.sizes, ch, true, &g.fit));
        }
        out.push("</ul>".into());
        out.push("</div>".into());
    }
}

fn strip(model: &Model, id: &str, ch: &str, out: &mut Vec<String>) {
    let size = strip_size(model);
    out.push(format!(r#"<div class="vg-panel" id="{id}-strip" data-vg-sizes="{size}">"#));
    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());
    out.push(r#"<ul class="vg-grid vg-track">"#.into());
    let sizes = [size.to_string()];
    for g in &model.groups {
        for sc in &g.screens {
            if sc.variants.iter().any(|v| v.size == size) {
                out.push(card(sc, &sizes, ch, false, &g.fit));
            }
        }
    }
    out.push("</ul>".into());
    out.push(r#"<button type="button" class="vg-icon vg-strip-next" data-vg-scroll="1" aria-label="Scroll forward">›</button></div>"#.into());
    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();

    // The size shown before the script runs: the first panel's (only it shows without the script).
    let size = if model.layout == "strip" { strip_size(model).to_string() } else { model.groups[0].sizes[0].clone() };
    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)
        }
    };
    out.push(format!(
        r#"<section class="vg" data-vg data-vg-layout="{}" aria-label="{}" data-vg-size="{size}"{source}{preload}>"#,
        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, &h(below), &mut out);
    } else {
        grid(model, &id, &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 {
        out.push(r#"<p class="vg-credit">Screenshots by <a href="https://visualci.com">VisualCI</a></p>"#.into());
    }
    out.push(format!(r#"<dialog class="vg-box" aria-labelledby="{id}-box-title">"#));
    let hb = h(below);
    out.push(format!(
        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>"#,
        if model.theme_switch { theme_switch() } else { String::new() },
        if model.layout == "grid" { size_switch(&["desktop", "phone"], " vg-box-sizes") } else { String::new() },
    ));
    out.push(r#"<div class="vg-box-view"></div>"#.into());
    out.push("</dialog>".into());
    out.push("</section>".into());
    out.join("\n") + "\n"
}