visualci-gallery 0.6.0

A screenshots page from VisualCI's public gallery, rendered in Rust (or an Askama template) and hydrated by the visualci-gallery script.
Documentation
//! One screenshot from the gallery's manifest, for a page or a README: an `<img>`, or a `<picture>` that shows the
//! dark shot when the reader's setting is dark (contract/SPEC.md, "A single screenshot"). A port of the JS library's
//! screenshot.ts.

use serde_json::{Map, Value, json};

use crate::Error;
use crate::model::{
    EXTENSION, Options, Variant, build_model, check_dimensions, check_manifest, parse_shot, resolve_dimensions,
};
use crate::render::escape;

/// What [`screenshot`] and [`screenshot_markdown`] show, as JSON-shaped values like the gallery's [`Options`]. Build
/// them with [`ScreenshotOptions::new`] and the setters, or [`ScreenshotOptions::from_json`].
#[derive(Debug, Clone, Default)]
pub struct ScreenshotOptions {
    raw: Map<String, Value>,
}

impl ScreenshotOptions {
    /// The screen, by its key (`overview`, `ios/sessions`), as the gallery's `screens` and `order` name it.
    pub fn new(screen: &str) -> Self {
        ScreenshotOptions::default().set("screen", screen.into())
    }
    /// Options from a JSON object with the contract's names.
    pub fn from_json(value: &Value) -> Result<Self, Error> {
        match value {
            Value::Object(m) => Ok(ScreenshotOptions { raw: m.clone() }),
            _ => Err(Error::Invalid("screenshot options must be an object".into())),
        }
    }
    fn set(mut self, key: &str, value: Value) -> Self {
        self.raw.insert(key.to_string(), value);
        self
    }
    /// The group it's in. Default: the first group that has the screen.
    pub fn group(self, name: &str) -> Self {
        self.set("group", name.into())
    }
    /// The theme value to show. Default: the screen's first, with its dark shot for readers whose setting is dark.
    pub fn theme(self, theme: &str) -> Self {
        self.set("theme", theme.into())
    }
    /// The size value to show. Default: the screen's first that has the theme.
    pub fn size(self, size: &str) -> Self {
        self.set("size", size.into())
    }
    /// The image's alt text. Default: the screen's title, made from its key.
    pub fn alt(self, alt: &str) -> Self {
        self.set("alt", alt.into())
    }
    /// Link the image to its full-size original.
    pub fn link(self, link: bool) -> Self {
        self.set("link", link.into())
    }
    /// Show the manifest's small copy where it has one.
    pub fn thumb(self, thumb: bool) -> Self {
        self.set("thumb", thumb.into())
    }
    /// `"lazy"` (the default) or `"eager"`.
    pub fn loading(self, loading: &str) -> Self {
        self.set("loading", loading.into())
    }
    /// The gallery options' `dimensions` and `groups`, so the screen's shots pair as they do in that gallery.
    pub fn gallery(mut self, options: &Options) -> Self {
        for key in ["dimensions", "groups"] {
            match options.raw.get(key) {
                Some(v) => self.raw.insert(key.into(), v.clone()),
                None => self.raw.remove(key),
            };
        }
        self
    }
    fn get(&self, key: &str) -> Option<&Value> {
        self.raw.get(key).filter(|v| !v.is_null())
    }
    fn check(&self, key: &str, ok: impl Fn(&Value) -> bool) -> Result<Option<&Value>, Error> {
        match self.get(key) {
            Some(v) if !ok(v) => Err(Error::Invalid(format!("screenshot option {key} is invalid"))),
            v => Ok(v),
        }
    }
}

struct Picked {
    src: String,
    src2x: Option<String>,
    width: u64,
    height: u64,
}

struct Shown {
    light: Picked,
    dark: Option<Picked>,
    href: String,
    link: bool,
    alt: String,
    loading: String,
}

fn fail<T>(message: String) -> Result<T, Error> {
    Err(Error::Invalid(message))
}

/// The screen's items in its group. When every one is a 2x shot, a 1x copy of each follows them: the 2x shots at half
/// their size. Otherwise the screen is the gallery's, 2x shots only as 2x copies.
fn screen_items(group: &Value, screen: &str, dims: &[crate::Dimension]) -> Vec<Value> {
    let items: Vec<Value> = group["items"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|item| parse_shot(item["name"].as_str().unwrap(), dims).key == screen)
        .cloned()
        .collect();
    if !items.iter().all(|item| parse_shot(item["name"].as_str().unwrap(), dims).x2) {
        return items;
    }
    let halves: Vec<Value> = items
        .iter()
        .map(|item| {
            // Whole numbers, checked with the manifest, though JSON may write them as 2880.0.
            let (w, h) = (item["width"].as_f64().unwrap() as u64, item["height"].as_f64().unwrap() as u64);
            let width = w.div_ceil(2);
            let height = (2 * h * width + w) / (2 * w);
            let base = EXTENSION.replace(item["name"].as_str().unwrap(), "").into_owned();
            let name = base.strip_suffix("-2x").unwrap_or(&base).to_string();
            json!({ "name": name, "url": item["url"], "width": width, "height": height, "thumb": item.get("thumb") })
        })
        .collect();
    items.into_iter().chain(halves).collect()
}

fn pick(v: &Variant, thumb: bool) -> Picked {
    match (&v.thumb, thumb) {
        (Some(t), true) => Picked { src: t.url.clone(), src2x: None, width: t.width, height: t.height },
        _ => Picked {
            src: v.url.clone(),
            src2x: v.url2x.clone().filter(|u| *u != v.url),
            width: v.width,
            height: v.height,
        },
    }
}

fn shown(manifest: &Value, options: &ScreenshotOptions) -> Result<Shown, Error> {
    check_manifest(manifest)?;
    let dims_opt = match options.get("dimensions") {
        Some(v) if !check_dimensions(v) => return fail("gallery option dimensions is invalid".into()),
        v => v,
    };
    let dims = resolve_dimensions(dims_opt);
    let keys = |dim: &str| -> Vec<String> {
        dims.iter().find(|d| d.key == dim).unwrap().values.iter().map(|v| v.key.clone()).collect()
    };
    let screen = match options.get("screen").and_then(Value::as_str) {
        Some(s) if !s.is_empty() => s.to_string(),
        _ => return fail("screenshot option screen is required".into()),
    };
    let group_opt = options.check("group", Value::is_string)?.and_then(Value::as_str);
    let theme = options.check("theme", |v| v.as_str().is_some_and(|s| keys("theme").iter().any(|k| k == s)))?;
    let theme = theme.and_then(Value::as_str);
    let size = options.check("size", |v| v.as_str().is_some_and(|s| keys("size").iter().any(|k| k == s)))?;
    let size = size.and_then(Value::as_str);
    let alt = options.check("alt", Value::is_string)?.and_then(Value::as_str);
    let link = options.check("link", Value::is_boolean)?.and_then(Value::as_bool) == Some(true);
    let thumb = options.check("thumb", Value::is_boolean)?.and_then(Value::as_bool) == Some(true);
    let loading = options.check("loading", |v| matches!(v.as_str(), Some("lazy" | "eager")))?;
    let loading = loading.and_then(Value::as_str).unwrap_or("lazy").to_string();
    let has = |g: &Value| {
        g["items"]
            .as_array()
            .unwrap()
            .iter()
            .any(|item| parse_shot(item["name"].as_str().unwrap(), &dims).key == screen)
    };
    let groups = manifest["groups"].as_array().unwrap();
    let group = match group_opt {
        Some(name) => {
            let Some(g) = groups.iter().find(|g| g["name"] == name) else {
                return fail(format!("the gallery manifest has no group {name}"));
            };
            if !has(g) {
                return fail(format!("gallery group {name} has no screen {screen}"));
            }
            g
        }
        None => match groups.iter().find(|g| has(g)) {
            Some(g) => g,
            None => return fail(format!("the gallery manifest has no screen {screen}")),
        },
    };
    let gname = group["name"].as_str().unwrap();
    let one = json!({ "groups": [{
        "name": gname,
        "title": group.get("title").cloned().unwrap_or(Value::Null),
        "items": screen_items(group, &screen, &dims),
    }] });
    let mut gallery = Options::default();
    for key in ["dimensions", "groups"] {
        if let Some(v) = options.get(key) {
            gallery = gallery.set(key, v.clone());
        }
    }
    let model = build_model(&one, &gallery)?;
    let sc = &model.groups[0].screens[0];
    let order: Vec<&str> = model.dimensions.iter().map(|d| d.key.as_str()).collect();
    // The values shown: each dimension's option, else the first value of the screen's first variant that has the
    // values chosen so far.
    let mut choice: Vec<(&str, String)> = Vec::new();
    for &k in &order {
        let asked = match k {
            "theme" => theme,
            "size" => size,
            _ => None,
        };
        let value = match asked {
            Some(a) => a.to_string(),
            None => {
                let fits = sc.variants.iter().find(|v| choice.iter().all(|(c, x)| v.values[*c] == *x));
                fits.unwrap_or(&sc.variants[0]).values[k].clone()
            }
        };
        choice.push((k, value));
    }
    let find = |c: &[(&str, String)]| sc.variants.iter().find(|v| c.iter().all(|(k, x)| v.values[*k] == *x));
    let Some(v) = find(&choice) else {
        let keys: Vec<&str> = choice.iter().map(|(_, x)| x.as_str()).collect();
        return fail(format!("gallery screen {screen} in group {gname} has no {} screenshot", keys.join(" ")));
    };
    // The dark shot, for readers whose setting is dark, when no theme was asked for; not when it's the same image.
    let chosen_theme = &choice.iter().find(|(k, _)| *k == "theme").unwrap().1;
    let found = if theme.is_none() && chosen_theme != "dark" {
        let dark: Vec<(&str, String)> =
            choice.iter().map(|(k, x)| (*k, if *k == "theme" { "dark".to_string() } else { x.clone() })).collect();
        find(&dark)
    } else {
        None
    };
    let dv = found.filter(|d| d.url != v.url || d.url2x != v.url2x);
    // The small copies only when every image shown has one, so light and dark readers see the same size.
    let use_thumb = thumb && v.thumb.is_some() && dv.is_none_or(|d| d.thumb.is_some());
    let text = alt.unwrap_or(&sc.title);
    let mut collapsed = String::new();
    let mut space = false;
    for c in text.chars() {
        if matches!(c, '\t' | '\n' | '\r' | ' ') {
            space = true;
        } else {
            if space {
                collapsed.push(' ');
                space = false;
            }
            collapsed.push(c);
        }
    }
    if space {
        collapsed.push(' ');
    }
    let alt = collapsed.strip_prefix(' ').unwrap_or(&collapsed);
    let alt = alt.strip_suffix(' ').unwrap_or(alt).to_string();
    Ok(Shown {
        light: pick(v, use_thumb),
        dark: dv.map(|d| pick(d, use_thumb)),
        href: v.url.clone(),
        link,
        alt,
        loading,
    })
}

fn srcset(p: &Picked) -> String {
    match &p.src2x {
        None => escape(&p.src),
        Some(x2) => format!("{}, {} 2x", escape(&p.src), escape(x2)),
    }
}

fn picture_html(s: &Shown) -> String {
    let l = &s.light;
    let set = if l.src2x.is_some() { format!(" srcset=\"{}\"", srcset(l)) } else { String::new() };
    let img = format!(
        "<img src=\"{}\"{set} width=\"{}\" height=\"{}\" alt=\"{}\" loading=\"{}\" decoding=\"async\">",
        escape(&l.src),
        l.width,
        l.height,
        escape(&s.alt),
        s.loading
    );
    let (open, close) =
        if s.link { (format!("<a href=\"{}\">", escape(&s.href)), "</a>") } else { (String::new(), "") };
    match &s.dark {
        None => format!("{open}{img}{close}\n"),
        Some(d) => {
            let source = format!(
                "<source media=\"(prefers-color-scheme: dark)\" srcset=\"{}\" width=\"{}\" height=\"{}\">",
                srcset(d),
                d.width,
                d.height
            );
            format!("{open}<picture>\n{source}\n{img}\n</picture>{close}\n")
        }
    }
}

/// One screenshot as HTML: an `<img>`, or a `<picture>` with the dark shot for readers whose setting is dark. Fails
/// when the manifest or the options are invalid, or the screen has no shot for what's asked.
pub fn screenshot(manifest: &Value, options: &ScreenshotOptions) -> Result<String, Error> {
    Ok(picture_html(&shown(manifest, options)?))
}

fn markdown_escape(s: &str, special: impl Fn(char) -> bool) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if special(c) {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/// One screenshot for a README: Markdown's `![alt](url)`, linked with `link`, or the HTML `<picture>` when it has a
/// dark shot.
pub fn screenshot_markdown(manifest: &Value, options: &ScreenshotOptions) -> Result<String, Error> {
    let s = shown(manifest, options)?;
    if s.dark.is_some() {
        return Ok(picture_html(&s));
    }
    let url = |u: &str| markdown_escape(u, |c| matches!(c, '\\' | '(' | ')' | '&'));
    let image = format!("![{}]({})", markdown_escape(&s.alt, |c| c.is_ascii_punctuation()), url(&s.light.src));
    Ok(if s.link { format!("[{image}]({})\n", url(&s.href)) } else { format!("{image}\n") })
}