diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7ef50bbd..9907a850 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -426,6 +426,9 @@ jobs: ruby-version: "3.4" - run: ruby -Ilib spec/visualci_spec.rb working-directory: clients/ruby + # The gallery's Ruby renderer: the contract's golden fixtures. + - run: ruby -Ilib test/gallery_test.rb + working-directory: clients/gallery/ruby - uses: pnpm/action-setup@v4 with: package_json_file: frontend/package.json @@ -437,6 +440,9 @@ jobs: # real astro build). - run: pnpm install --frozen-lockfile && pnpm --filter visualci-gallery typecheck && pnpm build && pnpm test working-directory: clients/gallery + # The gem carries the library's built script and stylesheet, and the licence: it builds with them. + - run: bin/assets && gem build visualci-gallery.gemspec && tar -xOf visualci-gallery-*.gem data.tar.gz | tar -tz > /tmp/gem-files && grep -x app/assets/javascripts/visualci_gallery.js /tmp/gem-files && grep -x LICENSE /tmp/gem-files + working-directory: clients/gallery/ruby # The Compare two PDFs page runs crates/visualci-wasm in the browser (scripts/wasm.mjs builds it). - run: rustup target add wasm32-unknown-unknown # Compile cache (kache, as Cargo's rustc wrapper): the R2 bucket every machine shares (KACHE_BUCKET), else the diff --git a/.github/workflows/release-gallery-gem.yml b/.github/workflows/release-gallery-gem.yml new file mode 100644 index 00000000..c02de689 --- /dev/null +++ b/.github/workflows/release-gallery-gem.yml @@ -0,0 +1,45 @@ +# Publish the visualci-gallery gem (clients/gallery/ruby) to RubyGems with trusted publishing: RubyGems trusts this +# workflow through GitHub's OIDC token, so no API key is stored anywhere. Runs for a gallery-ruby-v* tag (matching +# VisualCI::Gallery::VERSION) or by hand. The gem carries the JS library's ES5 build and stylesheet (bin/assets). +name: Release gallery gem + +on: + push: + tags: ["gallery-ruby-v*"] + workflow_dispatch: + +permissions: + contents: read + id-token: write + +jobs: + publish: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + with: + package_json_file: clients/gallery/package.json + - uses: actions/setup-node@v4 + with: + node-version: "24" + - run: pnpm install --frozen-lockfile && pnpm --filter visualci-gallery build + working-directory: clients/gallery + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + - name: The tag matches the gem's version + if: startsWith(github.ref, 'refs/tags/gallery-ruby-v') + working-directory: clients/gallery/ruby + run: | + version=$(ruby -r ./lib/visualci/gallery/version -e 'print VisualCI::Gallery::VERSION') + test "gallery-ruby-v$version" = "$GITHUB_REF_NAME" || { echo "tag $GITHUB_REF_NAME, gem $version"; exit 1; } + - run: ruby -Ilib test/gallery_test.rb + working-directory: clients/gallery/ruby + - uses: rubygems/configure-rubygems-credentials@v2.2.0 + with: + # The RubyGems.org account that owns the gem (needed for the first push through a pending trusted publisher). + owner: "48431" + - run: bin/assets && gem build visualci-gallery.gemspec && gem push visualci-gallery-*.gem + working-directory: clients/gallery/ruby diff --git a/clients/gallery/README.md b/clients/gallery/README.md index 89689e02..152629f7 100644 --- a/clients/gallery/README.md +++ b/clients/gallery/README.md @@ -8,6 +8,8 @@ variables. fixtures every renderer's tests check. - [`js/`](js/README.md): `visualci-gallery`, the browser library and reference renderer. - [`astro/`](astro/README.md): `visualci-astro-gallery`, rendered when the site builds and hydrated by the library. +- [`ruby/`](ruby/README.md): the `visualci-gallery` gem, with a Rails helper and the library's files for the asset + pipeline. -A pnpm workspace: `pnpm install && pnpm build && pnpm test` here. Coming: the Ruby gem, the Python package and the Rust -crate, each emitting the contract's markup for the JS library to hydrate. +A pnpm workspace: `pnpm install && pnpm build && pnpm test` here. Coming: the Python package and the Rust crate, each +emitting the contract's markup for the JS library to hydrate. diff --git a/clients/gallery/contract/SPEC.md b/clients/gallery/contract/SPEC.md index a41b40b4..a6c83bff 100644 --- a/clients/gallery/contract/SPEC.md +++ b/clients/gallery/contract/SPEC.md @@ -43,7 +43,8 @@ word for word, in every language. An invalid option's message names it in the co - The manifest is an object with a `groups` array. Each group is an object with a non-empty string `name`, a `title` that's absent, null or a string, and an `items` array (possibly empty). Each item is an object with a non-empty - string `name`, a `url`, and a `width` and `height` that are positive integers (JSON numbers with no fraction). + string `name`, a `url`, and a `width` and `height` that are whole numbers from 1 to 1000000 (JSON numbers with no + fraction; the limit keeps the density maths below exact in every language's numbers). - An item's `url` must be an absolute http or https URL: it starts with `http://` or `https://` (scheme in any case) and has no character from U+0000 to U+0020 or U+007F anywhere (browsers drop those, so `java\tscript:` would still run). @@ -54,6 +55,8 @@ word for word, in every language. An invalid option's message names it in the co `themeSwitch` booleans; `layout` `"grid"` or `"strip"`; `seeAll` an object with a string `href` and a `text` that's absent, null or a string. `seeAll.href` is an absolute URL as above, or a relative one: not empty, no character from U+0000 to U+0020 or U+007F, and not starting with a scheme (`^[A-Za-z][A-Za-z0-9+.-]*:`). +- The manifest is checked first, then the options in this order, and the first problem is the error: `headingLevel`, + `title`, `id`, `screens`, `groups`, `order`, `groupOrder`, `credit`, `themeSwitch`, `layout`, `seeAll`. - Other fields, in the manifest or the options, are ignored. ## Reading the manifest @@ -93,8 +96,9 @@ ASCII digits only, and `.` means any character at all, line breaks included: 3. Otherwise the key is the whole name without its extension, with no theme (it stands for both), no CSS width, not 2x. -Size: with a CSS width, under 768 is `phone`, else `desktop`. Without one, the group's `size` option when set, else -an image taller than it is wide (`height > width`) is `phone`, else `desktop`. +Size: with a CSS width (the number's value: leading zeros don't count, so `0390` is 390), under 768 is `phone`, else +`desktop`. Without one, the group's `size` option when set, else an image taller than it is wide (`height > width`) +is `phone`, else `desktop`. ### Pairing diff --git a/clients/gallery/contract/errors/fractional-size.message b/clients/gallery/contract/errors/fractional-size.message index fc59956d..6e9c4a45 100644 --- a/clients/gallery/contract/errors/fractional-size.message +++ b/clients/gallery/contract/errors/fractional-size.message @@ -1 +1 @@ -gallery manifest group Web, item 0 (a-light-1440): its width and height aren't positive integers +gallery manifest group Web, item 0 (a-light-1440): its width and height aren't whole numbers from 1 to 1000000 diff --git a/clients/gallery/contract/errors/no-size.message b/clients/gallery/contract/errors/no-size.message index fc59956d..6e9c4a45 100644 --- a/clients/gallery/contract/errors/no-size.message +++ b/clients/gallery/contract/errors/no-size.message @@ -1 +1 @@ -gallery manifest group Web, item 0 (a-light-1440): its width and height aren't positive integers +gallery manifest group Web, item 0 (a-light-1440): its width and height aren't whole numbers from 1 to 1000000 diff --git a/clients/gallery/contract/errors/too-wide.json b/clients/gallery/contract/errors/too-wide.json new file mode 100644 index 00000000..f39e0912 --- /dev/null +++ b/clients/gallery/contract/errors/too-wide.json @@ -0,0 +1 @@ +{"groups": [{"name": "Web", "items": [{"name": "a-light-1440", "url": "https://app.visualci.com/g/acme/web/a.png", "width": 1000001, "height": 900}]}]} diff --git a/clients/gallery/contract/errors/too-wide.message b/clients/gallery/contract/errors/too-wide.message new file mode 100644 index 00000000..6e9c4a45 --- /dev/null +++ b/clients/gallery/contract/errors/too-wide.message @@ -0,0 +1 @@ +gallery manifest group Web, item 0 (a-light-1440): its width and height aren't whole numbers from 1 to 1000000 diff --git a/clients/gallery/contract/fixtures/widths/gallery.html b/clients/gallery/contract/fixtures/widths/gallery.html new file mode 100644 index 00000000..5e8fe8d4 --- /dev/null +++ b/clients/gallery/contract/fixtures/widths/gallery.html @@ -0,0 +1,13 @@ +
+
+

Web

+ +
+

Screenshot Gallery Powered by VisualCI.com

+ +

+
+
+
diff --git a/clients/gallery/contract/fixtures/widths/manifest.json b/clients/gallery/contract/fixtures/widths/manifest.json new file mode 100644 index 00000000..281489f1 --- /dev/null +++ b/clients/gallery/contract/fixtures/widths/manifest.json @@ -0,0 +1,46 @@ +{ + "project": "acme/web", + "groups": [ + { + "name": "Web", + "items": [ + { + "name": "home-light-1440", + "platform": "", + "url": "https://app.visualci.com/g/acme/web/home-light-1440.png", + "width": 2880, + "height": 1800, + "sha256": "s-home-light-1440", + "since": "2026-12-01T09:00:00+00:00" + }, + { + "name": "home-dark-1440", + "platform": "", + "url": "https://app.visualci.com/g/acme/web/home-dark-1440.png", + "width": 2880, + "height": 1800, + "sha256": "s-home-dark-1440", + "since": "2026-12-01T09:00:00+00:00" + }, + { + "name": "home-light-0000000000000000000390", + "platform": "", + "url": "https://app.visualci.com/g/acme/web/home-light-0000000000000000000390.png", + "width": 780, + "height": 1688, + "sha256": "s-home-light-0000000000000000000390", + "since": "2026-12-01T09:00:00+00:00" + }, + { + "name": "home-dark-0000000000000000000390", + "platform": "", + "url": "https://app.visualci.com/g/acme/web/home-dark-0000000000000000000390.png", + "width": 780, + "height": 1688, + "sha256": "s-home-dark-0000000000000000000390", + "since": "2026-12-01T09:00:00+00:00" + } + ] + } + ] +} \ No newline at end of file diff --git a/clients/gallery/contract/fixtures/widths/model.json b/clients/gallery/contract/fixtures/widths/model.json new file mode 100644 index 00000000..14eab5b2 --- /dev/null +++ b/clients/gallery/contract/fixtures/widths/model.json @@ -0,0 +1,63 @@ +{ + "layout": "grid", + "themeSwitch": true, + "seeAll": null, + "title": null, + "label": "Screenshots", + "headingLevel": 2, + "id": "vg", + "credit": true, + "groups": [ + { + "name": "Web", + "title": "Web", + "slug": "web", + "fit": "cover", + "sizes": [ + "desktop", + "phone" + ], + "screens": [ + { + "key": "home", + "title": "Home", + "caption": null, + "variants": [ + { + "size": "desktop", + "theme": "light", + "url": "https://app.visualci.com/g/acme/web/home-light-1440.png", + "url2x": null, + "width": 1440, + "height": 900 + }, + { + "size": "desktop", + "theme": "dark", + "url": "https://app.visualci.com/g/acme/web/home-dark-1440.png", + "url2x": null, + "width": 1440, + "height": 900 + }, + { + "size": "phone", + "theme": "light", + "url": "https://app.visualci.com/g/acme/web/home-light-0000000000000000000390.png", + "url2x": null, + "width": 390, + "height": 844 + }, + { + "size": "phone", + "theme": "dark", + "url": "https://app.visualci.com/g/acme/web/home-dark-0000000000000000000390.png", + "url2x": null, + "width": 390, + "height": 844 + } + ] + } + ] + } + ] +} diff --git a/clients/gallery/contract/fixtures/widths/options.json b/clients/gallery/contract/fixtures/widths/options.json new file mode 100644 index 00000000..88f876d0 --- /dev/null +++ b/clients/gallery/contract/fixtures/widths/options.json @@ -0,0 +1 @@ +{"title": null} diff --git a/clients/gallery/contract/option-errors/several-in-order.json b/clients/gallery/contract/option-errors/several-in-order.json new file mode 100644 index 00000000..43596951 --- /dev/null +++ b/clients/gallery/contract/option-errors/several-in-order.json @@ -0,0 +1 @@ +{"seeAll": 5, "layout": "y", "themeSwitch": "x", "credit": "x", "groupOrder": 5, "order": 5, "id": "1", "screens": 5} diff --git a/clients/gallery/contract/option-errors/several-in-order.message b/clients/gallery/contract/option-errors/several-in-order.message new file mode 100644 index 00000000..c86881f1 --- /dev/null +++ b/clients/gallery/contract/option-errors/several-in-order.message @@ -0,0 +1 @@ +gallery option id is invalid diff --git a/clients/gallery/js/src/model.ts b/clients/gallery/js/src/model.ts index 0c3a1bac..af24fdcb 100644 --- a/clients/gallery/js/src/model.ts +++ b/clients/gallery/js/src/model.ts @@ -206,7 +206,9 @@ function fail(message: string): never { throw new Error(message); } const isObject = (v: unknown): v is Record => typeof v === "object" && v !== null && !Array.isArray(v); -const isSize = (v: unknown) => typeof v === "number" && Number.isInteger(v) && v > 0; +/** A width or height: a whole number from 1 to MAX_SIZE, so the density maths stays exact in every language. */ +export const MAX_SIZE = 1_000_000; +const isSize = (v: unknown) => typeof v === "number" && Number.isInteger(v) && v > 0 && v <= MAX_SIZE; /** An option's value, with null meaning absent. */ function opt(value: T | null | undefined, check: (v: T) => boolean, what: string): T | undefined { if (value === null || value === undefined) return undefined; @@ -232,7 +234,7 @@ function checkManifest(manifest: unknown): asserts manifest is Manifest { const where = `gallery manifest group ${g.name}, item ${j}`; if (!isObject(item) || typeof item.name !== "string" || item.name === "") fail(`${where} has no name`); if (typeof item.url !== "string" || !ABSOLUTE.test(item.url)) fail(`${where} (${item.name}): its url isn't an http(s) URL`); - if (!isSize(item.width) || !isSize(item.height)) fail(`${where} (${item.name}): its width and height aren't positive integers`); + if (!isSize(item.width) || !isSize(item.height)) fail(`${where} (${item.name}): its width and height aren't whole numbers from 1 to 1000000`); }); }); } diff --git a/clients/gallery/ruby/.gitignore b/clients/gallery/ruby/.gitignore new file mode 100644 index 00000000..b7f231cf --- /dev/null +++ b/clients/gallery/ruby/.gitignore @@ -0,0 +1,3 @@ +app/assets/ +*.gem +/LICENSE diff --git a/clients/gallery/ruby/README.md b/clients/gallery/ruby/README.md new file mode 100644 index 00000000..88d267d3 --- /dev/null +++ b/clients/gallery/ruby/README.md @@ -0,0 +1,45 @@ +# visualci-gallery (Ruby) + +A screenshots page from a VisualCI [public gallery](https://visualci.com/docs/gallery/) manifest, rendered in Ruby as +the [gallery contract](../contract/SPEC.md)'s markup: byte for byte what the `visualci-gallery` JS library renders, so +the library's script hydrates it (tabs, light and dark, desktop and phone, the full-size view). + +```ruby +require 'visualci/gallery' + +manifest = VisualCI::Gallery.fetch('https://app.visualci.com/g/acme/web.json') # raises VisualCI::Gallery::Error +html = VisualCI::Gallery.render(manifest, title: nil, layout: 'strip', theme_switch: false, + screens: { 'screenshots/templates' => { title: 'Templates' } }, + see_all: { href: '/screenshots' }) +``` + +`fetch` raises when the manifest can't be read, and `render` raises when it has nothing to show or the options are +invalid. A site that mustn't fail at request time fetches the manifest when it builds (a Docker build step that +writes it to a file, failing the build if it can't) and renders from that file. + +## Rails + +The gem's engine adds a view helper and serves the library's files to the asset pipeline: + +```erb +<%= stylesheet_link_tag 'visualci_gallery' %> +<%= visualci_gallery(JSON.parse(File.read(Rails.root.join('config/screenshots.json'))), title: nil) %> +<%= javascript_include_tag 'visualci_gallery' %> + +``` + +`visualci_gallery.js` is the library's ES5 build (it sets `window.VisualCIGallery`); `visualci_gallery.css` is its +stylesheet, styled through the `--vg-*` CSS variables. + +## Options + +Keyword arguments, the contract's options in Ruby spelling: `title` (default "Screenshots"; `nil` for no heading), +`heading_level`, `id`, `screens`, `order`, `groups` (`{ 'Mac approver' => { size: 'desktop', fit: 'contain' } }` for an app's windows), `group_order`, `credit`, `layout` (`'grid'` or `'strip'`), +`theme_switch`, `see_all`. Hash keys may be strings or symbols. + +## Development + +`ruby -Ilib test/gallery_test.rb` checks the contract's golden fixtures. `bin/assets` copies the JS library's build +into `app/assets` before `gem build`. diff --git a/clients/gallery/ruby/bin/assets b/clients/gallery/ruby/bin/assets new file mode 100755 index 00000000..1ee9dd84 --- /dev/null +++ b/clients/gallery/ruby/bin/assets @@ -0,0 +1,12 @@ +#!/bin/sh +# Copies the JS library's ES5 build and stylesheet into app/assets, where the Rails engine serves them, and the repo's +# LICENSE, which the gem carries. Run before `gem build` (the release workflow does), after `pnpm build` in +# clients/gallery. +set -eu +here=$(cd "$(dirname "$0")/.." && pwd) +dist=$here/../js/dist +[ -f "$dist/gallery.iife.js" ] || { echo "no $dist/gallery.iife.js: run pnpm build in clients/gallery first" >&2; exit 1; } +mkdir -p "$here/app/assets/javascripts" "$here/app/assets/stylesheets" +cp "$dist/gallery.iife.js" "$here/app/assets/javascripts/visualci_gallery.js" +cp "$dist/gallery.css" "$here/app/assets/stylesheets/visualci_gallery.css" +cp "$here/../../../LICENSE" "$here/LICENSE" diff --git a/clients/gallery/ruby/lib/visualci/gallery.rb b/clients/gallery/ruby/lib/visualci/gallery.rb new file mode 100644 index 00000000..abae2fb6 --- /dev/null +++ b/clients/gallery/ruby/lib/visualci/gallery.rb @@ -0,0 +1,321 @@ +# frozen_string_literal: true + +require 'json' +require 'net/http' +require 'uri' +require_relative 'gallery/version' + +module VisualCI + # A screenshots page from a VisualCI public gallery manifest (https://visualci.com/docs/gallery/), rendered as the + # gallery contract's markup (clients/gallery/contract/SPEC.md in DocSpring/visualci), byte for byte what the + # visualci-gallery JS library renders and hydrates. + # + # manifest = VisualCI::Gallery.fetch('https://app.visualci.com/g/acme/web.json') # raises when it can't + # html = VisualCI::Gallery.render(manifest, title: nil, screens: { 'overview' => { title: 'Overview' } }) + # + # In Rails, `visualci_gallery(manifest, **options)` in a view returns it html_safe, and the engine serves + # visualci_gallery.js (which sets window.VisualCIGallery) and visualci_gallery.css to Sprockets or Propshaft. + module Gallery + # A manifest that can't be read or shown, or options the contract refuses. + class Error < StandardError; end + + DEFAULT_TITLE = 'Screenshots' + SEE_ALL_TEXT = 'See all screenshots' + SIZES = %w[desktop phone].freeze + THEMES = %w[light dark].freeze + # The largest width or height (SPEC.md, "Validation"): the density maths stays exact in every language. + MAX_SIZE = 1_000_000 + SIZE_LABEL = { 'desktop' => 'Desktop', 'phone' => 'Phone' }.freeze + + # Whole-string matches, ASCII digits, and `.` matching line breaks too (/m), as SPEC.md says. + EXTENSION = /\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\z/ + WIDTH_THEME = /\A([0-9]+)-(light|dark)(-2x)?\z/ + SCREEN_THEME = /\A(.+?)-(light|dark)(?:-([0-9]+))?(-2x)?\z/m + ABSOLUTE = %r{\A[hH][tT][tT][pP][sS]?://[^\x00-\x20\x7f]+\z} + CONTROL = /[\x00-\x20\x7f]/ + SCHEME = /\A[A-Za-z][A-Za-z0-9+.-]*:/ + ID = /\A[A-Za-z][A-Za-z0-9_-]*\z/ + UNSET = Object.new.freeze + private_constant :UNSET + + module_function + + # The manifest at `url`, parsed. Raises Error, naming the URL, when it can't be read (a network error, a timeout, + # a status other than 200, JSON that doesn't parse) after `attempts` tries. + def fetch(url, timeout: 20, attempts: 3) + last = nil + attempts = [attempts.to_i, 1].max + attempts.times do |i| + begin + response = get(URI(url), timeout) + raise "HTTP #{response.code}" unless response.code == '200' + + return JSON.parse(response.body) + rescue StandardError => e + last = e + sleep(i + 1) if i + 1 < attempts + end + end + raise Error, "The screenshots gallery couldn't read #{url}: #{last.message}" + end + + # A GET that follows up to 5 redirects, as browsers' fetch does. + def get(uri, timeout, redirects = 5) + response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', + open_timeout: timeout, read_timeout: timeout) do |http| + http.request(Net::HTTP::Get.new(uri)) + end + return response unless response.is_a?(Net::HTTPRedirection) && response['location'] && redirects.positive? + + get(uri + response['location'], timeout, redirects - 1) + end + + # The gallery's HTML for a parsed manifest (a Hash, as JSON.parse gives it). Raises Error when the manifest or the + # options are invalid or nothing in the manifest can be shown. + def render(manifest, **options) + Renderer.new(model(manifest, **options)).call + end + + # The model (SPEC.md, "The model") as a Hash with the same keys as the fixtures' model.json. + def model(manifest, title: UNSET, heading_level: nil, id: nil, screens: nil, order: nil, groups: nil, + group_order: nil, credit: nil, layout: nil, theme_switch: nil, see_all: nil) + check_manifest(manifest) + # Options in the contract's order (SPEC.md, "Validation"): the first problem is the error. + level = opt(heading_level, 'headingLevel') { |v| integral?(v) } + title = title.equal?(UNSET) ? DEFAULT_TITLE : opt(title, 'title') { |v| v.is_a?(String) } + id = opt(id, 'id') { |v| v.is_a?(String) && ID.match?(v) } || 'vg' + screens_opt = texts(screens, 'screens', %w[title caption]) + groups_opt = group_options(groups) + order = strings(order, 'order') + group_order = strings(group_order, 'groupOrder') + credit = opt(credit, 'credit') { |v| boolean?(v) } + switch = opt(theme_switch, 'themeSwitch') { |v| boolean?(v) } + layout = opt(layout, 'layout') { |v| %w[grid strip].include?(v.to_s) }&.to_s || 'grid' + see_all = opt(see_all, 'seeAll') { |v| see_all?(v) } + model = { + 'layout' => layout, + 'themeSwitch' => layout == 'grid' && switch != false, + 'seeAll' => see_all && { 'href' => fetch_key(see_all, 'href'), 'text' => fetch_key(see_all, 'text') || SEE_ALL_TEXT }, + 'title' => title, + 'label' => title || DEFAULT_TITLE, + 'headingLevel' => (level ? level.to_i : 2).clamp(1, 4), + 'id' => id, + 'credit' => credit.nil? ? true : credit, + 'groups' => build_groups(manifest, screens_opt, groups_opt, order, group_order) + } + raise Error, 'the gallery manifest has no screenshots to show' if model['groups'].empty? + + model + end + + # How a manifest name pairs (SPEC.md, "A shot's name"): key, theme (nil for both), size, 2x, CSS width. + def parse_shot(name, width, height, size = nil) + parts = name.sub(EXTENSION, '').split('/', -1) + parts = [''] if parts.empty? # "".split gives [] in Ruby, [""] in JavaScript + last = parts.pop + folder = parts.join('/') + sized = ->(w) { w ? (w.to_i < 768 ? 'phone' : 'desktop') : (size || (height > width ? 'phone' : 'desktop')) } + if folder != '' && (m = WIDTH_THEME.match(last)) + return { key: folder, theme: m[2], size: sized.call(m[1]), x2: !m[3].nil?, css_width: m[1].to_i } + end + if (m = SCREEN_THEME.match(last)) + key = folder == '' ? m[1] : "#{folder}/#{m[1]}" + return { key: key, theme: m[2], size: sized.call(m[3]), x2: !m[4].nil?, css_width: m[3]&.to_i } + end + { key: folder == '' ? last : "#{folder}/#{last}", theme: nil, size: sized.call(nil), x2: false, css_width: nil } + end + + # `billing/free` → "Billing, free". + def humanize(segments) + text = segments.map { |s| s.gsub(/[-_]+/, ' ').gsub(/\A +| +\z/, '') }.join(', ') + return text if text.empty? + + text[0].upcase + text[1..] + end + + # A group's name as an id: ASCII lower case, runs of anything else as one hyphen. + def slugify(name) + slug = name.gsub(/[A-Z]/, &:downcase).gsub(/[^a-z0-9]+/, '-').gsub(/\A-+|-+\z/, '') + slug.empty? ? 'group' : slug + end + + # & < > " ' as entities, and nothing else. + def escape(text) + text.to_s.gsub('&', '&').gsub('<', '<').gsub('>', '>').gsub('"', '"').gsub("'", ''') + end + + def build_groups(manifest, screens_opt, groups_opt, order, group_order) + slugs = {} + groups = manifest['groups'].filter_map do |g| + set = groups_opt[g['name']] || {} + kept = pair(g['items'], set['size']) + # A screen shows both themes at each of its sizes: one theme's image never stands in for the other's. + kept.each do |key, variants| + variants.each do |v| + next if variants.any? { |o| o['size'] == v['size'] && o['theme'] != v['theme'] } + + other = v['theme'] == 'light' ? 'dark' : 'light' + raise Error, "gallery screen #{key} in group #{g['name']} has a #{v['theme']} #{v['size']} screenshot but no #{other} one" + end + end + next if kept.empty? + + prefix = common_folder(kept.map(&:first)).length + list = kept.map do |key, variants| + screen = screens_opt[key] || {} + { 'key' => key, 'title' => screen['title'] || humanize(key.split('/', -1).drop(prefix)), + 'caption' => screen['caption'], 'variants' => variants } + end + list = list.each_with_index.sort_by { |sc, i| [rank(order, sc['key']), sc['key'], i] }.map(&:first) + base = slugify(g['name']) + slug = base + n = 2 + while slugs[slug] + slug = "#{base}-#{n}" + n += 1 + end + slugs[slug] = true + { 'name' => g['name'], 'title' => set['title'] || g['title'] || g['name'], + 'slug' => slug, 'fit' => set['fit'] || 'cover', 'sizes' => SIZES.select { |s| list.any? { |sc| sc['variants'].any? { |v| v['size'] == s } } }, + 'screens' => list } + end + groups.each_with_index.sort_by { |g, i| [rank(group_order, g['name']), i] }.map(&:first) + end + + # [key, variants] for each screen with something to show, in manifest order. + def pair(items, size = nil) + screens = {} + items.each do |item| + width = item['width'].to_i + height = item['height'].to_i + shot = parse_shot(item['name'], width, height, size) + variants = (screens[shot[:key]] ||= {}) + (shot[:theme] ? [shot[:theme]] : THEMES).each do |theme| + v = (variants["#{shot[:size]}-#{theme}"] ||= { 'size' => shot[:size], 'theme' => theme, 'url' => '', + 'url2x' => nil, 'width' => 0, 'height' => 0 }) + if shot[:x2] + v['url2x'] ||= item['url'] + elsif v['url'] == '' + w = shot[:css_width] + scaled = !w.nil? && width > w + v['url'] = item['url'] + v['width'] = scaled ? w : width + v['height'] = scaled ? (2 * height * w + width) / (2 * width) : height + end + end + end + screens.filter_map do |key, variants| + list = variants.values.reject { |v| v['url'] == '' } + .sort_by { |v| [SIZES.index(v['size']), THEMES.index(v['theme'])] } + [key, list] unless list.empty? + end + end + + def common_folder(keys) + folders = keys.map { |k| k.split('/', -1)[0...-1] } + folders.drop(1).reduce(folders.first) do |common, f| + i = 0 + i += 1 while i < common.length && i < f.length && common[i] == f[i] + common.take(i) + end + end + + def rank(list, key) + list.index(key) || list.length + end + + def check_manifest(manifest) + raise Error, 'not a gallery manifest: it has no groups' unless manifest.is_a?(Hash) && manifest['groups'].is_a?(Array) + + manifest['groups'].each_with_index do |g, i| + raise Error, "gallery manifest group #{i} has no name" unless g.is_a?(Hash) && g['name'].is_a?(String) && g['name'] != '' + + name = g['name'] + raise Error, "gallery manifest group #{name}: its title isn't a string" unless g['title'].nil? || g['title'].is_a?(String) + raise Error, "gallery manifest group #{name} has no items" unless g['items'].is_a?(Array) + + g['items'].each_with_index do |item, j| + where = "gallery manifest group #{name}, item #{j}" + raise Error, "#{where} has no name" unless item.is_a?(Hash) && item['name'].is_a?(String) && item['name'] != '' + unless item['url'].is_a?(String) && ABSOLUTE.match?(item['url']) + raise Error, "#{where} (#{item['name']}): its url isn't an http(s) URL" + end + unless positive_integral?(item['width']) && positive_integral?(item['height']) + raise Error, "#{where} (#{item['name']}): its width and height aren't whole numbers from 1 to #{MAX_SIZE}" + end + end + end + end + + # An integer, or a float with no fraction (JSON can't tell 1440 from 1440.0 in JavaScript). + # An integer as JSON has it, and as JavaScript reads it: one past a double's range is Infinity there, so not one. + def integral?(value) + (value.is_a?(Integer) && value.to_f.finite?) || (value.is_a?(Float) && value.finite? && value == value.floor) + end + + def positive_integral?(value) + integral?(value) && value.positive? && value <= MAX_SIZE + end + + def boolean?(value) + [true, false].include?(value) + end + + def opt(value, name) + return nil if value.nil? + raise Error, "gallery option #{name} is invalid" unless yield(value) + + value + end + + def strings(value, name) + opt(value, name) { |v| v.is_a?(Array) && v.all?(String) } || [] + end + + # {"key" => {"title" => …, "caption" => …}} with string keys, values nil or strings. + GROUP_VALUES = { 'size' => SIZES, 'fit' => %w[cover contain] }.freeze + + # groups: {name => {title, size, fit}}; size and fit take their words as strings or symbols. + def group_options(value) + opt(value, 'groups') do |v| + v.is_a?(Hash) && v.values.all? do |entry| + entry.is_a?(Hash) && entry.all? do |k, x| + k = k.to_s + (k == 'title' && (x.nil? || x.is_a?(String))) || + (GROUP_VALUES.key?(k) && (x.nil? || ((x.is_a?(String) || x.is_a?(Symbol)) && GROUP_VALUES[k].include?(x.to_s)))) + end + end + end.to_h { |k, entry| [k.to_s, entry.to_h { |ek, ev| [ek.to_s, ev.is_a?(Symbol) ? ev.to_s : ev] }] } + end + + def texts(value, name, keys) + opt(value, name) do |v| + v.is_a?(Hash) && v.values.all? do |entry| + entry.is_a?(Hash) && entry.all? { |k, x| keys.include?(k.to_s) && (x.nil? || x.is_a?(String)) } + end + end.to_h { |k, entry| [k.to_s, entry.to_h { |ek, ev| [ek.to_s, ev] }] } + end + + def fetch_key(hash, key) + hash.key?(key) ? hash[key] : hash[key.to_sym] + end + + def see_all?(value) + return false unless value.is_a?(Hash) + + href = fetch_key(value, 'href') + text = fetch_key(value, 'text') + href.is_a?(String) && safe_href?(href) && (text.nil? || text.is_a?(String)) + end + + def safe_href?(value) + ABSOLUTE.match?(value) || (value != '' && !CONTROL.match?(value) && !SCHEME.match?(value)) + end + + private_class_method :build_groups, :get, :pair, :common_folder, :rank, :check_manifest, :integral?, + :positive_integral?, :boolean?, :opt, :strings, :texts, :fetch_key, :see_all?, :safe_href? + end +end + +require_relative 'gallery/renderer' +require_relative 'gallery/engine' if defined?(Rails::Engine) diff --git a/clients/gallery/ruby/lib/visualci/gallery/engine.rb b/clients/gallery/ruby/lib/visualci/gallery/engine.rb new file mode 100644 index 00000000..567a4c72 --- /dev/null +++ b/clients/gallery/ruby/lib/visualci/gallery/engine.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +module VisualCI + module Gallery + # In a view: `<%= visualci_gallery(manifest, title: nil, screens: SCREENS) %>`. + module Helper + def visualci_gallery(manifest, **options) + Gallery.render(manifest, **options).html_safe # rubocop:disable Rails/OutputSafety -- escaped by the renderer + end + end + + # Adds the helper to every view and serves app/assets (visualci_gallery.js and visualci_gallery.css, the JS + # library's ES5 build and stylesheet, copied in when the gem is built) to the asset pipeline. + class Engine < ::Rails::Engine + initializer 'visualci_gallery.helper' do + ActiveSupport.on_load(:action_view) { include VisualCI::Gallery::Helper } + end + + # Sprockets compiles only the files it's told to in production; Propshaft serves every asset path as it is, and + # its config.assets has no precompile list (an OrderedOptions answers nil for it). + initializer 'visualci_gallery.assets' do |app| + assets = app.config.respond_to?(:assets) ? app.config.assets : nil + assets.precompile += %w[visualci_gallery.js visualci_gallery.css] if assets && assets.precompile.is_a?(Array) + end + end + end +end diff --git a/clients/gallery/ruby/lib/visualci/gallery/renderer.rb b/clients/gallery/ruby/lib/visualci/gallery/renderer.rb new file mode 100644 index 00000000..e8b00785 --- /dev/null +++ b/clients/gallery/ruby/lib/visualci/gallery/renderer.rb @@ -0,0 +1,138 @@ +# frozen_string_literal: true + +module VisualCI + module Gallery + # The contract's markup from a model (SPEC.md, "The markup"): a port of the JS library's render.ts, line for line. + class Renderer + def initialize(model) + @m = model + @id = Gallery.escape(model['id']) + @below = model['title'].nil? ? 0 : 1 + end + + def call + out = [] + size = @m['layout'] == 'strip' ? strip_size : @m['groups'][0]['sizes'][0] + out << %(
) + out << "<#{h(0)} class=\"vg-title\">#{esc(@m['title'])}" unless @m['title'].nil? + @m['layout'] == 'strip' ? strip(out) : grid(out) + if (see = @m['seeAll']) + out << %(

#{esc(see['text'])}

) + end + if @m['credit'] + out << '

Screenshot Gallery Powered by VisualCI.com

' + end + out << %() + out << %(
<#{h(@below)} class="vg-box-title" id="#{@id}-box-title">) + + '
' + + (@m['themeSwitch'] ? themes : '') + + (@m['layout'] == 'grid' ? sizes(%w[desktop phone], ' vg-box-sizes') : '') + + '' \ + '' \ + '' \ + '
' + out << '
' + out << '
' + out << '
' + "#{out.join("\n")}\n" + end + + private + + def esc(text) = Gallery.escape(text) + + def h(offset) = "h#{[@m['headingLevel'] + offset, 6].min}" + + def themes + '
' \ + '' \ + '' \ + '
' + end + + def sizes(list, extra = '') + %(
) + + list.map { |s| %() }.join + + '
' + end + + def image(title, v, themes) + alt = "#{title}, #{SIZE_LABEL[v['size']].downcase}, #{themes.join(' and ')}" + %(#{esc(alt)}) + end + + def card(sc, sizes, heading, caption, fit) + imgs = [] + shown = [] + first = nil + sizes.each do |size| + at = sc['variants'].select { |v| v['size'] == size } + next if at.empty? + + shown << size + first ||= at[0] + # Every size has both themes (the model refuses a screen without); the same image for both is shown once. + if at[0]['url'] == at[1]['url'] && at[0]['url2x'] == at[1]['url2x'] + imgs << image(sc['title'], at[0], %w[light dark]) + else + at.each { |v| imgs << image(sc['title'], v, [v['theme']]) } + end + end + %(
  • ' + + %() + + imgs.join + '' + + %(<#{heading} class="vg-card-title">#{esc(sc['title'])}) + + (caption && !sc['caption'].nil? ? %(

    #{esc(sc['caption'])}

    ) : '') + + '
  • ' + end + + def grid(out) + groups = @m['groups'] + tabs = groups.length > 1 + if tabs + out << %(
    ) + groups.each_with_index do |g, i| + out << %() + end + out << '
    ' + end + groups.each_with_index do |g, i| + out << %(
    ' + controls = (@m['themeSwitch'] ? themes : '') + (g['sizes'].length > 1 ? sizes(g['sizes']) : '') + out << %(
    <#{h(@below)} class="vg-group-title">#{esc(g['title'])}) + + (controls.empty? ? '' : %(
    #{controls}
    )) + '
    ' + out << '
      ' + g['screens'].each { |sc| out << card(sc, g['sizes'], h(@below + 1), true, g['fit']) } + out << '
    ' + out << '
    ' + end + end + + def strip_size + @m['groups'].any? { |g| g['sizes'].include?('desktop') } ? 'desktop' : 'phone' + end + + def strip(out) + size = strip_size + out << %(
    ) + out << '
    ' + out << '
      ' + @m['groups'].each do |g| + g['screens'].each do |sc| + out << card(sc, [size], h(@below), false, g['fit']) if sc['variants'].any? { |v| v['size'] == size } + end + end + out << '
    ' + out << '
    ' + out << '
    ' + end + end + end +end diff --git a/clients/gallery/ruby/lib/visualci/gallery/version.rb b/clients/gallery/ruby/lib/visualci/gallery/version.rb new file mode 100644 index 00000000..0211f3cf --- /dev/null +++ b/clients/gallery/ruby/lib/visualci/gallery/version.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +module VisualCI + module Gallery + VERSION = '0.1.0' + end +end diff --git a/clients/gallery/ruby/test/gallery_test.rb b/clients/gallery/ruby/test/gallery_test.rb new file mode 100644 index 00000000..64c6448b --- /dev/null +++ b/clients/gallery/ruby/test/gallery_test.rb @@ -0,0 +1,120 @@ +# frozen_string_literal: true + +require 'minitest/autorun' +require 'json' +require 'socket' +require_relative '../lib/visualci/gallery' + +# The gallery contract's golden fixtures (../contract): every fixture's manifest and options give exactly its +# model.json and gallery.html, and every manifest in errors/ and option in option-errors/ is refused. +class GalleryContractTest < Minitest::Test + CONTRACT = File.expand_path('../../contract', __dir__) + OPTION_NAMES = { 'headingLevel' => :heading_level, 'groupOrder' => :group_order, 'themeSwitch' => :theme_switch, + 'seeAll' => :see_all }.freeze + + def self.options(json) + json.to_h { |k, v| [OPTION_NAMES.fetch(k, k.to_sym), v] } + end + + def read(path) = JSON.parse(File.read(path, encoding: 'UTF-8')) + + Dir[File.join(CONTRACT, 'fixtures', '*')].each do |dir| + name = File.basename(dir) + define_method("test_fixture_#{name}") do + manifest = read(File.join(dir, 'manifest.json')) + options = self.class.options(read(File.join(dir, 'options.json'))) + assert_equal read(File.join(dir, 'model.json')), VisualCI::Gallery.model(manifest, **options) + assert_equal File.read(File.join(dir, 'gallery.html'), encoding: 'UTF-8'), VisualCI::Gallery.render(manifest, **options) + end + end + + # A refusal's message, word for word: .message beside .json. + def assert_refused(path) + error = assert_raises(VisualCI::Gallery::Error) { yield } + assert_equal File.read(path.sub(/\.json\z/, '.message'), encoding: 'UTF-8'), "#{error.message}\n" + end + + Dir[File.join(CONTRACT, 'errors', '*.json')].each do |path| + define_method("test_refuses_manifest_#{File.basename(path, '.json')}") do + assert_refused(path) { VisualCI::Gallery.render(read(path)) } + end + end + + Dir[File.join(CONTRACT, 'option-errors', '*.json')].each do |path| + define_method("test_refuses_option_#{File.basename(path, '.json')}") do + manifest = read(File.join(CONTRACT, 'fixtures', 'visualci', 'manifest.json')) + assert_refused(path) { VisualCI::Gallery.render(manifest, **self.class.options(read(path))) } + end + end + + def test_has_fixtures + refute_empty Dir[File.join(CONTRACT, 'fixtures', '*')] + end +end + +# Ruby spellings: symbol keys work as well as strings. +class GalleryOptionsTest < Minitest::Test + MANIFEST = JSON.parse(File.read(File.expand_path('../../contract/fixtures/fleetlayer/manifest.json', __dir__), encoding: 'UTF-8')) + + def test_symbol_keys + html = VisualCI::Gallery.render(MANIFEST, title: nil, screens: { overview: { title: 'Overview!' } }, + see_all: { href: '/all' }) + assert_includes html, '

    Overview!

    ' + assert_includes html, 'See all screenshots' + end + + def test_parse_shot_and_titles + assert_equal({ key: 'shots/app/billing', theme: 'dark', size: 'desktop', x2: true, css_width: 1440 }, + VisualCI::Gallery.parse_shot('shots/app/billing/1440-dark-2x', 2880, 1800)) + assert_equal 'SSig', VisualCI::Gallery.humanize(['ßig']) + assert_equal 'os', VisualCI::Gallery.slugify('İOS') + end +end + +# fetch: the manifest over HTTP, and a clear error when it can't be read. +class GalleryFetchTest < Minitest::Test + def serve(status, body, headers = '') + server = TCPServer.new('127.0.0.1', 0) + thread = Thread.new do + loop do + client = server.accept + client.gets + while (line = client.gets) && line != "\r\n"; end + client.write("HTTP/1.1 #{status}\r\nContent-Type: application/json\r\nContent-Length: #{body.bytesize}\r\n" \ + "#{headers}Connection: close\r\n\r\n#{body}") + client.close + end + end + yield "http://127.0.0.1:#{server.addr[1]}/g/acme/web.json" + ensure + thread&.kill + server&.close + end + + def test_follows_redirects + serve('200 OK', '{"groups": []}') do |target| + serve('302 Found', '', "Location: #{target}\r\n") do |url| + assert_equal({ 'groups' => [] }, VisualCI::Gallery.fetch(url, attempts: 1)) + end + end + end + + def test_fetches_and_parses + serve('200 OK', '{"groups":[]}') do |url| + assert_equal({ 'groups' => [] }, VisualCI::Gallery.fetch(url)) + end + end + + def test_raises_naming_the_url + serve('503 Service Unavailable', 'down') do |url| + error = assert_raises(VisualCI::Gallery::Error) { VisualCI::Gallery.fetch(url, attempts: 1) } + assert_equal "The screenshots gallery couldn't read #{url}: HTTP 503", error.message + end + end + + def test_raises_on_bad_json + serve('200 OK', 'not json') do |url| + assert_raises(VisualCI::Gallery::Error) { VisualCI::Gallery.fetch(url, attempts: 1) } + end + end +end diff --git a/clients/gallery/ruby/visualci-gallery.gemspec b/clients/gallery/ruby/visualci-gallery.gemspec new file mode 100644 index 00000000..ce7fe34e --- /dev/null +++ b/clients/gallery/ruby/visualci-gallery.gemspec @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +require_relative 'lib/visualci/gallery/version' + +Gem::Specification.new do |s| + s.name = 'visualci-gallery' + s.version = VisualCI::Gallery::VERSION + s.summary = 'A screenshots page from a VisualCI public gallery, rendered in Ruby or Rails' + s.description = 'Fetches a VisualCI public gallery manifest and renders a screenshots page (tabs, light and dark, ' \ + 'desktop and phone, a full-size view) as the markup the visualci-gallery JS library hydrates. ' \ + 'Includes a Rails helper and the library\'s script and stylesheet for the asset pipeline.' + s.authors = ['DocSpring'] + s.homepage = 'https://visualci.com/docs/gallery/' + s.license = 'Apache-2.0' + s.required_ruby_version = '>= 3.1' + s.files = Dir['lib/**/*.rb'] + Dir['app/assets/**/*.{js,css}'] + ['README.md', 'LICENSE'] + s.metadata = { + 'homepage_uri' => 'https://visualci.com/docs/gallery/', + 'source_code_uri' => 'https://github.com/DocSpring/visualci/tree/main/clients/gallery/ruby', + 'bug_tracker_uri' => 'https://github.com/DocSpring/visualci/issues', + 'rubygems_mfa_required' => 'true' + } +end