Skip to main content

visualci_gallery/
screenshot.rs

1//! One screenshot from the gallery's manifest, for a page or a README: an `<img>`, or a `<picture>` that shows the
2//! dark shot when the reader's setting is dark (contract/SPEC.md, "A single screenshot"). A port of the JS library's
3//! screenshot.ts.
4
5use serde_json::{Map, Value, json};
6
7use crate::Error;
8use crate::model::{
9    EXTENSION, Options, Variant, build_model, check_dimensions, check_manifest, parse_shot, resolve_dimensions,
10};
11use crate::render::escape;
12
13/// What [`screenshot`] and [`screenshot_markdown`] show, as JSON-shaped values like the gallery's [`Options`]. Build
14/// them with [`ScreenshotOptions::new`] and the setters, or [`ScreenshotOptions::from_json`].
15#[derive(Debug, Clone, Default)]
16pub struct ScreenshotOptions {
17    raw: Map<String, Value>,
18}
19
20impl ScreenshotOptions {
21    /// The screen, by its key (`overview`, `ios/sessions`), as the gallery's `screens` and `order` name it.
22    pub fn new(screen: &str) -> Self {
23        ScreenshotOptions::default().set("screen", screen.into())
24    }
25    /// Options from a JSON object with the contract's names.
26    pub fn from_json(value: &Value) -> Result<Self, Error> {
27        match value {
28            Value::Object(m) => Ok(ScreenshotOptions { raw: m.clone() }),
29            _ => Err(Error::Invalid("screenshot options must be an object".into())),
30        }
31    }
32    fn set(mut self, key: &str, value: Value) -> Self {
33        self.raw.insert(key.to_string(), value);
34        self
35    }
36    /// The group it's in. Default: the first group that has the screen.
37    pub fn group(self, name: &str) -> Self {
38        self.set("group", name.into())
39    }
40    /// The theme value to show. Default: the screen's first, with its dark shot for readers whose setting is dark.
41    pub fn theme(self, theme: &str) -> Self {
42        self.set("theme", theme.into())
43    }
44    /// The size value to show. Default: the screen's first that has the theme.
45    pub fn size(self, size: &str) -> Self {
46        self.set("size", size.into())
47    }
48    /// The image's alt text. Default: the screen's title, made from its key.
49    pub fn alt(self, alt: &str) -> Self {
50        self.set("alt", alt.into())
51    }
52    /// Link the image to its full-size original.
53    pub fn link(self, link: bool) -> Self {
54        self.set("link", link.into())
55    }
56    /// Show the manifest's small copy where it has one.
57    pub fn thumb(self, thumb: bool) -> Self {
58        self.set("thumb", thumb.into())
59    }
60    /// `"lazy"` (the default) or `"eager"`.
61    pub fn loading(self, loading: &str) -> Self {
62        self.set("loading", loading.into())
63    }
64    /// The gallery options' `dimensions` and `groups`, so the screen's shots pair as they do in that gallery.
65    pub fn gallery(mut self, options: &Options) -> Self {
66        for key in ["dimensions", "groups"] {
67            match options.raw.get(key) {
68                Some(v) => self.raw.insert(key.into(), v.clone()),
69                None => self.raw.remove(key),
70            };
71        }
72        self
73    }
74    fn get(&self, key: &str) -> Option<&Value> {
75        self.raw.get(key).filter(|v| !v.is_null())
76    }
77    fn check(&self, key: &str, ok: impl Fn(&Value) -> bool) -> Result<Option<&Value>, Error> {
78        match self.get(key) {
79            Some(v) if !ok(v) => Err(Error::Invalid(format!("screenshot option {key} is invalid"))),
80            v => Ok(v),
81        }
82    }
83}
84
85struct Picked {
86    src: String,
87    src2x: Option<String>,
88    width: u64,
89    height: u64,
90}
91
92struct Shown {
93    light: Picked,
94    dark: Option<Picked>,
95    href: String,
96    link: bool,
97    alt: String,
98    loading: String,
99}
100
101fn fail<T>(message: String) -> Result<T, Error> {
102    Err(Error::Invalid(message))
103}
104
105/// 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
106/// their size. Otherwise the screen is the gallery's, 2x shots only as 2x copies.
107fn screen_items(group: &Value, screen: &str, dims: &[crate::Dimension]) -> Vec<Value> {
108    let items: Vec<Value> = group["items"]
109        .as_array()
110        .unwrap()
111        .iter()
112        .filter(|item| parse_shot(item["name"].as_str().unwrap(), dims).key == screen)
113        .cloned()
114        .collect();
115    if !items.iter().all(|item| parse_shot(item["name"].as_str().unwrap(), dims).x2) {
116        return items;
117    }
118    let halves: Vec<Value> = items
119        .iter()
120        .map(|item| {
121            // Whole numbers, checked with the manifest, though JSON may write them as 2880.0.
122            let (w, h) = (item["width"].as_f64().unwrap() as u64, item["height"].as_f64().unwrap() as u64);
123            let width = w.div_ceil(2);
124            let height = (2 * h * width + w) / (2 * w);
125            let base = EXTENSION.replace(item["name"].as_str().unwrap(), "").into_owned();
126            let name = base.strip_suffix("-2x").unwrap_or(&base).to_string();
127            json!({ "name": name, "url": item["url"], "width": width, "height": height, "thumb": item.get("thumb") })
128        })
129        .collect();
130    items.into_iter().chain(halves).collect()
131}
132
133fn pick(v: &Variant, thumb: bool) -> Picked {
134    match (&v.thumb, thumb) {
135        (Some(t), true) => Picked { src: t.url.clone(), src2x: None, width: t.width, height: t.height },
136        _ => Picked {
137            src: v.url.clone(),
138            src2x: v.url2x.clone().filter(|u| *u != v.url),
139            width: v.width,
140            height: v.height,
141        },
142    }
143}
144
145fn shown(manifest: &Value, options: &ScreenshotOptions) -> Result<Shown, Error> {
146    check_manifest(manifest)?;
147    let dims_opt = match options.get("dimensions") {
148        Some(v) if !check_dimensions(v) => return fail("gallery option dimensions is invalid".into()),
149        v => v,
150    };
151    let dims = resolve_dimensions(dims_opt);
152    let keys = |dim: &str| -> Vec<String> {
153        dims.iter().find(|d| d.key == dim).unwrap().values.iter().map(|v| v.key.clone()).collect()
154    };
155    let screen = match options.get("screen").and_then(Value::as_str) {
156        Some(s) if !s.is_empty() => s.to_string(),
157        _ => return fail("screenshot option screen is required".into()),
158    };
159    let group_opt = options.check("group", Value::is_string)?.and_then(Value::as_str);
160    let theme = options.check("theme", |v| v.as_str().is_some_and(|s| keys("theme").iter().any(|k| k == s)))?;
161    let theme = theme.and_then(Value::as_str);
162    let size = options.check("size", |v| v.as_str().is_some_and(|s| keys("size").iter().any(|k| k == s)))?;
163    let size = size.and_then(Value::as_str);
164    let alt = options.check("alt", Value::is_string)?.and_then(Value::as_str);
165    let link = options.check("link", Value::is_boolean)?.and_then(Value::as_bool) == Some(true);
166    let thumb = options.check("thumb", Value::is_boolean)?.and_then(Value::as_bool) == Some(true);
167    let loading = options.check("loading", |v| matches!(v.as_str(), Some("lazy" | "eager")))?;
168    let loading = loading.and_then(Value::as_str).unwrap_or("lazy").to_string();
169    let has = |g: &Value| {
170        g["items"]
171            .as_array()
172            .unwrap()
173            .iter()
174            .any(|item| parse_shot(item["name"].as_str().unwrap(), &dims).key == screen)
175    };
176    let groups = manifest["groups"].as_array().unwrap();
177    let group = match group_opt {
178        Some(name) => {
179            let Some(g) = groups.iter().find(|g| g["name"] == name) else {
180                return fail(format!("the gallery manifest has no group {name}"));
181            };
182            if !has(g) {
183                return fail(format!("gallery group {name} has no screen {screen}"));
184            }
185            g
186        }
187        None => match groups.iter().find(|g| has(g)) {
188            Some(g) => g,
189            None => return fail(format!("the gallery manifest has no screen {screen}")),
190        },
191    };
192    let gname = group["name"].as_str().unwrap();
193    let one = json!({ "groups": [{
194        "name": gname,
195        "title": group.get("title").cloned().unwrap_or(Value::Null),
196        "items": screen_items(group, &screen, &dims),
197    }] });
198    let mut gallery = Options::default();
199    for key in ["dimensions", "groups"] {
200        if let Some(v) = options.get(key) {
201            gallery = gallery.set(key, v.clone());
202        }
203    }
204    let model = build_model(&one, &gallery)?;
205    let sc = &model.groups[0].screens[0];
206    let order: Vec<&str> = model.dimensions.iter().map(|d| d.key.as_str()).collect();
207    // The values shown: each dimension's option, else the first value of the screen's first variant that has the
208    // values chosen so far.
209    let mut choice: Vec<(&str, String)> = Vec::new();
210    for &k in &order {
211        let asked = match k {
212            "theme" => theme,
213            "size" => size,
214            _ => None,
215        };
216        let value = match asked {
217            Some(a) => a.to_string(),
218            None => {
219                let fits = sc.variants.iter().find(|v| choice.iter().all(|(c, x)| v.values[*c] == *x));
220                fits.unwrap_or(&sc.variants[0]).values[k].clone()
221            }
222        };
223        choice.push((k, value));
224    }
225    let find = |c: &[(&str, String)]| sc.variants.iter().find(|v| c.iter().all(|(k, x)| v.values[*k] == *x));
226    let Some(v) = find(&choice) else {
227        let keys: Vec<&str> = choice.iter().map(|(_, x)| x.as_str()).collect();
228        return fail(format!("gallery screen {screen} in group {gname} has no {} screenshot", keys.join(" ")));
229    };
230    // The dark shot, for readers whose setting is dark, when no theme was asked for; not when it's the same image.
231    let chosen_theme = &choice.iter().find(|(k, _)| *k == "theme").unwrap().1;
232    let found = if theme.is_none() && chosen_theme != "dark" {
233        let dark: Vec<(&str, String)> =
234            choice.iter().map(|(k, x)| (*k, if *k == "theme" { "dark".to_string() } else { x.clone() })).collect();
235        find(&dark)
236    } else {
237        None
238    };
239    let dv = found.filter(|d| d.url != v.url || d.url2x != v.url2x);
240    // The small copies only when every image shown has one, so light and dark readers see the same size.
241    let use_thumb = thumb && v.thumb.is_some() && dv.is_none_or(|d| d.thumb.is_some());
242    let text = alt.unwrap_or(&sc.title);
243    let mut collapsed = String::new();
244    let mut space = false;
245    for c in text.chars() {
246        if matches!(c, '\t' | '\n' | '\r' | ' ') {
247            space = true;
248        } else {
249            if space {
250                collapsed.push(' ');
251                space = false;
252            }
253            collapsed.push(c);
254        }
255    }
256    if space {
257        collapsed.push(' ');
258    }
259    let alt = collapsed.strip_prefix(' ').unwrap_or(&collapsed);
260    let alt = alt.strip_suffix(' ').unwrap_or(alt).to_string();
261    Ok(Shown {
262        light: pick(v, use_thumb),
263        dark: dv.map(|d| pick(d, use_thumb)),
264        href: v.url.clone(),
265        link,
266        alt,
267        loading,
268    })
269}
270
271fn srcset(p: &Picked) -> String {
272    match &p.src2x {
273        None => escape(&p.src),
274        Some(x2) => format!("{}, {} 2x", escape(&p.src), escape(x2)),
275    }
276}
277
278fn picture_html(s: &Shown) -> String {
279    let l = &s.light;
280    let set = if l.src2x.is_some() { format!(" srcset=\"{}\"", srcset(l)) } else { String::new() };
281    let img = format!(
282        "<img src=\"{}\"{set} width=\"{}\" height=\"{}\" alt=\"{}\" loading=\"{}\" decoding=\"async\">",
283        escape(&l.src),
284        l.width,
285        l.height,
286        escape(&s.alt),
287        s.loading
288    );
289    let (open, close) =
290        if s.link { (format!("<a href=\"{}\">", escape(&s.href)), "</a>") } else { (String::new(), "") };
291    match &s.dark {
292        None => format!("{open}{img}{close}\n"),
293        Some(d) => {
294            let source = format!(
295                "<source media=\"(prefers-color-scheme: dark)\" srcset=\"{}\" width=\"{}\" height=\"{}\">",
296                srcset(d),
297                d.width,
298                d.height
299            );
300            format!("{open}<picture>\n{source}\n{img}\n</picture>{close}\n")
301        }
302    }
303}
304
305/// One screenshot as HTML: an `<img>`, or a `<picture>` with the dark shot for readers whose setting is dark. Fails
306/// when the manifest or the options are invalid, or the screen has no shot for what's asked.
307pub fn screenshot(manifest: &Value, options: &ScreenshotOptions) -> Result<String, Error> {
308    Ok(picture_html(&shown(manifest, options)?))
309}
310
311fn markdown_escape(s: &str, special: impl Fn(char) -> bool) -> String {
312    let mut out = String::with_capacity(s.len());
313    for c in s.chars() {
314        if special(c) {
315            out.push('\\');
316        }
317        out.push(c);
318    }
319    out
320}
321
322/// One screenshot for a README: Markdown's `![alt](url)`, linked with `link`, or the HTML `<picture>` when it has a
323/// dark shot.
324pub fn screenshot_markdown(manifest: &Value, options: &ScreenshotOptions) -> Result<String, Error> {
325    let s = shown(manifest, options)?;
326    if s.dark.is_some() {
327        return Ok(picture_html(&s));
328    }
329    let url = |u: &str| markdown_escape(u, |c| matches!(c, '\\' | '(' | ')' | '&'));
330    let image = format!("![{}]({})", markdown_escape(&s.alt, |c| c.is_ascii_punctuation()), url(&s.light.src));
331    Ok(if s.link { format!("[{image}]({})\n", url(&s.href)) } else { format!("{image}\n") })
332}