Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,19 @@ jobs:
# 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 gallery's Python renderer: the contract's golden fixtures, on the oldest Python it supports and the newest.
- uses: actions/setup-python@v5
with:
python-version: |
3.10
3.14
- run: python3.10 -W error -m unittest discover -s tests && python3.14 -W error -m unittest discover -s tests
working-directory: clients/gallery/python
env:
PYTHONPATH: src
# Its wheel carries the library's built script and stylesheet.
- run: bin/assets && python3.14 -m pip install --quiet build && python3.14 -m build --wheel && unzip -l dist/*.whl | grep -q visualci_gallery/static/visualci_gallery/visualci_gallery.js
working-directory: clients/gallery/python
# 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
Expand Down
47 changes: 47 additions & 0 deletions .github/workflows/release-gallery-python.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Publish the visualci-gallery Python package (clients/gallery/python) to PyPI with trusted publishing: PyPI trusts this
# workflow through GitHub's OIDC token, so no API token is stored anywhere (the pending publisher is in Nathan's Tasks
# sc-9327). Runs for a gallery-python-v* tag (matching the version in pyproject.toml) or by hand. The package carries
# the JS library's ES5 build and stylesheet (bin/assets).
name: Release gallery Python package

on:
push:
tags: ["gallery-python-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: actions/setup-python@v5
with:
python-version: "3.14"
- name: The tag matches the package's version
if: startsWith(github.ref, 'refs/tags/gallery-python-v')
working-directory: clients/gallery/python
run: |
version=$(python -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')
test "gallery-python-v$version" = "$GITHUB_REF_NAME" || { echo "tag $GITHUB_REF_NAME, package $version"; exit 1; }
- run: python -W error -m unittest discover -s tests
working-directory: clients/gallery/python
env:
PYTHONPATH: src
- run: bin/assets && python -m pip install --quiet build && python -m build
working-directory: clients/gallery/python
- uses: pypa/gh-action-pypi-publish@release/v1
with:
packages-dir: clients/gallery/python/dist
6 changes: 4 additions & 2 deletions clients/gallery/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ variables.
- [`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.
- [`python/`](python/README.md): the `visualci-gallery` package, standard library only, with the library's files for
Django's static files.

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.
A pnpm workspace: `pnpm install && pnpm build && pnpm test` here. Coming: the Rust crate, emitting the contract's
markup for the JS library to hydrate.
4 changes: 4 additions & 0 deletions clients/gallery/python/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
src/visualci_gallery/static/
dist/
__pycache__/
*.egg-info/
46 changes: 46 additions & 0 deletions clients/gallery/python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# visualci-gallery (Python)

A screenshots page from a VisualCI [public gallery](https://visualci.com/docs/gallery/) manifest, rendered in Python as
the [gallery contract](https://github.com/DocSpring/visualci/blob/main/clients/gallery/contract/SPEC.md)'s markup. The
markup is byte for byte what the `visualci-gallery` JS library renders, so the library's script hydrates it: tabs,
light and dark, desktop and phone, and the full-size view. No dependencies beyond the standard library.

```python
from visualci_gallery import fetch, render

manifest = fetch("https://app.visualci.com/g/acme/web.json") # raises GalleryError
html = render(manifest, title=None, layout="strip", theme_switch=False,
screens={"screenshots/templates": {"title": "Templates"}},
see_all={"href": "/screenshots"})
```

`fetch` raises `GalleryError` when the manifest can't be read. `render` raises it when the manifest has nothing to
show or the options are invalid. There's no fallback: a site fetches the manifest when it builds and fails the build
if it can't, then renders from that copy.

## The script and stylesheet

The package carries the library's ES5 build and stylesheet in `static/visualci_gallery/`. With `visualci_gallery` in
Django's `INSTALLED_APPS`:

```django
{% load static %}
<link rel="stylesheet" href="{% static 'visualci_gallery/visualci_gallery.css' %}">
{{ gallery_html|safe }}
<script src="{% static 'visualci_gallery/visualci_gallery.js' %}"></script>
<script>document.querySelectorAll("[data-vg]").forEach(function (el) { VisualCIGallery.hydrate(el); });</script>
```

Elsewhere, `visualci_gallery.static_dir()` is that folder, so you can copy it into your static files. In Jinja, mark
the HTML safe with `markupsafe.Markup(html)`. The stylesheet is styled through `--vg-*` CSS variables.

## Options

Keyword arguments, the contract's options in Python spelling: `title` (default "Screenshots"; `None` for no heading),
`heading_level`, `id`, `screens`, `order`, `groups` (such as `{"Mac approver": {"size": "desktop", "fit": "contain"}}`
for an app's windows), `group_order`, `credit`, `layout` (`"grid"` or `"strip"`), `theme_switch`, `see_all`.

## Development

`PYTHONPATH=src python -m unittest discover -s tests` checks the contract's golden fixtures. `bin/assets` copies the JS
library's build into the package before `python -m build`.
10 changes: 10 additions & 0 deletions clients/gallery/python/bin/assets
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/sh
# Copies the JS library's ES5 build and stylesheet (clients/gallery/js, built with `pnpm build`) into the package's
# static folder, before `python -m build`.
set -eu
here=$(cd "$(dirname "$0")/.." && pwd)
dist="$here/../js/dist"
test -f "$dist/gallery.iife.js" || { echo "build clients/gallery/js first (pnpm build)" >&2; exit 1; }
mkdir -p "$here/src/visualci_gallery/static/visualci_gallery"
cp "$dist/gallery.iife.js" "$here/src/visualci_gallery/static/visualci_gallery/visualci_gallery.js"
cp "$dist/gallery.css" "$here/src/visualci_gallery/static/visualci_gallery/visualci_gallery.css"
30 changes: 30 additions & 0 deletions clients/gallery/python/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
[build-system]
requires = ["hatchling>=1.25"]
build-backend = "hatchling.build"

[project]
name = "visualci-gallery"
version = "0.1.0"
description = "A screenshots page from VisualCI's public gallery, rendered in Python and hydrated by the visualci-gallery script."
readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.10"
keywords = ["screenshots", "gallery", "visualci"]
classifiers = [
"Programming Language :: Python :: 3",
"Framework :: Django",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
]

[project.urls]
Homepage = "https://visualci.com/docs/gallery/"
Source = "https://github.com/DocSpring/visualci/tree/main/clients/gallery/python"

[tool.hatch.build.targets.wheel]
packages = ["src/visualci_gallery"]
# bin/assets copies the JS library's build here; it's ignored by git but must be in the wheel.
artifacts = ["src/visualci_gallery/static/**"]

[tool.hatch.build.targets.sdist]
include = ["src/visualci_gallery", "README.md", "tests"]
artifacts = ["src/visualci_gallery/static/**"]
71 changes: 71 additions & 0 deletions clients/gallery/python/src/visualci_gallery/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""visualci-gallery: a screenshots page from a VisualCI public gallery manifest, rendered in Python as the gallery
contract's markup, byte for byte what the visualci-gallery JS library renders, so its script hydrates it.

from visualci_gallery import fetch, render

html = render(fetch("https://app.visualci.com/g/acme/web.json"), title=None)

fetch() raises GalleryError when the manifest can't be read; render() raises it when the manifest has nothing to show
or the options are invalid. There is no fallback: a static site's build fails rather than ship without screenshots.
"""

from __future__ import annotations

import http.client
import json
import time
import urllib.error
import urllib.request
from importlib.resources import files
from typing import Any

from ._model import GalleryError, build_model, humanize, parse_shot, slugify
from ._render import escape, render_model

__all__ = [
"GalleryError",
"build_model",
"escape",
"fetch",
"humanize",
"parse_shot",
"render",
"render_model",
"slugify",
"static_dir",
]


def fetch(url: str, *, timeout: float = 20, attempts: int = 3) -> Any:
"""The manifest at `url`, parsed. Raises GalleryError, 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."""
attempts = max(int(attempts), 1)
last: Exception | None = None
for i in range(attempts):
try:
request = urllib.request.Request(url, headers={"Accept": "application/json"})
with urllib.request.urlopen(request, timeout=timeout) as response:
if response.status != 200:
raise OSError(f"HTTP {response.status}")
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as e:
e.close()
last = OSError(f"HTTP {e.code}")
except (OSError, ValueError, http.client.HTTPException) as e:
last = e
if i + 1 < attempts:
time.sleep(i + 1)
raise GalleryError(f"The screenshots gallery couldn't read {url}: {last}")


def render(manifest: Any, **options: Any) -> str:
"""The gallery's HTML for a parsed manifest. Options are the contract's, in Python spelling: title (None for no
heading), heading_level, id, screens, order, groups, group_order, credit, layout, theme_switch, see_all.
Raises GalleryError when the manifest or the options are invalid or nothing in the manifest can be shown."""
return render_model(build_model(manifest, **options))


def static_dir():
"""The folder with the JS library's ES5 build and stylesheet (visualci_gallery/visualci_gallery.js and .css), for
a site's static files. Django finds it as the app's static/ folder when visualci_gallery is in INSTALLED_APPS."""
return files(__package__) / "static"
Loading
Loading