Skip to main content

visualci_gallery/
lib.rs

1//! A screenshots page from a VisualCI [public gallery](https://visualci.com/docs/gallery/) manifest, rendered in Rust
2//! as the gallery contract's markup: byte for byte what the `visualci-gallery` JS library renders, so its script
3//! hydrates it (tabs, light and dark, desktop and phone and any dimension a site adds, the full-size view).
4//!
5//! ```no_run
6//! # fn main() -> Result<(), visualci_gallery::Error> {
7//! use visualci_gallery::{Gallery, Options};
8//!
9//! // The manifest a build step wrote (a copy of https://app.visualci.com/g/<org>/<project>.json).
10//! let manifest = std::fs::read_to_string("screenshots.json").expect("the build writes it");
11//! let gallery = Gallery::from_json(&manifest, &Options::default().title(None))?;
12//! let html = gallery.to_string();
13//! # Ok(()) }
14//! ```
15//!
16//! There is no fallback: rendering fails when the manifest has nothing to show or the options are invalid, and
17//! [`fetch`] (feature `fetch`) fails when the manifest can't be read. Read it when the site builds, fail the build if
18//! it can't be, and render from that copy.
19//!
20//! With the `askama` feature, [`Gallery`] is safe HTML to Askama: a template writes `{{ gallery }}`.
21
22mod model;
23mod render;
24mod screenshot;
25
26use std::fmt;
27
28pub use model::{
29    Dimension, DimensionValue, Group, Missing, Model, NEW_DAYS, Options, Preload, PreloadCaps, SEARCH_FROM,
30    SEE_ALL_TEXT, Screen, SeeAll, Shape, Shot, TEXT_DEFAULTS, Text, Thumb, Values, Variant, Version, Versions,
31    build_model, default_dimensions, humanize, options_json, parse_shot, slugify,
32};
33pub use render::{escape, render_model};
34pub use screenshot::{ScreenshotOptions, screenshot, screenshot_markdown};
35
36/// Why a gallery can't be shown.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum Error {
39    /// The manifest or the options are invalid, or nothing in the manifest can be shown. The message is the
40    /// contract's, word for word (contract/errors/*.message).
41    Invalid(String),
42    /// The manifest couldn't be read: "The screenshots gallery couldn't read <url>: <why>".
43    Fetch(String),
44}
45
46impl fmt::Display for Error {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self {
49            Error::Invalid(m) | Error::Fetch(m) => f.write_str(m),
50        }
51    }
52}
53
54impl std::error::Error for Error {}
55
56/// A rendered gallery. Displays as its HTML; with the `askama` feature, Askama doesn't escape it.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct Gallery {
59    html: String,
60}
61
62impl Gallery {
63    /// The gallery for a parsed manifest.
64    pub fn new(manifest: &serde_json::Value, options: &Options) -> Result<Self, Error> {
65        Ok(Gallery { html: render(manifest, options)? })
66    }
67
68    /// The gallery for a manifest's JSON text (a file the build wrote, or `include_str!`).
69    pub fn from_json(manifest: &str, options: &Options) -> Result<Self, Error> {
70        let value = serde_json::from_str(manifest)
71            .map_err(|e| Error::Invalid(format!("not a gallery manifest: it isn't JSON ({e})")))?;
72        Self::new(&value, options)
73    }
74
75    pub fn as_str(&self) -> &str {
76        &self.html
77    }
78}
79
80impl fmt::Display for Gallery {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.write_str(&self.html)
83    }
84}
85
86#[cfg(feature = "askama")]
87impl askama::filters::HtmlSafe for Gallery {}
88
89/// The gallery's HTML for a parsed manifest.
90pub fn render(manifest: &serde_json::Value, options: &Options) -> Result<String, Error> {
91    Ok(render_model(&build_model(manifest, options)?))
92}
93
94/// The manifest to read for `url`: the main one, or with `reference` (a version's label or key, `v2.0.0`), that
95/// version's, `…/<project>@<key>.json` (contract/SPEC.md, "Pinning a version"). The key is the server's: ASCII lower
96/// case, each run of anything else one hyphen, none at either end. Fails when that key is empty or `latest`, or `url`
97/// doesn't end in `.json`.
98pub fn manifest_url(url: &str, reference: Option<&str>) -> Result<String, Error> {
99    let Some(reference) = reference else { return Ok(url.to_string()) };
100    let mut key = String::new();
101    let mut dash = false;
102    for c in reference.chars() {
103        let c = c.to_ascii_lowercase();
104        if c.is_ascii_lowercase() || c.is_ascii_digit() {
105            if dash && !key.is_empty() {
106                key.push('-');
107            }
108            dash = false;
109            key.push(c);
110        } else {
111            dash = true;
112        }
113    }
114    match url.strip_suffix(".json") {
115        Some(base) if !key.is_empty() && key != "latest" => Ok(format!("{base}@{key}.json")),
116        _ => Err(Error::Invalid("gallery option ref is invalid".into())),
117    }
118}
119
120/// The manifest at `url`, parsed: tried `attempts` times, each within `timeout`. Fails, naming the URL, when it can't
121/// be read (a network error, a timeout, a status other than 200, JSON that doesn't parse).
122#[cfg(feature = "fetch")]
123pub fn fetch(url: &str, timeout: std::time::Duration, attempts: u32) -> Result<serde_json::Value, Error> {
124    let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(timeout)).build().into();
125    let attempts = attempts.max(1);
126    let mut last = String::new();
127    for i in 0..attempts {
128        let result = agent.get(url).call().map_err(|e| match e {
129            ureq::Error::StatusCode(code) => format!("HTTP {code}"),
130            e => e.to_string(),
131        });
132        match result.and_then(|mut res| {
133            if res.status() != 200 {
134                return Err(format!("HTTP {}", res.status().as_u16()));
135            }
136            let text = res.body_mut().read_to_string().map_err(|e| e.to_string())?;
137            serde_json::from_str(&text).map_err(|e| e.to_string())
138        }) {
139            Ok(v) => return Ok(v),
140            Err(e) => last = e,
141        }
142        if i + 1 < attempts {
143            std::thread::sleep(std::time::Duration::from_secs(u64::from(i) + 1));
144        }
145    }
146    Err(Error::Fetch(format!("The screenshots gallery couldn't read {url}: {last}")))
147}