# Gallery in Rust

> Render a screenshots page from your VisualCI gallery in Rust, in a build step, an Askama template, a Loco controller or an axum handler, with the visualci-gallery crate.

Source: https://visualci.com/docs/gallery/rust/
All of VisualCI's documentation: https://visualci.com/llms.txt

The [`visualci-gallery`](https://crates.io/crates/visualci-gallery) crate turns your [gallery's manifest](https://visualci.com/docs/gallery.md) into a screenshots page: tabs per group, light and dark, desktop and phone, and a full-size view. It renders the HTML on your server, the same HTML the JS library renders, and the JS library's script brings it to life in the browser.

Every example on this page is a file in [clients/gallery/rust/examples](https://github.com/DocSpring/visualci/tree/main/clients/gallery/rust/examples), run by tests.

## Install

Add the crate with the features you need:

<!-- example: clients/gallery/rust/examples/loco/Cargo.toml#dependencies -->

```toml
visualci-gallery = { version = "=0.7.0", features = ["askama", "fetch"] }
askama = "0.16"
```

- `fetch` adds `visualci_gallery::fetch`, which reads the manifest over HTTPS (blocking, with ureq).
- `askama` lets an Askama 0.16 template write a `Gallery` without escaping it.

Without features you get `Gallery::new` (a parsed manifest) and `Gallery::from_json` (the manifest's text). Pin the exact version, with `=`, so the crate only changes when you change the script's version too (see [Versions](#versions)).

The crate doesn't ship the stylesheet and the script. Your page links them from the `visualci-gallery` npm package, at the same version:

```text
https://cdn.jsdelivr.net/npm/visualci-gallery@0.7.0/dist/gallery.css
https://cdn.jsdelivr.net/npm/visualci-gallery@0.7.0/dist/gallery.iife.js
```

After the script, call `VisualCIGallery.hydrate` on each gallery. Every example below does.

## Render a page

For a static site or a build step, fetch the manifest, render it, and write the page. `Gallery` displays as its HTML:

<!-- example: clients/gallery/rust/examples/plain.rs#page -->

```rust
use std::time::Duration;

use visualci_gallery::{Error, Gallery, Options};

const MANIFEST: &str = "https://app.visualci.com/g/acme/web.json";

pub fn page(manifest_url: &str) -> Result<String, Error> {
    // Three tries, 20 seconds each. Err when VisualCI can't be read or the manifest has nothing to show.
    let manifest = visualci_gallery::fetch(manifest_url, Duration::from_secs(20), 3)?;
    let gallery = Gallery::new(&manifest, &Options::default())?;
    Ok(format!(
        r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Screenshots</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/visualci-gallery@0.7.0/dist/gallery.css">
</head>
<body>
{gallery}<script src="https://cdn.jsdelivr.net/npm/visualci-gallery@0.7.0/dist/gallery.iife.js"></script>
<script>document.querySelectorAll("[data-vg]").forEach(function (el) {{ VisualCIGallery.hydrate(el); }});</script>
</body>
</html>
"#
    ))
}

fn main() -> std::process::ExitCode {
    match page(MANIFEST) {
        Ok(html) => {
            print!("{html}");
            std::process::ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("{e}");
            std::process::ExitCode::FAILURE
        }
    }
}
```

Replace `acme/web` with your organization and project. The script's braces are doubled because the page is a `format!` string. The program exits with an error when the manifest can't be read, so the build that runs it fails.

## Askama

With the `askama` feature, a `Gallery` is safe HTML to Askama, so the template writes `{{ gallery }}` and Askama leaves it as it is. This is `templates/screenshots.html`:

<!-- example: clients/gallery/rust/templates/screenshots.html -->

```html
<!doctype html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Screenshots</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/visualci-gallery@0.7.0/dist/gallery.css">
<style>
  .vg {
    --vg-accent: #2563eb;
    --vg-radius-md: 6px;
  }
  [data-theme="dark"] .vg {
    --vg-accent: #60a5fa;
  }
</style>
</head>
<body>
<main>
{{ gallery }}
</main>
<script src="https://cdn.jsdelivr.net/npm/visualci-gallery@0.7.0/dist/gallery.iife.js"></script>
<script>document.querySelectorAll("[data-vg]").forEach(function (el) { VisualCIGallery.hydrate(el); });</script>
</body>
</html>
```

The feature is built for Askama 0.16. With another version, or without the feature, pass `gallery.to_string()` and write `{{ gallery|safe }}`: Askama escapes anything it doesn't know is safe, and the page would show the HTML as text.

This renders the template from a manifest a CI step saved, with `curl -fsS https://app.visualci.com/g/acme/web.json -o screenshots.json` (`-f` fails the step when VisualCI can't be read):

<!-- example: clients/gallery/rust/examples/askama_template.rs#page -->

```rust
use askama::Template;
use visualci_gallery::{Gallery, Options};

#[derive(Template)]
#[template(path = "screenshots.html")]
pub struct ScreenshotsPage {
    pub gallery: Gallery,
}

pub fn render_page(manifest_path: &str) -> Result<String, Box<dyn std::error::Error>> {
    let manifest = std::fs::read_to_string(manifest_path).map_err(|e| format!("couldn't read {manifest_path}: {e}"))?;
    let gallery = Gallery::from_json(&manifest, &Options::default())?;
    Ok(ScreenshotsPage { gallery }.render()?)
}
```

## Loco

A Loco app reads the manifest once, when it boots, and keeps the gallery in its shared store. A request renders from that copy, so it never waits on VisualCI and never fails because of it. Each image URL always serves the approved version, so a changed screenshot shows on the page at once. A new screenshot, or one whose size changed, waits until the app restarts, at your next deploy.

Put the manifest's URL in your config's `settings` (`config/development.yaml`, and the same in production's):

<!-- example: clients/gallery/rust/examples/loco/config/development.yaml#settings -->

```yaml
settings:
  gallery_manifest: https://app.visualci.com/g/acme/web.json
```

In `src/app.rs`, read it in `after_context`. `fetch` blocks, so it runs on Tokio's blocking pool:

<!-- example: clients/gallery/rust/examples/loco/src/app.rs#uses -->

```rust
use std::sync::Arc;
use std::time::Duration;

use loco_rs::{Error, Result};
use serde::Deserialize;
use visualci_gallery::{Gallery, Options};
```

<!-- example: clients/gallery/rust/examples/loco/src/app.rs#settings -->

```rust
/// config/*.yaml's `settings:`.
#[derive(Deserialize)]
struct Settings {
    gallery_manifest: String,
}
```

<!-- example: clients/gallery/rust/examples/loco/src/app.rs#after_context -->

```rust
/// The gallery, read once at boot and kept in the shared store. When the manifest can't be read, the app doesn't
/// start, so a deploy fails and the running version keeps serving.
async fn after_context(ctx: AppContext) -> Result<AppContext> {
    let settings: Settings = ctx.config.settings()?;
    let gallery = tokio::task::spawn_blocking(move || {
        let manifest = visualci_gallery::fetch(&settings.gallery_manifest, Duration::from_secs(20), 3)?;
        Gallery::new(&manifest, &Options::default().heading_level(1))
    })
    .await
    .map_err(Error::wrap)?
    .map_err(Error::wrap)?;
    ctx.shared_store.insert(Arc::new(gallery));
    Ok(ctx)
}
```

If your app already has a `settings` struct, add `gallery_manifest` to it. The controller, `src/controllers/screenshots.rs`, takes the gallery with Loco's `SharedStore` extractor and renders the Askama template above (Askama reads templates from `templates/` beside `Cargo.toml`):

<!-- example: clients/gallery/rust/examples/loco/src/controllers/screenshots.rs -->

```rust
use std::sync::Arc;

use askama::Template;
use loco_rs::prelude::*;
use visualci_gallery::Gallery;

#[derive(Template)]
#[template(path = "screenshots.html")]
struct ScreenshotsPage<'a> {
    gallery: &'a Gallery,
}

async fn index(SharedStore(gallery): SharedStore<Arc<Gallery>>) -> Result<Response> {
    let page = ScreenshotsPage { gallery: &gallery };
    format::html(&page.render().map_err(Error::wrap)?)
}

pub fn routes() -> Routes {
    Routes::new().prefix("screenshots").add("/", get(index))
}
```

Add `pub mod screenshots;` to `src/controllers/mod.rs` and register the routes in `src/app.rs`:

<!-- example: clients/gallery/rust/examples/loco/src/app.rs#routes -->

```rust
fn routes(_ctx: &AppContext) -> AppRoutes {
    AppRoutes::with_default_routes().add_route(controllers::screenshots::routes())
}
```

The page is at `/screenshots`. When the manifest can't be read, `cargo loco start` exits with the error (`The screenshots gallery couldn't read https://app.visualci.com/g/acme/web.json: HTTP 503`), and the new version never starts serving.

## axum

Loco runs on axum, and the same approach works in a plain axum app: read the manifest before the server listens, keep the gallery in the router's state, and render it in a handler. This one also renders the [homepage band](#a-band-on-the-homepage) from the same manifest:

<!-- example: clients/gallery/rust/examples/axum_app.rs#load -->

```rust
#[derive(Clone)]
pub struct Galleries {
    pub page: Arc<Gallery>,
    pub band: Arc<Gallery>,
}

pub fn load(manifest_url: &str) -> Result<Galleries, Error> {
    let manifest = visualci_gallery::fetch(manifest_url, Duration::from_secs(20), 3)?;
    Ok(Galleries {
        page: Arc::new(Gallery::new(&manifest, &options())?),
        band: Arc::new(Gallery::new(&manifest, &band_options())?),
    })
}
```

<!-- example: clients/gallery/rust/examples/axum_app.rs#routes -->

```rust
#[derive(Template)]
#[template(path = "screenshots.html")]
struct ScreenshotsPage<'a> {
    gallery: &'a Gallery,
}

#[derive(Template)]
#[template(path = "home.html")]
struct HomePage<'a> {
    band: &'a Gallery,
}

async fn screenshots(State(galleries): State<Galleries>) -> Result<Html<String>, StatusCode> {
    let page = ScreenshotsPage { gallery: &galleries.page };
    page.render().map(Html).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}

async fn home(State(galleries): State<Galleries>) -> Result<Html<String>, StatusCode> {
    let page = HomePage { band: &galleries.band };
    page.render().map(Html).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}

pub fn app(galleries: Galleries) -> Router {
    Router::new().route("/", get(home)).route("/screenshots/", get(screenshots)).with_state(galleries)
}
```

<!-- example: clients/gallery/rust/examples/axum_app.rs#main -->

```rust
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Before the server listens: when the manifest can't be read, the process exits with the error and the deploy
    // fails, so the running version keeps serving.
    let galleries = tokio::task::spawn_blocking(|| load(MANIFEST)).await??;
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    axum::serve(listener, app(galleries)).await?;
    Ok(())
}
```

The whole file, with its imports, is [examples/axum_app.rs](https://github.com/DocSpring/visualci/blob/main/clients/gallery/rust/examples/axum_app.rs).

## Options

`Options::default()` gives the defaults. Each setter returns the options, so they chain:

<!-- example: clients/gallery/rust/examples/axum_app.rs#options -->

```rust
pub fn options() -> Options {
    Options::default()
        .heading_level(1)
        .screen("overview", Some("Overview"), Some("Everything at a glance."))
        .order(&["overview", "access"])
        .group("Web", Some("In the browser"), None, None)
        .group("Mac approver", None, Some("desktop"), Some("contain"))
        .group_order(&["Web", "iPhone"])
        .theme_switch(false)
}
```

The setters are `title`, `heading_level`, `id`, `screen` (a screen's title and caption, by key), `order`, `group` (a group's title, size and fit, by name), `group_order`, `credit`, `layout`, `theme_switch`, `see_all`, `preload`, `preload_caps`, `deep_links`, `search` and `search_from` (the search box always or never, or from a number of screens), `zoom`, `new_badges` and `new_badges_days` (the New badge, for 30 days or your own number), and `text` (one of the gallery's own words, by key: `.text("close", "Fermer")`; see [Your own words](https://visualci.com/docs/gallery/options.md#your-own-words)). `title(None)` leaves out the heading. `Options::from_json` takes the same options as a `&serde_json::Value` object, with the names the JS library uses (`headingLevel`, `themeSwitch`). [Gallery options](https://visualci.com/docs/gallery/options.md) says what each one does.

After the page has loaded, the gallery preloads the images a reader is likely to look at next. `.preload(false)` turns that off, and `.preload_caps(None, Some(200), Some(20_000_000), None)` sets your own limits (fold, count, bytes and requests at once; `None` keeps a default). It's on by default, and [Preloading](https://visualci.com/docs/gallery/options.md#preloading) says what it fetches and when.

An invalid option (an `id` that isn't a valid id, a `layout` other than `"grid"` or `"strip"`) is an error when the gallery renders, `Error::Invalid` with a message that names it. In the examples above that's at build time or at boot, never in a request.

## Theming

Set the `--vg-*` CSS variables on `.vg` to your site's colours, radii and type. The template above sets two, and changes the accent in the site's dark theme:

<!-- example: clients/gallery/rust/templates/screenshots.html#theme -->

```html
<style>
  .vg {
    --vg-accent: #2563eb;
    --vg-radius-md: 6px;
  }
  [data-theme="dark"] .vg {
    --vg-accent: #60a5fa;
  }
</style>
```

Out of the box the gallery follows your page's text colour and `color-scheme`. [Theming](https://visualci.com/docs/gallery/options.md#theming) lists every variable.

## Light and dark

By default the grid has Light and Dark buttons: the gallery starts in your page's theme and the reader then chooses. If your site has its own theme toggle on `<html data-theme>`, turn the buttons off with `.theme_switch(false)`, as in the options above. The gallery then shows the light or dark screenshots to match the page, and switches when the page does. See [Light and dark](https://visualci.com/docs/gallery/options.md#light-and-dark).

## A band on the homepage

The strip layout shows every screen at one size in a single row that scrolls sideways. Give it a link to the full page with `see_all`:

<!-- example: clients/gallery/rust/examples/axum_app.rs#strip -->

```rust
pub fn band_options() -> Options {
    Options::default().title(None).layout("strip").credit(false).see_all("/screenshots/", None)
}
```

`see_all`'s second argument is the link's text, "See all screenshots" when it's `None`. The strip never has theme buttons, so it follows the page's theme. Render it from the same manifest and write it into your homepage's template, here `templates/home.html`:

<!-- example: clients/gallery/rust/templates/home.html -->

```html
<!doctype html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Home</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/visualci-gallery@0.7.0/dist/gallery.css">
</head>
<body>
<main>
<h1>Acme</h1>
<p>Everything your team needs, in one place.</p>
{{ band }}
</main>
<script src="https://cdn.jsdelivr.net/npm/visualci-gallery@0.7.0/dist/gallery.iife.js"></script>
<script>document.querySelectorAll("[data-vg]").forEach(function (el) { VisualCIGallery.hydrate(el); });</script>
</body>
</html>
```

To show the band and the full gallery on the same page, give one of them its own `id` (`.id("band")`), so their ids don't clash.

## When the manifest can't be read

`fetch` returns `Error::Fetch` when VisualCI can't be read (a network error, a timeout, a status other than 200, JSON that doesn't parse), naming the URL. Rendering returns `Error::Invalid` when the manifest has nothing to show. The crate never renders an empty gallery in place of one of these errors. Read the manifest where an error stops a release: in the build of a static site, or at boot before a server takes traffic, as in the examples above. A failed build or deploy leaves the last good version live.

## Versions

The script hydrates the HTML the crate renders, so use the same version of both: the crate at `=0.7.0` and the stylesheet and script at `visualci-gallery@0.7.0`. Upgrade them in the same change. To serve the files yourself instead of from jsDelivr, copy them from the npm package:

```sh
npm pack visualci-gallery@0.7.0
tar -xzf visualci-gallery-0.7.0.tgz package/dist/gallery.css package/dist/gallery.iife.js
```
