diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9907a850..1a37d4c4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.github/workflows/release-gallery-python.yml b/.github/workflows/release-gallery-python.yml new file mode 100644 index 00000000..4614fd4b --- /dev/null +++ b/.github/workflows/release-gallery-python.yml @@ -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 diff --git a/clients/gallery/README.md b/clients/gallery/README.md index 152629f7..2a647e54 100644 --- a/clients/gallery/README.md +++ b/clients/gallery/README.md @@ -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. diff --git a/clients/gallery/python/.gitignore b/clients/gallery/python/.gitignore new file mode 100644 index 00000000..43af328b --- /dev/null +++ b/clients/gallery/python/.gitignore @@ -0,0 +1,4 @@ +src/visualci_gallery/static/ +dist/ +__pycache__/ +*.egg-info/ diff --git a/clients/gallery/python/README.md b/clients/gallery/python/README.md new file mode 100644 index 00000000..06057360 --- /dev/null +++ b/clients/gallery/python/README.md @@ -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 %} + +{{ gallery_html|safe }} + + +``` + +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`. diff --git a/clients/gallery/python/bin/assets b/clients/gallery/python/bin/assets new file mode 100755 index 00000000..1fdabc10 --- /dev/null +++ b/clients/gallery/python/bin/assets @@ -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" diff --git a/clients/gallery/python/pyproject.toml b/clients/gallery/python/pyproject.toml new file mode 100644 index 00000000..f24ad11e --- /dev/null +++ b/clients/gallery/python/pyproject.toml @@ -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/**"] diff --git a/clients/gallery/python/src/visualci_gallery/__init__.py b/clients/gallery/python/src/visualci_gallery/__init__.py new file mode 100644 index 00000000..e868d4a4 --- /dev/null +++ b/clients/gallery/python/src/visualci_gallery/__init__.py @@ -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" diff --git a/clients/gallery/python/src/visualci_gallery/_model.py b/clients/gallery/python/src/visualci_gallery/_model.py new file mode 100644 index 00000000..80f1a189 --- /dev/null +++ b/clients/gallery/python/src/visualci_gallery/_model.py @@ -0,0 +1,333 @@ +"""The gallery's model from a VisualCI public gallery manifest (contract/SPEC.md): a line-for-line port of the JS +library's model.ts, so every renderer gives the same model and markup.""" + +from __future__ import annotations + +import math +import re +import sys +from typing import Any + +DEFAULT_TITLE = "Screenshots" +SEE_ALL_TEXT = "See all screenshots" +SIZES = ("desktop", "phone") +THEMES = ("light", "dark") + +# Whole-string matches (re.fullmatch), ASCII digits only and "any character" including line breaks, so every +# language's regex engine agrees (contract/SPEC.md, "A shot's name"). +_EXTENSION = re.compile(r"\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\Z") +_WIDTH_THEME = re.compile(r"([0-9]+)-(light|dark)(-2x)?") +_SCREEN_THEME = re.compile(r"([\s\S]+?)-(light|dark)(?:-([0-9]+))?(-2x)?") +_ABSOLUTE = re.compile(r"[hH][tT][tT][pP][sS]?://[^\x00-\x20\x7f]+") +_CONTROL = re.compile(r"[\x00-\x20\x7f]") +_SCHEME = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*:") +_ID = re.compile(r"[A-Za-z][A-Za-z0-9_-]*") + + +class GalleryError(Exception): + """The manifest can't be read, it or the options are invalid, or nothing in it can be shown.""" + + +def _fail(message: str) -> Any: + raise GalleryError(message) + + +def _integral(v: Any) -> bool: + """An integer as JSON has it: Python's int (not bool), or a float with no fraction (JavaScript can't tell 1440 + from 1440.0).""" + if isinstance(v, bool): + return False + if isinstance(v, int): + # As JavaScript reads it: one past a double's range is Infinity there, so not an integer. + return abs(v) <= _MAX_DOUBLE + return isinstance(v, float) and math.isfinite(v) and v.is_integer() + + +_MAX_DOUBLE = int(sys.float_info.max) + + +# The largest width or height (SPEC.md, "Validation"): the density maths stays exact in every language. +MAX_SIZE = 1_000_000 + + +def _is_size(v: Any) -> bool: + return _integral(v) and 0 < v <= MAX_SIZE + + +def parse_shot(name: str, width: int, height: int, size: str | None = None) -> dict[str, Any]: + """How a manifest name pairs: `-[-][-2x]`, or `/-[-2x]`. A name in + neither shape is a screen of its own, in both themes. Under 768 wide is a phone; with no width, a portrait image + is a phone and a landscape one a desktop, unless `size` says.""" + parts = _EXTENSION.sub("", name).split("/") + last = parts.pop() + folder = "/".join(parts) + + # A width in a name can have any number of digits, and leading zeros don't count ("0390" is 390): past 18 more it's + # too big to matter (desktop, never scaled), and int() of a few thousand digits would raise. + def value(w: str) -> int | None: + digits = w.lstrip("0") or "0" + return int(digits) if len(digits) <= 18 else None + + def sized(w: str | None) -> str: + if w is not None: + n = value(w) + return "phone" if n is not None and n < 768 else "desktop" + return size or ("phone" if height > width else "desktop") + + def css(w: str | None) -> int | None: + return value(w) if w is not None else None + + m = _WIDTH_THEME.fullmatch(last) + if m and folder: + return {"key": folder, "theme": m[2], "size": sized(m[1]), "x2": bool(m[3]), "css_width": css(m[1])} + m = _SCREEN_THEME.fullmatch(last) + if m: + key = f"{folder}/{m[1]}" if folder else m[1] + return {"key": key, "theme": m[2], "size": sized(m[3]), "x2": bool(m[4]), "css_width": css(m[3])} + key = f"{folder}/{last}" if folder else last + return {"key": key, "theme": None, "size": sized(None), "x2": False, "css_width": None} + + +def humanize(segments: list[str]) -> str: + """`["billing", "free"]` → "Billing, free".""" + text = ", ".join(re.sub(r"[-_]+", " ", s).strip(" ") for s in segments) + return text[:1].upper() + text[1:] + + +def slugify(name: str) -> str: + """A group's name as an id: ASCII lower case, runs of anything else as one hyphen.""" + lowered = re.sub(r"[A-Z]", lambda m: m[0].lower(), name) + return re.sub(r"[^a-z0-9]+", "-", lowered).strip("-") or "group" + + +def _common_folder(keys: list[str]) -> list[str]: + folders = [k.split("/")[:-1] for k in keys] + if not folders: + return [] + common = folders[0] + for f in folders[1:]: + i = 0 + while i < len(common) and i < len(f) and common[i] == f[i]: + i += 1 + common = common[:i] + return common + + +def _rank_by(order: list[str] | None): + items = order or [] + + def rank(key: str) -> int: + return items.index(key) if key in items else len(items) + + return rank + + +def _safe_href(value: str) -> bool: + if _ABSOLUTE.fullmatch(value): + return True + return value != "" and not _CONTROL.search(value) and not _SCHEME.match(value) + + +def _opt(value: Any, check, what: str) -> Any: + """An option's value, with None meaning absent.""" + if value is None: + return None + if not check(value): + _fail(f"gallery option {what} is invalid") + return value + + +def _texts(keys: tuple[str, ...]): + def check(v: Any) -> bool: + return isinstance(v, dict) and all( + isinstance(entry, dict) and all(k in keys and (x is None or isinstance(x, str)) for k, x in entry.items()) + for entry in v.values() + ) + + return check + + +def _group_options(v: Any) -> bool: + def ok(k: str, x: Any) -> bool: + if k == "title": + return x is None or isinstance(x, str) + if k == "size": + return x is None or x in SIZES + if k == "fit": + return x is None or x in ("cover", "contain") + return False + + return isinstance(v, dict) and all( + isinstance(entry, dict) and all(ok(k, x) for k, x in entry.items()) for entry in v.values() + ) + + +def _strings(v: Any) -> bool: + return isinstance(v, list) and all(isinstance(x, str) for x in v) + + +def _check_manifest(manifest: Any) -> None: + """The manifest's shape (contract/SPEC.md, "Validation"): anything else is refused.""" + if not isinstance(manifest, dict) or not isinstance(manifest.get("groups"), list): + _fail("not a gallery manifest: it has no groups") + for i, g in enumerate(manifest["groups"]): + if not isinstance(g, dict) or not isinstance(g.get("name"), str) or g["name"] == "": + _fail(f"gallery manifest group {i} has no name") + if g.get("title") is not None and not isinstance(g["title"], str): + _fail(f"gallery manifest group {g['name']}: its title isn't a string") + if not isinstance(g.get("items"), list): + _fail(f"gallery manifest group {g['name']} has no items") + for j, item in enumerate(g["items"]): + where = f"gallery manifest group {g['name']}, item {j}" + if not isinstance(item, dict) or not isinstance(item.get("name"), str) or item["name"] == "": + _fail(f"{where} has no name") + if not isinstance(item.get("url"), str) or not _ABSOLUTE.fullmatch(item["url"]): + _fail(f"{where} ({item['name']}): its url isn't an http(s) URL") + if not _is_size(item.get("width")) or not _is_size(item.get("height")): + _fail(f"{where} ({item['name']}): its width and height aren't whole numbers from 1 to {MAX_SIZE}") + + +_UNSET: Any = object() + + +def build_model( + manifest: Any, + *, + title: Any = _UNSET, + heading_level: Any = None, + id: Any = None, + screens: Any = None, + order: Any = None, + groups: Any = None, + group_order: Any = None, + credit: Any = None, + layout: Any = None, + theme_switch: Any = None, + see_all: Any = None, +) -> dict[str, Any]: + """The manifest as the gallery shows it (contract/SPEC.md), as a dict with the keys of the fixtures' model.json. + Raises GalleryError when it or the options are invalid, or nothing in it can be shown.""" + _check_manifest(manifest) + level = _opt(heading_level, _integral, "headingLevel") + heading = min(max(int(level) if level is not None else 2, 1), 4) + title = DEFAULT_TITLE if title is _UNSET else _opt(title, lambda v: isinstance(v, str), "title") + gid = _opt(id, lambda v: isinstance(v, str) and bool(_ID.fullmatch(v)), "id") or "vg" + screens_opt = _opt(screens, _texts(("title", "caption")), "screens") or {} + groups_opt = _opt(groups, _group_options, "groups") or {} + order = _opt(order, _strings, "order") + group_order = _opt(group_order, _strings, "groupOrder") + credit = _opt(credit, lambda v: isinstance(v, bool), "credit") + credit = True if credit is None else credit + switch = _opt(theme_switch, lambda v: isinstance(v, bool), "themeSwitch") + switch = True if switch is None else switch + layout = _opt(layout, lambda v: v in ("grid", "strip"), "layout") or "grid" + see_all = _opt( + see_all, + lambda v: isinstance(v, dict) + and isinstance(v.get("href"), str) + and _safe_href(v["href"]) + and (v.get("text") is None or isinstance(v["text"], str)), + "seeAll", + ) + slugs: set[str] = set() + + built: list[dict[str, Any]] = [] + for g in manifest["groups"]: + group_set = groups_opt.get(g["name"]) or {} + found: dict[str, dict[str, dict[str, Any]]] = {} + for item in g["items"]: + w, h = int(item["width"]), int(item["height"]) + shot = parse_shot(item["name"], w, h, group_set.get("size")) + variants = found.setdefault(shot["key"], {}) + for theme in [shot["theme"]] if shot["theme"] else THEMES: + v = variants.setdefault( + f"{shot['size']}-{theme}", + {"size": shot["size"], "theme": theme, "url": "", "url2x": None, "width": 0, "height": 0}, + ) + if shot["x2"]: + if v["url2x"] is None: + v["url2x"] = item["url"] + elif v["url"] == "": + # An image wider than the width its name gives was taken at a higher density: shown at the + # name's width, its height rounded half up in integers (the same in every language). + cw = shot["css_width"] + if cw is not None and w > cw: + v.update(url=item["url"], width=cw, height=(2 * h * cw + w) // (2 * w)) + else: + v.update(url=item["url"], width=w, height=h) + # The screens that have something to show; titles are made from these keys only. + kept = [] + for key, variants in found.items(): + shown = sorted( + (v for v in variants.values() if v["url"] != ""), + key=lambda v: (SIZES.index(v["size"]), THEMES.index(v["theme"])), + ) + if shown: + kept.append((key, shown)) + # A screen shows both themes at each of its sizes: one theme's image never stands in for the other's. + for key, variants in kept: + for v in variants: + if not any(o["size"] == v["size"] and o["theme"] != v["theme"] for o in variants): + other = "dark" if v["theme"] == "light" else "light" + _fail( + f"gallery screen {key} in group {g['name']} has a {v['theme']} {v['size']} screenshot " + f"but no {other} one" + ) + if not kept: + continue + prefix = len(_common_folder([key for key, _ in kept])) + rank = _rank_by(order) + listed = [] + for key, variants in kept: + screen = screens_opt.get(key) or {} + listed.append( + { + "key": key, + "title": screen.get("title") if screen.get("title") is not None else humanize(key.split("/")[prefix:]), + "caption": screen.get("caption"), + "variants": variants, + } + ) + listed.sort(key=lambda sc: (rank(sc["key"]), sc["key"])) + + slug = slugify(g["name"]) + n = 2 + while slug in slugs: + slug = f"{slugify(g['name'])}-{n}" + n += 1 + slugs.add(slug) + group_title = group_set.get("title") + if group_title is None: + group_title = g.get("title") if g.get("title") is not None else g["name"] + built.append( + { + "name": g["name"], + "title": group_title, + "slug": slug, + "fit": group_set.get("fit") or "cover", + "sizes": [s for s in SIZES if any(v["size"] == s for sc in listed for v in sc["variants"])], + "screens": listed, + } + ) + if not built: + _fail("the gallery manifest has no screenshots to show") + + # Named groups first; the rest keep the manifest's order (the sort is stable). + group_rank = _rank_by(group_order) + built.sort(key=lambda g: group_rank(g["name"])) + + return { + "layout": layout, + "themeSwitch": layout == "grid" and switch, + "seeAll": ( + {"href": see_all["href"], "text": see_all["text"] if see_all.get("text") is not None else SEE_ALL_TEXT} + if see_all + else None + ), + "title": title, + "label": title if title is not None else DEFAULT_TITLE, + "headingLevel": heading, + "id": gid, + "credit": credit, + "groups": built, + } diff --git a/clients/gallery/python/src/visualci_gallery/_render.py b/clients/gallery/python/src/visualci_gallery/_render.py new file mode 100644 index 00000000..449e339f --- /dev/null +++ b/clients/gallery/python/src/visualci_gallery/_render.py @@ -0,0 +1,168 @@ +"""The gallery's HTML from its model: the markup every renderer emits byte for byte (contract/SPEC.md, "The markup"), +a line-for-line port of the JS library's render.ts.""" + +from __future__ import annotations + +from typing import Any + +SIZE_LABEL = {"desktop": "Desktop", "phone": "Phone"} + + +def escape(s: str) -> str: + """& < > " ' as entities: the only escaping the contract allows, so every language's output is the same.""" + return ( + s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """).replace("'", "'") + ) + + +def _theme_switch() -> str: + return ( + '
' + '' + '' + "
" + ) + + +def _size_switch(sizes: list[str], extra: str = "") -> str: + buttons = "".join( + f'' for s in sizes + ) + return f'
{buttons}
' + + +def _image(title: str, v: dict[str, Any], themes: list[str]) -> str: + alt = f"{title}, {SIZE_LABEL[v['size']].lower()}, {' and '.join(themes)}" + return ( + f'{escape(alt)}' + ) + + +def _card(sc: dict[str, Any], sizes: list[str], heading: str, caption: bool, fit: str) -> str: + imgs: list[str] = [] + shown: list[str] = [] + first = None + for size in sizes: + at = [v for v in sc["variants"] if v["size"] == size] + if not at: + continue + shown.append(size) + first = first or 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"] and at[0]["url2x"] == at[1]["url2x"]: + imgs.append(_image(sc["title"], at[0], ["light", "dark"])) + else: + imgs.extend(_image(sc["title"], v, [v["theme"]]) for v in at) + assert first is not None + return ( + f'
  • " + + f'' + + "".join(imgs) + + "" + + f'<{heading} class="vg-card-title">{escape(sc["title"])}' + + (f'

    {escape(sc["caption"])}

    ' if caption and sc["caption"] is not None else "") + + "
  • " + ) + + +def _strip_size(model: dict[str, Any]) -> str: + """Every screen of every group at one size (desktop when any group has it) in one row.""" + return "desktop" if any("desktop" in g["sizes"] for g in model["groups"]) else "phone" + + +def _grid(model: dict[str, Any], gid: str, gh: str, ch: str, out: list[str]) -> None: + tabs = len(model["groups"]) > 1 + if tabs: + out.append(f'
    ') + for i, g in enumerate(model["groups"]): + out.append( + f'' + ) + out.append("
    ") + for i, g in enumerate(model["groups"]): + out.append( + f'
    0 else "") + + ">" + ) + controls = (_theme_switch() if model["themeSwitch"] else "") + ( + _size_switch(g["sizes"]) if len(g["sizes"]) > 1 else "" + ) + out.append( + f'
    <{gh} class="vg-group-title">{escape(g["title"])}' + + (f'
    {controls}
    ' if controls else "") + + "
    " + ) + out.append('
      ') + out.extend(_card(sc, g["sizes"], ch, True, g["fit"]) for sc in g["screens"]) + out.append("
    ") + out.append("
    ") + + +def _strip(model: dict[str, Any], gid: str, ch: str, out: list[str]) -> None: + size = _strip_size(model) + out.append(f'
    ') + out.append( + '
    ' + ) + out.append('
      ') + for g in model["groups"]: + for sc in g["screens"]: + if any(v["size"] == size for v in sc["variants"]): + out.append(_card(sc, [size], ch, False, g["fit"])) + out.append("
    ") + out.append('
    ') + out.append("
    ") + + +def render_model(model: dict[str, Any]) -> str: + """The gallery's markup: one line per block, no indentation, "\\n" after each line.""" + gid = escape(model["id"]) + + def h(offset: int) -> str: + return f"h{min(model['headingLevel'] + offset, 6)}" + + below = 0 if model["title"] is None else 1 + out: list[str] = [] + + # The size shown before the script runs: the first panel's (only it shows without the script). + size = _strip_size(model) if model["layout"] == "strip" else model["groups"][0]["sizes"][0] + out.append( + f'
    " + ) + if model["title"] is not None: + out.append(f'<{h(0)} class="vg-title">{escape(model["title"])}') + if model["layout"] == "strip": + _strip(model, gid, h(below), out) + else: + _grid(model, gid, h(below), h(below + 1), out) + + if model["seeAll"]: + out.append( + f'

    {escape(model["seeAll"]["text"])}

    ' + ) + if model["credit"]: + out.append('

    Screenshot Gallery Powered by VisualCI.com

    ') + out.append(f'') + out.append( + f'
    <{h(below)} class="vg-box-title" id="{gid}-box-title">' + + '
    ' + + (_theme_switch() if model["themeSwitch"] else "") + + (_size_switch(["desktop", "phone"], " vg-box-sizes") if model["layout"] == "grid" else "") + + '' + + '' + + '' + + "
    " + ) + out.append('
    ') + out.append("
    ") + out.append("
    ") + return "\n".join(out) + "\n" diff --git a/clients/gallery/python/src/visualci_gallery/py.typed b/clients/gallery/python/src/visualci_gallery/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/clients/gallery/python/tests/test_gallery.py b/clients/gallery/python/tests/test_gallery.py new file mode 100644 index 00000000..835d8af2 --- /dev/null +++ b/clients/gallery/python/tests/test_gallery.py @@ -0,0 +1,115 @@ +"""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.""" + +from __future__ import annotations + +import http.server +import json +import threading +import unittest +from pathlib import Path + +from visualci_gallery import GalleryError, build_model, fetch, humanize, parse_shot, render, slugify + +CONTRACT = Path(__file__).resolve().parents[2] / "contract" +OPTION_NAMES = {"headingLevel": "heading_level", "groupOrder": "group_order", "themeSwitch": "theme_switch", "seeAll": "see_all"} + + +def read(path: Path): + return json.loads(path.read_text(encoding="utf-8")) + + +def options(raw: dict) -> dict: + return {OPTION_NAMES.get(k, k): v for k, v in raw.items()} + + +class Contract(unittest.TestCase): + def test_fixtures(self): + dirs = sorted(p for p in (CONTRACT / "fixtures").iterdir() if p.is_dir()) + self.assertTrue(dirs) + for d in dirs: + with self.subTest(fixture=d.name): + manifest = read(d / "manifest.json") + opts = options(read(d / "options.json")) + self.assertEqual(read(d / "model.json"), build_model(manifest, **opts)) + self.assertEqual((d / "gallery.html").read_text(encoding="utf-8"), render(manifest, **opts)) + + def assert_refused(self, path: Path, run): + """A refusal's message, word for word: .message beside .json.""" + with self.assertRaises(GalleryError) as e: + run() + self.assertEqual(path.with_suffix(".message").read_text(encoding="utf-8"), f"{e.exception}\n") + + def test_refuses_manifests(self): + for path in sorted((CONTRACT / "errors").glob("*.json")): + with self.subTest(error=path.name): + self.assert_refused(path, lambda: render(read(path))) + + def test_refuses_options(self): + manifest = read(CONTRACT / "fixtures" / "visualci" / "manifest.json") + for path in sorted((CONTRACT / "option-errors").glob("*.json")): + with self.subTest(error=path.name): + self.assert_refused(path, lambda: render(manifest, **options(read(path)))) + + +class Helpers(unittest.TestCase): + def test_parse_shot(self): + self.assertEqual("screenshots/app/billing", parse_shot("screenshots/app/billing/1440-dark-2x", 2880, 1800)["key"]) + self.assertEqual("phone", parse_shot("ios/usage-light", 1206, 2622)["size"]) + self.assertEqual("desktop", parse_shot("mac/proposal-light", 920, 992, "desktop")["size"]) + # A newline isn't the end of the string, and only ASCII digits are a width. + self.assertIsNone(parse_shot("a-light-1440\n", 1440, 900)["theme"]) + self.assertIsNone(parse_shot("x/١٤٤٠-light", 1440, 900)["css_width"]) + + def test_humanize_and_slugify(self): + self.assertEqual("Billing, free plan", humanize(["billing", "free_plan"])) + self.assertEqual("X", humanize(["--x--"])) + self.assertEqual("SSig", humanize(["ßig"])) + self.assertEqual("mac-approver", slugify("Mac approver")) + self.assertEqual("os", slugify("İOS")) + self.assertEqual("group", slugify("---")) + + def test_json_integers_and_bools(self): + item = {"name": "a", "url": "https://x/a.png", "width": 1440.0, "height": 900.0} + self.assertEqual(1440, build_model({"groups": [{"name": "G", "items": [item]}]})["groups"][0]["screens"][0]["variants"][0]["width"]) + with self.assertRaises(GalleryError): + build_model({"groups": [{"name": "G", "items": [{**item, "width": True}]}]}) + with self.assertRaisesRegex(GalleryError, "headingLevel"): + build_model({"groups": [{"name": "G", "items": [item]}]}, heading_level=True) + + +class Fetch(unittest.TestCase): + def serve(self, status: int, body: bytes): + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(status) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + server = http.server.HTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + return f"http://127.0.0.1:{server.server_port}/g/acme/web.json" + + def test_reads_the_manifest(self): + url = self.serve(200, b'{"groups": []}') + self.assertEqual({"groups": []}, fetch(url, attempts=1)) + + def test_raises_naming_the_url(self): + url = self.serve(503, b"") + with self.assertRaises(GalleryError) as e: + fetch(url, attempts=1) + self.assertEqual(f"The screenshots gallery couldn't read {url}: HTTP 503", str(e.exception)) + + def test_raises_on_bad_json(self): + url = self.serve(200, b"") + with self.assertRaises(GalleryError): + fetch(url, attempts=1) + + +if __name__ == "__main__": + unittest.main()