# Gallery in JavaScript

> Show a VisualCI screenshots gallery on any page with the visualci-gallery library, from a script tag, a bundler, or HTML rendered when the site builds.

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

The `visualci-gallery` library turns a [public gallery](https://visualci.com/docs/gallery.md)'s manifest into a screenshots page: a tab for each group, light and dark, desktop and phone, and a full-size view. It has no dependencies and works with any framework, or none. On an Astro site, use [the Astro component](https://visualci.com/docs/gallery/astro.md) instead.

There are three ways to use it:

- A script tag and `mount()`, with no build step. The browser reads the manifest when the page opens.
- A bundler: install it from npm, import it and call `mount()`.
- Rendered when the site builds, with `visualci-gallery/render`, then `hydrate()` in the browser. The screenshots are in the page's HTML, and the build fails when the manifest can't be read.

Each needs your project's manifest URL, `https://app.visualci.com/g/<org>/<project>.json`, which works once the project's gallery is on. The examples use `acme/web`. Every snippet below is a file, or part of one, from the [examples](https://github.com/DocSpring/visualci/tree/main/clients/gallery/js/examples), which run in VisualCI's tests.

## A script tag

Load the stylesheet and the script from jsDelivr, with the version in the URL, and call `VisualCIGallery.mount()` on an empty element:

<!-- example: clients/gallery/js/examples/cdn/index.html -->
```html
<!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>
  <div id="screenshots"></div>
  <script src="https://cdn.jsdelivr.net/npm/visualci-gallery@0.7.0/dist/gallery.iife.js"></script>
  <script>
    VisualCIGallery.mount(document.getElementById("screenshots"), {
      manifest: "https://app.visualci.com/g/acme/web.json",
      screens: {
        overview: { title: "Overview", caption: "Everything at a glance." }
      },
      order: ["overview"]
    });
  </script>
</body>
</html>
```

`gallery.iife.js` is one ES5 file that sets `window.VisualCIGallery`, with the same functions as the npm package: `mount`, `hydrate`, `load` and `render`. To serve the files yourself, copy `dist/gallery.css` and `dist/gallery.iife.js` from the npm package into your site.

## With a bundler

The examples use [Vite](https://vite.dev), which serves an `index.html` and the TypeScript it loads with no config. Any bundler that handles CSS imports works the same way. Install the package:

```sh
npm install visualci-gallery@0.7.0
```

Give the page an empty element, and load the script that mounts the gallery:

<!-- example: clients/gallery/js/examples/bundler/index.html -->
```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Screenshots</title>
  <script type="module" src="./main.ts"></script>
</head>
<body>
  <div id="screenshots"></div>
</body>
</html>
```

Then import the library and its stylesheet, and mount the gallery, in `main.ts`:

<!-- example: clients/gallery/js/examples/bundler/main.ts -->
```ts
import { mount } from "visualci-gallery";
import "visualci-gallery/gallery.css";

mount(document.getElementById("screenshots")!, {
  manifest: "https://app.visualci.com/g/acme/web.json",
  screens: {
    overview: { title: "Overview", caption: "Everything at a glance." },
  },
  order: ["overview"],
});
```

Run `npx vite` in the page's folder to open it, and `npx vite build` to build it into `dist/`.

`mount()` reads the manifest, renders the gallery into the element and hydrates it. It returns a promise of the gallery, which has `setTheme()`, `setSize()`, `open()`, `close()` and `destroy()`. Mounting again on the same element replaces the gallery.

## Rendered when the site builds

`visualci-gallery/render` has the half of the library that needs no browser: `load()` reads the manifest and `render()` returns the gallery's HTML. Run it when your site builds, and the screenshots are in the page before any script runs. This build step puts the gallery where the page has a `<!-- gallery -->` comment, then bundles the page's script with [esbuild](https://esbuild.github.io):

```sh
npm install visualci-gallery@0.7.0
npm install --save-dev esbuild
```

<!-- example: clients/gallery/js/examples/prerender/build.mjs -->
```js
// Run when the site builds: node build.mjs
// load() throws when the manifest can't be read, so the build fails rather than shipping an empty page.
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { build } from "esbuild";
import { load, render } from "visualci-gallery/render";

const model = await load({
  manifest: "https://app.visualci.com/g/acme/web.json",
  screens: {
    overview: { title: "Overview", caption: "Everything at a glance." },
  },
  order: ["overview"],
});

const page = readFileSync("src/screenshots.html", "utf8").replace("<!-- gallery -->", render(model));
mkdirSync("dist", { recursive: true });
writeFileSync("dist/screenshots.html", page);

// client.ts and the stylesheet it imports, bundled as dist/assets/client.js and dist/assets/client.css.
await build({ entryPoints: ["client.ts"], bundle: true, format: "esm", outdir: "dist/assets" });
```

The page, `src/screenshots.html`, loads the two files esbuild makes from `client.ts`, which `dist/` serves at `/assets/`:

<!-- example: clients/gallery/js/examples/prerender/src/screenshots.html -->
```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Screenshots</title>
  <link rel="stylesheet" href="/assets/client.css">
  <script type="module" src="/assets/client.js"></script>
</head>
<body>
  <main id="screenshots"><!-- gallery --></main>
</body>
</html>
```

`client.ts` imports the library's stylesheet, which esbuild writes as `client.css`, and hydrates the gallery:

<!-- example: clients/gallery/js/examples/prerender/client.ts -->
```ts
import { hydrate } from "visualci-gallery";
import "visualci-gallery/gallery.css";

hydrate(document.getElementById("screenshots")!);
```

Run `node build.mjs` when your site builds, and serve `dist/`. `hydrate()` adds the tabs, the switches and the full-size view to HTML that's already there. To skip the bundle, link the two files from jsDelivr as in [A script tag](#a-script-tag) and call `VisualCIGallery.hydrate(document.getElementById("screenshots"))`. It works from the markup alone, so it also brings HTML from the Ruby, Python and Rust libraries to life.

The image URLs always serve the approved version, so a changed screenshot shows on your site without a rebuild. A new screenshot, or one whose size changed, shows after the next build.

## Options

`mount()` and `load()` take the gallery's options next to `manifest`. In this example, the gallery gets a heading, and two screens get a title and a caption. `order` puts two screens first. The Mac approver group gets a new title and shows its windows whole, and the iPhone tab comes first:

<!-- example: clients/gallery/js/examples/bundler/options.ts -->
```ts
import { mount } from "visualci-gallery";
import "visualci-gallery/gallery.css";

mount(document.getElementById("screenshots")!, {
  manifest: "https://app.visualci.com/g/acme/web.json",
  title: "See it in action",
  headingLevel: 2,
  screens: {
    overview: { title: "Overview", caption: "What needs you, at a glance." },
    "ios/sessions": { title: "Sessions", caption: "Every session on every machine." },
  },
  order: ["overview", "access"],
  groups: {
    "Mac approver": { title: "On the Mac", fit: "contain" },
  },
  groupOrder: ["iPhone", "Web"],
});
```

A screen's key is its screenshots' name without the theme and width: `overview-light-1440` and `overview-dark-390` are the screen `overview`. Groups go by the names in `visualci.yml`'s `gallery` section. `title: null` leaves the heading out, for a page that has its own. Give each gallery on a page its own `id`.

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: { count: 200, bytes: 20_000_000 }` sets your own limits. It's on by default, and [Preloading](https://visualci.com/docs/gallery/options.md#preloading) says what it fetches and when. A page that renders its own markup and calls `hydrate(el)` sets it with `hydrate(el, { preload: false })`.

`mount()` and `load()` also take `timeout` (milliseconds for each try, default 20000), `attempts` (default 3) and `fetch` (one to use in place of the global `fetch`). [Gallery options](https://visualci.com/docs/gallery/options.md) describes every option, and how screenshot names pair into screens.

## Theming

`gallery.css` follows the page's text colour and `color-scheme` out of the box. To give the gallery your site's look, set the `--vg-*` variables to your own tokens. When the tokens change with your site's theme, the gallery's colours change with them:

<!-- example: clients/gallery/js/examples/theme/site.css -->
```css
/* The site's own tokens, light and dark. */
:root {
  --color-text: #1c2024;
  --color-text-muted: #60646c;
  --color-bg: #ffffff;
  --color-surface: #f4f5f7;
  --color-border: #dfe1e6;
  --color-brand: #3e63dd;
  --radius: 10px;
}
[data-theme="dark"] {
  --color-text: #edeef0;
  --color-text-muted: #9ba1a6;
  --color-bg: #111113;
  --color-surface: #1b1b1f;
  --color-border: #2e3035;
  --color-brand: #8da4ef;
}

/* The gallery in the site's colours. Set on .vg or any element around it, these win in any stylesheet order. */
.vg {
  --vg-ink: var(--color-text);
  --vg-ink-2: var(--color-text);
  --vg-muted: var(--color-text-muted);
  --vg-paper: var(--color-bg);
  --vg-paper-2: var(--color-surface);
  --vg-rule: var(--color-border);
  --vg-accent: var(--color-brand);
  --vg-radius-md: var(--radius);
  --vg-radius-lg: calc(var(--radius) * 1.5);
  --vg-title-size: 2.25rem;
}
```

Set the variables on `.vg` or on any element around the gallery, such as `:root` or your content's wrapper. `gallery.css` declares its defaults on the root with no specificity, so your values win whichever stylesheet loads first. [Gallery options](https://visualci.com/docs/gallery/options.md#theming) lists every variable.

## Light and dark

By default each group has Light and Dark buttons. The gallery starts in the page's theme (`<html data-theme="light">` or `"dark"` when it's set, otherwise the reader's system setting), and the buttons switch the screenshots. They don't change your page.

If your site has its own theme toggle on `<html data-theme>`, turn the buttons off with `themeSwitch: false`. The gallery then follows `data-theme` as it changes, and the reader's system setting when it isn't set. This page has the site's toggle:

<!-- example: clients/gallery/js/examples/bundler/follow-page.html -->
```html
<!doctype html>
<html lang="en" data-theme="light">
<head>
  <meta charset="utf-8">
  <title>Screenshots</title>
  <script type="module" src="./follow-page.ts"></script>
</head>
<body>
  <button id="theme-toggle" type="button">Light or dark</button>
  <div id="screenshots"></div>
</body>
</html>
```

Its script, `follow-page.ts`, mounts the gallery without the buttons and wires up the toggle:

<!-- example: clients/gallery/js/examples/bundler/follow-page.ts -->
```ts
import { mount } from "visualci-gallery";
import "visualci-gallery/gallery.css";

mount(document.getElementById("screenshots")!, {
  manifest: "https://app.visualci.com/g/acme/web.json",
  themeSwitch: false,
});

// The site's own toggle sets <html data-theme>, and the gallery follows it.
document.getElementById("theme-toggle")!.addEventListener("click", () => {
  const html = document.documentElement;
  html.dataset.theme = html.dataset.theme === "dark" ? "light" : "dark";
});
```

A site that marks its theme some other way (a `dark` class) can call `setTheme("dark")` on the gallery that `mount()` returns.

## When the manifest can't be read

`load()` tries three times, 20 seconds each, then throws an error that names the URL. It also throws when the manifest has nothing to show or an option is invalid. Rendered when the site builds, that error stops the build: `build.mjs` above exits 1 and writes nothing, and the site you have keeps serving its last copy.

`mount()` runs in the reader's browser, so nothing can stop a build. When the manifest can't be read, the element says "The screenshots couldn't be loaded." and the promise rejects with the same error. Add a `.catch()` if you want to report it.

## Pinning the version

Install an exact version, so an update to the library is a change you make:

```sh
npm install --save-exact visualci-gallery@0.7.0
```

From jsDelivr, keep the full version in both URLs, as above: `https://cdn.jsdelivr.net/npm/visualci-gallery@0.7.0/dist/gallery.css` and `https://cdn.jsdelivr.net/npm/visualci-gallery@0.7.0/dist/gallery.iife.js`. A URL without a version, or with `@latest` or `@0`, changes under you. The stylesheet and the script go together, so update both URLs at once.

## A band on the homepage

The strip layout shows every screen at one size in a single row that scrolls sideways, with no tabs and no captions. With `seeAll` it links to the full page:

<!-- example: clients/gallery/js/examples/bundler/strip.ts -->
```ts
import { mount } from "visualci-gallery";
import "visualci-gallery/gallery.css";

mount(document.getElementById("home-screenshots")!, {
  manifest: "https://app.visualci.com/g/acme/web.json",
  layout: "strip",
  title: null,
  credit: false,
  order: ["overview", "access"],
  seeAll: { href: "/screenshots/" },
});
```

A strip has no Light and Dark buttons: it follows the page, as with `themeSwitch: false`. `seeAll`'s text is "See all screenshots" unless you give it a `text`.
