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
//! A screenshots page from a VisualCI [public gallery](https://visualci.com/docs/gallery/) manifest, rendered in Rust
//! as the gallery contract's markup: byte for byte what the `visualci-gallery` JS library renders, so its script
//! hydrates it (tabs, light and dark, desktop and phone and any dimension a site adds, the full-size view).
//!
//! ```no_run
//! # fn main() -> Result<(), visualci_gallery::Error> {
//! use visualci_gallery::{Gallery, Options};
//!
//! // The manifest a build step wrote (a copy of https://app.visualci.com/g/<org>/<project>.json).
//! let manifest = std::fs::read_to_string("screenshots.json").expect("the build writes it");
//! let gallery = Gallery::from_json(&manifest, &Options::default().title(None))?;
//! let html = gallery.to_string();
//! # Ok(()) }
//! ```
//!
//! There is no fallback: rendering fails when the manifest has nothing to show or the options are invalid, and
//! [`fetch`] (feature `fetch`) fails when the manifest can't be read. Read it when the site builds, fail the build if
//! it can't be, and render from that copy.
//!
//! With the `askama` feature, [`Gallery`] is safe HTML to Askama: a template writes `{{ gallery }}`.

mod model;
mod render;
mod screenshot;

use std::fmt;

pub use model::{
    Dimension, DimensionValue, Group, Missing, Model, NEW_DAYS, Options, Preload, PreloadCaps, SEARCH_FROM,
    SEE_ALL_TEXT, Screen, SeeAll, Shape, Shot, TEXT_DEFAULTS, Text, Thumb, Values, Variant, build_model,
    default_dimensions, humanize, parse_shot, slugify,
};
pub use render::{escape, render_model};
pub use screenshot::{ScreenshotOptions, screenshot, screenshot_markdown};

/// Why a gallery can't be shown.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    /// The manifest or the options are invalid, or nothing in the manifest can be shown. The message is the
    /// contract's, word for word (contract/errors/*.message).
    Invalid(String),
    /// The manifest couldn't be read: "The screenshots gallery couldn't read <url>: <why>".
    Fetch(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Invalid(m) | Error::Fetch(m) => f.write_str(m),
        }
    }
}

impl std::error::Error for Error {}

/// A rendered gallery. Displays as its HTML; with the `askama` feature, Askama doesn't escape it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Gallery {
    html: String,
}

impl Gallery {
    /// The gallery for a parsed manifest.
    pub fn new(manifest: &serde_json::Value, options: &Options) -> Result<Self, Error> {
        Ok(Gallery { html: render(manifest, options)? })
    }

    /// The gallery for a manifest's JSON text (a file the build wrote, or `include_str!`).
    pub fn from_json(manifest: &str, options: &Options) -> Result<Self, Error> {
        let value = serde_json::from_str(manifest)
            .map_err(|e| Error::Invalid(format!("not a gallery manifest: it isn't JSON ({e})")))?;
        Self::new(&value, options)
    }

    pub fn as_str(&self) -> &str {
        &self.html
    }
}

impl fmt::Display for Gallery {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.html)
    }
}

#[cfg(feature = "askama")]
impl askama::filters::HtmlSafe for Gallery {}

/// The gallery's HTML for a parsed manifest.
pub fn render(manifest: &serde_json::Value, options: &Options) -> Result<String, Error> {
    Ok(render_model(&build_model(manifest, options)?))
}

/// The manifest at `url`, parsed: tried `attempts` times, each within `timeout`. Fails, naming the URL, when it can't
/// be read (a network error, a timeout, a status other than 200, JSON that doesn't parse).
#[cfg(feature = "fetch")]
pub fn fetch(url: &str, timeout: std::time::Duration, attempts: u32) -> Result<serde_json::Value, Error> {
    let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(timeout)).build().into();
    let attempts = attempts.max(1);
    let mut last = String::new();
    for i in 0..attempts {
        let result = agent.get(url).call().map_err(|e| match e {
            ureq::Error::StatusCode(code) => format!("HTTP {code}"),
            e => e.to_string(),
        });
        match result.and_then(|mut res| {
            if res.status() != 200 {
                return Err(format!("HTTP {}", res.status().as_u16()));
            }
            let text = res.body_mut().read_to_string().map_err(|e| e.to_string())?;
            serde_json::from_str(&text).map_err(|e| e.to_string())
        }) {
            Ok(v) => return Ok(v),
            Err(e) => last = e,
        }
        if i + 1 < attempts {
            std::thread::sleep(std::time::Duration::from_secs(u64::from(i) + 1));
        }
    }
    Err(Error::Fetch(format!("The screenshots gallery couldn't read {url}: {last}")))
}