Gallery in Ruby

The visualci-gallery gem renders a public gallery on your server, in Ruby. Its HTML is byte for byte what the JS library renders, and the gem carries the library's script and stylesheet, so the page works before any script runs and the script then adds the tabs, the switches and the full-size view.

In Rails it adds a visualci_gallery view helper and serves the script and stylesheet through Propshaft or Sprockets. Outside Rails, VisualCI::Gallery.render returns the HTML as a string. It needs Ruby 3.1 or later.

Every example on this page comes from the example apps in clients/gallery/ruby/examples, which the gem's CI boots and requests.

Install

Add it to your Gemfile:

gem 'visualci-gallery', '~> 0.8.1'

~> 0.8.1 takes 0.8.x fixes and nothing newer, and Gemfile.lock holds the exact version you deployed. The script and stylesheet are inside the gem, so they're pinned with it: the HTML the gem renders and the script that hydrates it always come from the same release. Upgrade with bundle update visualci-gallery.

Rails

Fetch the manifest when you deploy

Read the manifest once, when you deploy, save it to a file, and serve every request from that file. We recommend this setup. A request never waits on VisualCI, and it can't fail because VisualCI is slow or down.

A rake task writes the file, and runs before assets:precompile, so every deploy that builds assets fetches the screenshots first:

# frozen_string_literal: true

namespace :screenshots do
  desc "Writes config/screenshots.json from VisualCI's gallery manifest, failing when it can't be read"
  task fetch: :environment do
    manifest = VisualCI::Gallery.fetch(Screenshots::URL) # raises VisualCI::Gallery::Error
    VisualCI::Gallery.render(manifest) # raises when it has nothing to show
    File.write(Screenshots::PATH, JSON.pretty_generate(manifest))
    puts "Wrote #{Screenshots::PATH}"
  end
end

# Every deploy that compiles assets fetches the screenshots first.
Rake::Task['assets:precompile'].enhance(['screenshots:fetch'])

fetch tries 3 times, 20 seconds each, then raises, so the build fails and the version you're running keeps serving. Rails' Dockerfile already runs bin/rails assets:precompile, so it needs no new step. The app reads the file:

# frozen_string_literal: true

# The project's gallery manifest, read from the file `bin/rails screenshots:fetch` writes when the app is deployed.
module Screenshots
  URL = ENV.fetch('SCREENSHOTS_URL', 'https://app.visualci.com/g/acme/web/gallery.json')
  PATH = Rails.root.join('config/screenshots.json')

  def self.manifest
    @manifest ||= JSON.parse(File.read(PATH))
  end
end

Put your project's manifest URL in place of acme/web. Add config/screenshots.json to .gitignore, and fetch it once in development. Your test suite needs the file too: run the task in CI before the tests, or copy a manifest you keep for tests into place.

bin/rails screenshots:fetch

The page

The controller passes the manifest to the view:

# frozen_string_literal: true

class ScreenshotsController < ApplicationController
  def index
    @manifest = Screenshots.manifest
  end
end

The view renders it with the helper, which returns the HTML marked safe (the gem escapes everything it puts in it):

<main>
  <h1>Screenshots</h1>
  <%= visualci_gallery(@manifest,
                       title: nil,
                       order: %w[overview access ios/sessions],
                       group_order: ['Web', 'iPhone'],
                       screens: {
                         'overview' => { title: 'Overview', caption: 'Everything that needs you, on one page.' },
                         'ios/sessions' => { title: 'Sessions' }
                       },
                       groups: { 'Mac approver' => { size: 'desktop', fit: 'contain' } }) %>
</main>

title: nil leaves out the gallery's own heading, since the page has one. Options lists the rest.

The layout

The layout links the gem's stylesheet and your own, and hydrates every gallery on the page after its markup:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Acme</title>
  <%= csp_meta_tag %>
  <%= stylesheet_link_tag 'visualci_gallery', 'application' %>
</head>
<body>
  <%= yield %>
  <%= javascript_include_tag 'visualci_gallery' %>
  <script nonce="<%= content_security_policy_nonce %>">
    document.querySelectorAll('[data-vg]').forEach(function (el) { VisualCIGallery.hydrate(el); });
  </script>
</body>
</html>

visualci_gallery.js is the library's ES5 build, a classic script that sets window.VisualCIGallery. Include it with javascript_include_tag even when the rest of your JavaScript is bundled.

The gem's engine puts both files on the asset path. With Propshaft there's nothing else to do. With Sprockets the engine also adds them to the precompile list, so the same tags work in production. With Sprockets you can also bundle them into your own files instead: add //= require visualci_gallery to application.js and *= require visualci_gallery to application.css. Propshaft has no require directives, so there you link the files with the tags above.

Content Security Policy

The screenshots load from app.visualci.com, and the inline script needs a nonce. In config/initializers/content_security_policy.rb:

Rails.application.configure do
  config.content_security_policy do |policy|
    policy.default_src :self
    policy.img_src :self, 'https://app.visualci.com' # the screenshots
    policy.script_src :self
    policy.style_src :self
  end
  config.content_security_policy_nonce_generator = ->(_request) { SecureRandom.base64(16) }
  config.content_security_policy_nonce_directives = %w[script-src]
end

The gallery needs no inline styles, so style-src can stay strict.

Caching the manifest instead

If you want approved screenshots to show up between deploys, read the manifest at request time through Rails.cache, and fall back to the deployed file when VisualCI can't be read:

# frozen_string_literal: true

# The manifest as VisualCI serves it now, cached for ten minutes, or the deployed file when VisualCI can't be read.
module LiveScreenshots
  def self.manifest
    Rails.cache.fetch('visualci/screenshots', expires_in: 10.minutes) do
      manifest = VisualCI::Gallery.fetch(Screenshots::URL, timeout: 2, attempts: 1)
      VisualCI::Gallery.model(manifest) # raises when it has nothing to show
      manifest
    rescue VisualCI::Gallery::Error => e
      Rails.logger.warn(e.message)
      Screenshots.manifest
    end
  end
end

Use LiveScreenshots.manifest in the controller. The fallback is cached too, so while VisualCI is down only one request every ten minutes waits for it, for up to the 2-second timeout. You still need the deploy-time file: it's what the page shows when the fetch fails. The deploy-time file alone is simpler, and it's what we recommend.

Rack and ERB

Without Rails, render the HTML yourself and serve the script and stylesheet from the gem's VisualCI::Gallery::ASSETS folder. The example's Gemfile has Rack, a server and the gem:

gem 'rack', '~> 3.1'
gem 'rackup', '~> 2.2'
gem 'webrick', '~> 1.9'
gem 'visualci-gallery', '~> 0.8.1'

A config.ru:

# frozen_string_literal: true

require 'erb'
require 'json'
require 'rack'
require 'securerandom'
require 'visualci/gallery'

# The gallery's HTML, rendered once at boot from the file fetch_screenshots.rb wrote.
manifest = JSON.parse(File.read(File.join(__dir__, 'screenshots.json')))
gallery = VisualCI::Gallery.render(manifest, title: 'Screenshots', heading_level: 1,
                                             screens: { 'overview' => { title: 'Overview' } })
page = ERB.new(File.read(File.join(__dir__, 'screenshots.html.erb')))

# visualci_gallery.js and visualci_gallery.css from the gem, at /assets/javascripts/… and /assets/stylesheets/….
# They change only with the gem's version, which the page puts in their URLs.
map '/assets' do
  run Rack::Files.new(VisualCI::Gallery::ASSETS, 'cache-control' => 'public, max-age=31536000, immutable')
end

run lambda { |env|
  next [404, { 'content-type' => 'text/plain' }, ['Not found']] unless env['PATH_INFO'] == '/'

  nonce = SecureRandom.base64(16)
  html = page.result_with_hash(gallery: gallery, nonce: nonce, version: VisualCI::Gallery::VERSION)
  [200, { 'content-type' => 'text/html; charset=utf-8',
          'content-security-policy' => "default-src 'self'; img-src 'self' https://app.visualci.com; " \
                                       "script-src 'self' 'nonce-#{nonce}'" }, [html]]
}

The page, screenshots.html.erb:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Screenshots</title>
  <link rel="stylesheet" href="/assets/stylesheets/visualci_gallery.css?v=<%= version %>">
</head>
<body>
<%= gallery %>
<script src="/assets/javascripts/visualci_gallery.js?v=<%= version %>"></script>
<script nonce="<%= nonce %>">
  document.querySelectorAll('[data-vg]').forEach(function (el) { VisualCIGallery.hydrate(el); });
</script>
</body>
</html>

Plain ERB doesn't escape, so <%= gallery %> puts the HTML in as it is. A template engine that escapes by default (Erubi with escape: true, Sinatra's escape_html) needs it marked as safe, as Rails' helper does.

A script writes screenshots.json when you deploy, and fails the deploy when it can't:

# frozen_string_literal: true

# Writes screenshots.json from VisualCI's gallery manifest. Run it when the site is deployed: it fails, and fails the
# deploy, when the manifest can't be read or has nothing to show.
require 'json'
require 'visualci/gallery'

url = ENV.fetch('SCREENSHOTS_URL', 'https://app.visualci.com/g/acme/web/gallery.json')
manifest = VisualCI::Gallery.fetch(url) # raises VisualCI::Gallery::Error
VisualCI::Gallery.render(manifest) # raises when it has nothing to show
File.write(File.join(__dir__, 'screenshots.json'), JSON.pretty_generate(manifest))
bundle exec ruby fetch_screenshots.rb   # in your Dockerfile or deploy script
bundle exec rackup

Options

The helper and render take the gallery options as keyword arguments, in snake case: title, heading_level, id, screens, order, groups, group_order, credit, layout, theme_switch, see_all, preload, deep_links, text, search, zoom and new_badges. Hash keys inside them can be strings or symbols, and groups' size and fit take either too (fit: :contain). The screenshots view above uses five of them.

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 says what it fetches and when.

deep_links: true keeps the shown tab, the open screen and the chosen values in the page's URL, so a link opens them (Deep links). text: changes the gallery's own words, for another language or tone: text: { label: 'Captures', open: 'Agrandir « {title} »', close: 'Fermer' }. Your own words lists every key. search: false takes away the search box a gallery of 40 screens or more gets, zoom: false turns off zooming in the full-size view, and new_badges: 14 badges the screens that changed in the last 14 days (Search, Zoom, New badges).

An option the gem can't use raises VisualCI::Gallery::Error, naming the option as the options page spells it (gallery option headingLevel is invalid). Give each gallery its own id: when a page has more than one.

Theming

The gem's stylesheet styles the gallery through --vg-* CSS variables. Set them to your site's tokens on .vg or any element around it, in any stylesheet:

/* The gallery in the site's colours, radii and type. */
.vg {
  --vg-ink: var(--ink);
  --vg-ink-2: var(--ink);
  --vg-muted: var(--muted);
  --vg-paper: var(--paper);
  --vg-paper-2: var(--paper-sunken);
  --vg-rule: var(--line);
  --vg-accent: var(--brand);
  --vg-radius-sm: calc(var(--radius) / 2);
  --vg-radius-md: var(--radius);
  --vg-radius-lg: calc(var(--radius) * 1.5);
  --vg-group-title-size: 1.25rem;
  --vg-card-title-size: 1rem;
  font-family: var(--font);
}

When your tokens change with your site's dark mode, the gallery changes with them. Theming lists every variable.

Light and dark

By default the grid has Light and Dark buttons. The gallery starts in the page's theme (<html data-theme="dark"> or "light" when it's set, else the reader's system setting), and the reader then picks which screenshots to see.

If your site has its own theme toggle that sets data-theme on <html>, pass theme_switch: false. The buttons go, and the gallery's screenshots follow <html data-theme> as it changes. The strip always works this way.

A strip on the homepage

layout: 'strip' shows every screen in one row that scrolls sideways, at the desktop size when there is one, with no captions and no theme buttons. With see_all, it links to the full page:

<main>
  <h1>Acme</h1>
  <p>Every machine's sessions, in one place.</p>
  <%= visualci_gallery(@manifest, title: 'See it in action', layout: 'strip', credit: false,
                                  see_all: { href: screenshots_path }) %>
</main>

The homepage's controller reads Screenshots.manifest like the screenshots page's, and the layout above hydrates both.

When the manifest can't be read

VisualCI::Gallery.fetch raises VisualCI::Gallery::Error when the manifest can't be read: a network error, a timeout, a status other than 200, or JSON that doesn't parse. It tries 3 times, 20 seconds each, by default (attempts: and timeout: change that). render raises the same error when the manifest has nothing to show, when a screen has a light screenshot but no dark one, or when an option is invalid.

Let the error fail your deploy, as the rake task and the script above do, so the version you're running keeps serving. Rescue it only where you have a manifest to fall back to, as the cached version does.