visualci-gallery 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- visualci_gallery-0.1.0/.gitignore +4 -0
- visualci_gallery-0.1.0/PKG-INFO +60 -0
- visualci_gallery-0.1.0/README.md +46 -0
- visualci_gallery-0.1.0/pyproject.toml +30 -0
- visualci_gallery-0.1.0/src/visualci_gallery/__init__.py +71 -0
- visualci_gallery-0.1.0/src/visualci_gallery/_model.py +333 -0
- visualci_gallery-0.1.0/src/visualci_gallery/_render.py +169 -0
- visualci_gallery-0.1.0/src/visualci_gallery/py.typed +0 -0
- visualci_gallery-0.1.0/src/visualci_gallery/static/visualci_gallery/visualci_gallery.css +434 -0
- visualci_gallery-0.1.0/src/visualci_gallery/static/visualci_gallery/visualci_gallery.js +1064 -0
- visualci_gallery-0.1.0/tests/test_gallery.py +115 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: visualci-gallery
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A screenshots page from VisualCI's public gallery, rendered in Python and hydrated by the visualci-gallery script.
|
|
5
|
+
Project-URL: Homepage, https://visualci.com/docs/gallery/
|
|
6
|
+
Project-URL: Source, https://github.com/DocSpring/visualci/tree/main/clients/gallery/python
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Keywords: gallery,screenshots,visualci
|
|
9
|
+
Classifier: Framework :: Django
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# visualci-gallery (Python)
|
|
16
|
+
|
|
17
|
+
A screenshots page from a VisualCI [public gallery](https://visualci.com/docs/gallery/) manifest, rendered in Python as
|
|
18
|
+
the [gallery contract](https://github.com/DocSpring/visualci/blob/main/clients/gallery/contract/SPEC.md)'s markup. The
|
|
19
|
+
markup is byte for byte what the `visualci-gallery` JS library renders, so the library's script hydrates it: tabs,
|
|
20
|
+
light and dark, desktop and phone, and the full-size view. No dependencies beyond the standard library.
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from visualci_gallery import fetch, render
|
|
24
|
+
|
|
25
|
+
manifest = fetch("https://app.visualci.com/g/acme/web.json") # raises GalleryError
|
|
26
|
+
html = render(manifest, title=None, layout="strip", theme_switch=False,
|
|
27
|
+
screens={"screenshots/templates": {"title": "Templates"}},
|
|
28
|
+
see_all={"href": "/screenshots"})
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`fetch` raises `GalleryError` when the manifest can't be read. `render` raises it when the manifest has nothing to
|
|
32
|
+
show or the options are invalid. There's no fallback: a site fetches the manifest when it builds and fails the build
|
|
33
|
+
if it can't, then renders from that copy.
|
|
34
|
+
|
|
35
|
+
## The script and stylesheet
|
|
36
|
+
|
|
37
|
+
The package carries the library's ES5 build and stylesheet in `static/visualci_gallery/`. With `visualci_gallery` in
|
|
38
|
+
Django's `INSTALLED_APPS`:
|
|
39
|
+
|
|
40
|
+
```django
|
|
41
|
+
{% load static %}
|
|
42
|
+
<link rel="stylesheet" href="{% static 'visualci_gallery/visualci_gallery.css' %}">
|
|
43
|
+
{{ gallery_html|safe }}
|
|
44
|
+
<script src="{% static 'visualci_gallery/visualci_gallery.js' %}"></script>
|
|
45
|
+
<script>document.querySelectorAll("[data-vg]").forEach(function (el) { VisualCIGallery.hydrate(el); });</script>
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Elsewhere, `visualci_gallery.static_dir()` is that folder, so you can copy it into your static files. In Jinja, mark
|
|
49
|
+
the HTML safe with `markupsafe.Markup(html)`. The stylesheet is styled through `--vg-*` CSS variables.
|
|
50
|
+
|
|
51
|
+
## Options
|
|
52
|
+
|
|
53
|
+
Keyword arguments, the contract's options in Python spelling: `title` (default "Screenshots"; `None` for no heading),
|
|
54
|
+
`heading_level`, `id`, `screens`, `order`, `groups` (such as `{"Mac approver": {"size": "desktop", "fit": "contain"}}`
|
|
55
|
+
for an app's windows), `group_order`, `credit`, `layout` (`"grid"` or `"strip"`), `theme_switch`, `see_all`.
|
|
56
|
+
|
|
57
|
+
## Development
|
|
58
|
+
|
|
59
|
+
`PYTHONPATH=src python -m unittest discover -s tests` checks the contract's golden fixtures. `bin/assets` copies the JS
|
|
60
|
+
library's build into the package before `python -m build`.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# visualci-gallery (Python)
|
|
2
|
+
|
|
3
|
+
A screenshots page from a VisualCI [public gallery](https://visualci.com/docs/gallery/) manifest, rendered in Python as
|
|
4
|
+
the [gallery contract](https://github.com/DocSpring/visualci/blob/main/clients/gallery/contract/SPEC.md)'s markup. The
|
|
5
|
+
markup is byte for byte what the `visualci-gallery` JS library renders, so the library's script hydrates it: tabs,
|
|
6
|
+
light and dark, desktop and phone, and the full-size view. No dependencies beyond the standard library.
|
|
7
|
+
|
|
8
|
+
```python
|
|
9
|
+
from visualci_gallery import fetch, render
|
|
10
|
+
|
|
11
|
+
manifest = fetch("https://app.visualci.com/g/acme/web.json") # raises GalleryError
|
|
12
|
+
html = render(manifest, title=None, layout="strip", theme_switch=False,
|
|
13
|
+
screens={"screenshots/templates": {"title": "Templates"}},
|
|
14
|
+
see_all={"href": "/screenshots"})
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`fetch` raises `GalleryError` when the manifest can't be read. `render` raises it when the manifest has nothing to
|
|
18
|
+
show or the options are invalid. There's no fallback: a site fetches the manifest when it builds and fails the build
|
|
19
|
+
if it can't, then renders from that copy.
|
|
20
|
+
|
|
21
|
+
## The script and stylesheet
|
|
22
|
+
|
|
23
|
+
The package carries the library's ES5 build and stylesheet in `static/visualci_gallery/`. With `visualci_gallery` in
|
|
24
|
+
Django's `INSTALLED_APPS`:
|
|
25
|
+
|
|
26
|
+
```django
|
|
27
|
+
{% load static %}
|
|
28
|
+
<link rel="stylesheet" href="{% static 'visualci_gallery/visualci_gallery.css' %}">
|
|
29
|
+
{{ gallery_html|safe }}
|
|
30
|
+
<script src="{% static 'visualci_gallery/visualci_gallery.js' %}"></script>
|
|
31
|
+
<script>document.querySelectorAll("[data-vg]").forEach(function (el) { VisualCIGallery.hydrate(el); });</script>
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Elsewhere, `visualci_gallery.static_dir()` is that folder, so you can copy it into your static files. In Jinja, mark
|
|
35
|
+
the HTML safe with `markupsafe.Markup(html)`. The stylesheet is styled through `--vg-*` CSS variables.
|
|
36
|
+
|
|
37
|
+
## Options
|
|
38
|
+
|
|
39
|
+
Keyword arguments, the contract's options in Python spelling: `title` (default "Screenshots"; `None` for no heading),
|
|
40
|
+
`heading_level`, `id`, `screens`, `order`, `groups` (such as `{"Mac approver": {"size": "desktop", "fit": "contain"}}`
|
|
41
|
+
for an app's windows), `group_order`, `credit`, `layout` (`"grid"` or `"strip"`), `theme_switch`, `see_all`.
|
|
42
|
+
|
|
43
|
+
## Development
|
|
44
|
+
|
|
45
|
+
`PYTHONPATH=src python -m unittest discover -s tests` checks the contract's golden fixtures. `bin/assets` copies the JS
|
|
46
|
+
library's build into the package before `python -m build`.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "visualci-gallery"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A screenshots page from VisualCI's public gallery, rendered in Python and hydrated by the visualci-gallery script."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
keywords = ["screenshots", "gallery", "visualci"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Framework :: Django",
|
|
16
|
+
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Homepage = "https://visualci.com/docs/gallery/"
|
|
21
|
+
Source = "https://github.com/DocSpring/visualci/tree/main/clients/gallery/python"
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["src/visualci_gallery"]
|
|
25
|
+
# bin/assets copies the JS library's build here; it's ignored by git but must be in the wheel.
|
|
26
|
+
artifacts = ["src/visualci_gallery/static/**"]
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.sdist]
|
|
29
|
+
include = ["src/visualci_gallery", "README.md", "tests"]
|
|
30
|
+
artifacts = ["src/visualci_gallery/static/**"]
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""visualci-gallery: a screenshots page from a VisualCI public gallery manifest, rendered in Python as the gallery
|
|
2
|
+
contract's markup, byte for byte what the visualci-gallery JS library renders, so its script hydrates it.
|
|
3
|
+
|
|
4
|
+
from visualci_gallery import fetch, render
|
|
5
|
+
|
|
6
|
+
html = render(fetch("https://app.visualci.com/g/acme/web.json"), title=None)
|
|
7
|
+
|
|
8
|
+
fetch() raises GalleryError when the manifest can't be read; render() raises it when the manifest has nothing to show
|
|
9
|
+
or the options are invalid. There is no fallback: a static site's build fails rather than ship without screenshots.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import http.client
|
|
15
|
+
import json
|
|
16
|
+
import time
|
|
17
|
+
import urllib.error
|
|
18
|
+
import urllib.request
|
|
19
|
+
from importlib.resources import files
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from ._model import GalleryError, build_model, humanize, parse_shot, slugify
|
|
23
|
+
from ._render import escape, render_model
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"GalleryError",
|
|
27
|
+
"build_model",
|
|
28
|
+
"escape",
|
|
29
|
+
"fetch",
|
|
30
|
+
"humanize",
|
|
31
|
+
"parse_shot",
|
|
32
|
+
"render",
|
|
33
|
+
"render_model",
|
|
34
|
+
"slugify",
|
|
35
|
+
"static_dir",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def fetch(url: str, *, timeout: float = 20, attempts: int = 3) -> Any:
|
|
40
|
+
"""The manifest at `url`, parsed. Raises GalleryError, naming the URL, when it can't be read (a network error, a
|
|
41
|
+
timeout, a status other than 200, JSON that doesn't parse) after `attempts` tries."""
|
|
42
|
+
attempts = max(int(attempts), 1)
|
|
43
|
+
last: Exception | None = None
|
|
44
|
+
for i in range(attempts):
|
|
45
|
+
try:
|
|
46
|
+
request = urllib.request.Request(url, headers={"Accept": "application/json"})
|
|
47
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
48
|
+
if response.status != 200:
|
|
49
|
+
raise OSError(f"HTTP {response.status}")
|
|
50
|
+
return json.loads(response.read().decode("utf-8"))
|
|
51
|
+
except urllib.error.HTTPError as e:
|
|
52
|
+
e.close()
|
|
53
|
+
last = OSError(f"HTTP {e.code}")
|
|
54
|
+
except (OSError, ValueError, http.client.HTTPException) as e:
|
|
55
|
+
last = e
|
|
56
|
+
if i + 1 < attempts:
|
|
57
|
+
time.sleep(i + 1)
|
|
58
|
+
raise GalleryError(f"The screenshots gallery couldn't read {url}: {last}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def render(manifest: Any, **options: Any) -> str:
|
|
62
|
+
"""The gallery's HTML for a parsed manifest. Options are the contract's, in Python spelling: title (None for no
|
|
63
|
+
heading), heading_level, id, screens, order, groups, group_order, credit, layout, theme_switch, see_all.
|
|
64
|
+
Raises GalleryError when the manifest or the options are invalid or nothing in the manifest can be shown."""
|
|
65
|
+
return render_model(build_model(manifest, **options))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def static_dir():
|
|
69
|
+
"""The folder with the JS library's ES5 build and stylesheet (visualci_gallery/visualci_gallery.js and .css), for
|
|
70
|
+
a site's static files. Django finds it as the app's static/ folder when visualci_gallery is in INSTALLED_APPS."""
|
|
71
|
+
return files(__package__) / "static"
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
"""The gallery's model from a VisualCI public gallery manifest (contract/SPEC.md): a line-for-line port of the JS
|
|
2
|
+
library's model.ts, so every renderer gives the same model and markup."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
import sys
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
DEFAULT_TITLE = "Screenshots"
|
|
12
|
+
SEE_ALL_TEXT = "See all screenshots"
|
|
13
|
+
SIZES = ("desktop", "phone")
|
|
14
|
+
THEMES = ("light", "dark")
|
|
15
|
+
|
|
16
|
+
# Whole-string matches (re.fullmatch), ASCII digits only and "any character" including line breaks, so every
|
|
17
|
+
# language's regex engine agrees (contract/SPEC.md, "A shot's name").
|
|
18
|
+
_EXTENSION = re.compile(r"\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\Z")
|
|
19
|
+
_WIDTH_THEME = re.compile(r"([0-9]+)-(light|dark)(-2x)?")
|
|
20
|
+
_SCREEN_THEME = re.compile(r"([\s\S]+?)-(light|dark)(?:-([0-9]+))?(-2x)?")
|
|
21
|
+
_ABSOLUTE = re.compile(r"[hH][tT][tT][pP][sS]?://[^\x00-\x20\x7f]+")
|
|
22
|
+
_CONTROL = re.compile(r"[\x00-\x20\x7f]")
|
|
23
|
+
_SCHEME = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*:")
|
|
24
|
+
_ID = re.compile(r"[A-Za-z][A-Za-z0-9_-]*")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class GalleryError(Exception):
|
|
28
|
+
"""The manifest can't be read, it or the options are invalid, or nothing in it can be shown."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _fail(message: str) -> Any:
|
|
32
|
+
raise GalleryError(message)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _integral(v: Any) -> bool:
|
|
36
|
+
"""An integer as JSON has it: Python's int (not bool), or a float with no fraction (JavaScript can't tell 1440
|
|
37
|
+
from 1440.0)."""
|
|
38
|
+
if isinstance(v, bool):
|
|
39
|
+
return False
|
|
40
|
+
if isinstance(v, int):
|
|
41
|
+
# As JavaScript reads it: one past a double's range is Infinity there, so not an integer.
|
|
42
|
+
return abs(v) <= _MAX_DOUBLE
|
|
43
|
+
return isinstance(v, float) and math.isfinite(v) and v.is_integer()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_MAX_DOUBLE = int(sys.float_info.max)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# The largest width or height (SPEC.md, "Validation"): the density maths stays exact in every language.
|
|
50
|
+
MAX_SIZE = 1_000_000
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _is_size(v: Any) -> bool:
|
|
54
|
+
return _integral(v) and 0 < v <= MAX_SIZE
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def parse_shot(name: str, width: int, height: int, size: str | None = None) -> dict[str, Any]:
|
|
58
|
+
"""How a manifest name pairs: `<screen>-<theme>[-<width>][-2x]`, or `<screen>/<width>-<theme>[-2x]`. A name in
|
|
59
|
+
neither shape is a screen of its own, in both themes. Under 768 wide is a phone; with no width, a portrait image
|
|
60
|
+
is a phone and a landscape one a desktop, unless `size` says."""
|
|
61
|
+
parts = _EXTENSION.sub("", name).split("/")
|
|
62
|
+
last = parts.pop()
|
|
63
|
+
folder = "/".join(parts)
|
|
64
|
+
|
|
65
|
+
# 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
|
|
66
|
+
# too big to matter (desktop, never scaled), and int() of a few thousand digits would raise.
|
|
67
|
+
def value(w: str) -> int | None:
|
|
68
|
+
digits = w.lstrip("0") or "0"
|
|
69
|
+
return int(digits) if len(digits) <= 18 else None
|
|
70
|
+
|
|
71
|
+
def sized(w: str | None) -> str:
|
|
72
|
+
if w is not None:
|
|
73
|
+
n = value(w)
|
|
74
|
+
return "phone" if n is not None and n < 768 else "desktop"
|
|
75
|
+
return size or ("phone" if height > width else "desktop")
|
|
76
|
+
|
|
77
|
+
def css(w: str | None) -> int | None:
|
|
78
|
+
return value(w) if w is not None else None
|
|
79
|
+
|
|
80
|
+
m = _WIDTH_THEME.fullmatch(last)
|
|
81
|
+
if m and folder:
|
|
82
|
+
return {"key": folder, "theme": m[2], "size": sized(m[1]), "x2": bool(m[3]), "css_width": css(m[1])}
|
|
83
|
+
m = _SCREEN_THEME.fullmatch(last)
|
|
84
|
+
if m:
|
|
85
|
+
key = f"{folder}/{m[1]}" if folder else m[1]
|
|
86
|
+
return {"key": key, "theme": m[2], "size": sized(m[3]), "x2": bool(m[4]), "css_width": css(m[3])}
|
|
87
|
+
key = f"{folder}/{last}" if folder else last
|
|
88
|
+
return {"key": key, "theme": None, "size": sized(None), "x2": False, "css_width": None}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def humanize(segments: list[str]) -> str:
|
|
92
|
+
"""`["billing", "free"]` → "Billing, free"."""
|
|
93
|
+
text = ", ".join(re.sub(r"[-_]+", " ", s).strip(" ") for s in segments)
|
|
94
|
+
return text[:1].upper() + text[1:]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def slugify(name: str) -> str:
|
|
98
|
+
"""A group's name as an id: ASCII lower case, runs of anything else as one hyphen."""
|
|
99
|
+
lowered = re.sub(r"[A-Z]", lambda m: m[0].lower(), name)
|
|
100
|
+
return re.sub(r"[^a-z0-9]+", "-", lowered).strip("-") or "group"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _common_folder(keys: list[str]) -> list[str]:
|
|
104
|
+
folders = [k.split("/")[:-1] for k in keys]
|
|
105
|
+
if not folders:
|
|
106
|
+
return []
|
|
107
|
+
common = folders[0]
|
|
108
|
+
for f in folders[1:]:
|
|
109
|
+
i = 0
|
|
110
|
+
while i < len(common) and i < len(f) and common[i] == f[i]:
|
|
111
|
+
i += 1
|
|
112
|
+
common = common[:i]
|
|
113
|
+
return common
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _rank_by(order: list[str] | None):
|
|
117
|
+
items = order or []
|
|
118
|
+
|
|
119
|
+
def rank(key: str) -> int:
|
|
120
|
+
return items.index(key) if key in items else len(items)
|
|
121
|
+
|
|
122
|
+
return rank
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _safe_href(value: str) -> bool:
|
|
126
|
+
if _ABSOLUTE.fullmatch(value):
|
|
127
|
+
return True
|
|
128
|
+
return value != "" and not _CONTROL.search(value) and not _SCHEME.match(value)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _opt(value: Any, check, what: str) -> Any:
|
|
132
|
+
"""An option's value, with None meaning absent."""
|
|
133
|
+
if value is None:
|
|
134
|
+
return None
|
|
135
|
+
if not check(value):
|
|
136
|
+
_fail(f"gallery option {what} is invalid")
|
|
137
|
+
return value
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _texts(keys: tuple[str, ...]):
|
|
141
|
+
def check(v: Any) -> bool:
|
|
142
|
+
return isinstance(v, dict) and all(
|
|
143
|
+
isinstance(entry, dict) and all(k in keys and (x is None or isinstance(x, str)) for k, x in entry.items())
|
|
144
|
+
for entry in v.values()
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
return check
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _group_options(v: Any) -> bool:
|
|
151
|
+
def ok(k: str, x: Any) -> bool:
|
|
152
|
+
if k == "title":
|
|
153
|
+
return x is None or isinstance(x, str)
|
|
154
|
+
if k == "size":
|
|
155
|
+
return x is None or x in SIZES
|
|
156
|
+
if k == "fit":
|
|
157
|
+
return x is None or x in ("cover", "contain")
|
|
158
|
+
return False
|
|
159
|
+
|
|
160
|
+
return isinstance(v, dict) and all(
|
|
161
|
+
isinstance(entry, dict) and all(ok(k, x) for k, x in entry.items()) for entry in v.values()
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _strings(v: Any) -> bool:
|
|
166
|
+
return isinstance(v, list) and all(isinstance(x, str) for x in v)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _check_manifest(manifest: Any) -> None:
|
|
170
|
+
"""The manifest's shape (contract/SPEC.md, "Validation"): anything else is refused."""
|
|
171
|
+
if not isinstance(manifest, dict) or not isinstance(manifest.get("groups"), list):
|
|
172
|
+
_fail("not a gallery manifest: it has no groups")
|
|
173
|
+
for i, g in enumerate(manifest["groups"]):
|
|
174
|
+
if not isinstance(g, dict) or not isinstance(g.get("name"), str) or g["name"] == "":
|
|
175
|
+
_fail(f"gallery manifest group {i} has no name")
|
|
176
|
+
if g.get("title") is not None and not isinstance(g["title"], str):
|
|
177
|
+
_fail(f"gallery manifest group {g['name']}: its title isn't a string")
|
|
178
|
+
if not isinstance(g.get("items"), list):
|
|
179
|
+
_fail(f"gallery manifest group {g['name']} has no items")
|
|
180
|
+
for j, item in enumerate(g["items"]):
|
|
181
|
+
where = f"gallery manifest group {g['name']}, item {j}"
|
|
182
|
+
if not isinstance(item, dict) or not isinstance(item.get("name"), str) or item["name"] == "":
|
|
183
|
+
_fail(f"{where} has no name")
|
|
184
|
+
if not isinstance(item.get("url"), str) or not _ABSOLUTE.fullmatch(item["url"]):
|
|
185
|
+
_fail(f"{where} ({item['name']}): its url isn't an http(s) URL")
|
|
186
|
+
if not _is_size(item.get("width")) or not _is_size(item.get("height")):
|
|
187
|
+
_fail(f"{where} ({item['name']}): its width and height aren't whole numbers from 1 to {MAX_SIZE}")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
_UNSET: Any = object()
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def build_model(
|
|
194
|
+
manifest: Any,
|
|
195
|
+
*,
|
|
196
|
+
title: Any = _UNSET,
|
|
197
|
+
heading_level: Any = None,
|
|
198
|
+
id: Any = None,
|
|
199
|
+
screens: Any = None,
|
|
200
|
+
order: Any = None,
|
|
201
|
+
groups: Any = None,
|
|
202
|
+
group_order: Any = None,
|
|
203
|
+
credit: Any = None,
|
|
204
|
+
layout: Any = None,
|
|
205
|
+
theme_switch: Any = None,
|
|
206
|
+
see_all: Any = None,
|
|
207
|
+
) -> dict[str, Any]:
|
|
208
|
+
"""The manifest as the gallery shows it (contract/SPEC.md), as a dict with the keys of the fixtures' model.json.
|
|
209
|
+
Raises GalleryError when it or the options are invalid, or nothing in it can be shown."""
|
|
210
|
+
_check_manifest(manifest)
|
|
211
|
+
level = _opt(heading_level, _integral, "headingLevel")
|
|
212
|
+
heading = min(max(int(level) if level is not None else 2, 1), 4)
|
|
213
|
+
title = DEFAULT_TITLE if title is _UNSET else _opt(title, lambda v: isinstance(v, str), "title")
|
|
214
|
+
gid = _opt(id, lambda v: isinstance(v, str) and bool(_ID.fullmatch(v)), "id") or "vg"
|
|
215
|
+
screens_opt = _opt(screens, _texts(("title", "caption")), "screens") or {}
|
|
216
|
+
groups_opt = _opt(groups, _group_options, "groups") or {}
|
|
217
|
+
order = _opt(order, _strings, "order")
|
|
218
|
+
group_order = _opt(group_order, _strings, "groupOrder")
|
|
219
|
+
credit = _opt(credit, lambda v: isinstance(v, bool), "credit")
|
|
220
|
+
credit = True if credit is None else credit
|
|
221
|
+
switch = _opt(theme_switch, lambda v: isinstance(v, bool), "themeSwitch")
|
|
222
|
+
switch = True if switch is None else switch
|
|
223
|
+
layout = _opt(layout, lambda v: v in ("grid", "strip"), "layout") or "grid"
|
|
224
|
+
see_all = _opt(
|
|
225
|
+
see_all,
|
|
226
|
+
lambda v: isinstance(v, dict)
|
|
227
|
+
and isinstance(v.get("href"), str)
|
|
228
|
+
and _safe_href(v["href"])
|
|
229
|
+
and (v.get("text") is None or isinstance(v["text"], str)),
|
|
230
|
+
"seeAll",
|
|
231
|
+
)
|
|
232
|
+
slugs: set[str] = set()
|
|
233
|
+
|
|
234
|
+
built: list[dict[str, Any]] = []
|
|
235
|
+
for g in manifest["groups"]:
|
|
236
|
+
group_set = groups_opt.get(g["name"]) or {}
|
|
237
|
+
found: dict[str, dict[str, dict[str, Any]]] = {}
|
|
238
|
+
for item in g["items"]:
|
|
239
|
+
w, h = int(item["width"]), int(item["height"])
|
|
240
|
+
shot = parse_shot(item["name"], w, h, group_set.get("size"))
|
|
241
|
+
variants = found.setdefault(shot["key"], {})
|
|
242
|
+
for theme in [shot["theme"]] if shot["theme"] else THEMES:
|
|
243
|
+
v = variants.setdefault(
|
|
244
|
+
f"{shot['size']}-{theme}",
|
|
245
|
+
{"size": shot["size"], "theme": theme, "url": "", "url2x": None, "width": 0, "height": 0},
|
|
246
|
+
)
|
|
247
|
+
if shot["x2"]:
|
|
248
|
+
if v["url2x"] is None:
|
|
249
|
+
v["url2x"] = item["url"]
|
|
250
|
+
elif v["url"] == "":
|
|
251
|
+
# An image wider than the width its name gives was taken at a higher density: shown at the
|
|
252
|
+
# name's width, its height rounded half up in integers (the same in every language).
|
|
253
|
+
cw = shot["css_width"]
|
|
254
|
+
if cw is not None and w > cw:
|
|
255
|
+
v.update(url=item["url"], width=cw, height=(2 * h * cw + w) // (2 * w))
|
|
256
|
+
else:
|
|
257
|
+
v.update(url=item["url"], width=w, height=h)
|
|
258
|
+
# The screens that have something to show; titles are made from these keys only.
|
|
259
|
+
kept = []
|
|
260
|
+
for key, variants in found.items():
|
|
261
|
+
shown = sorted(
|
|
262
|
+
(v for v in variants.values() if v["url"] != ""),
|
|
263
|
+
key=lambda v: (SIZES.index(v["size"]), THEMES.index(v["theme"])),
|
|
264
|
+
)
|
|
265
|
+
if shown:
|
|
266
|
+
kept.append((key, shown))
|
|
267
|
+
# A screen shows both themes at each of its sizes: one theme's image never stands in for the other's.
|
|
268
|
+
for key, variants in kept:
|
|
269
|
+
for v in variants:
|
|
270
|
+
if not any(o["size"] == v["size"] and o["theme"] != v["theme"] for o in variants):
|
|
271
|
+
other = "dark" if v["theme"] == "light" else "light"
|
|
272
|
+
_fail(
|
|
273
|
+
f"gallery screen {key} in group {g['name']} has a {v['theme']} {v['size']} screenshot "
|
|
274
|
+
f"but no {other} one"
|
|
275
|
+
)
|
|
276
|
+
if not kept:
|
|
277
|
+
continue
|
|
278
|
+
prefix = len(_common_folder([key for key, _ in kept]))
|
|
279
|
+
rank = _rank_by(order)
|
|
280
|
+
listed = []
|
|
281
|
+
for key, variants in kept:
|
|
282
|
+
screen = screens_opt.get(key) or {}
|
|
283
|
+
listed.append(
|
|
284
|
+
{
|
|
285
|
+
"key": key,
|
|
286
|
+
"title": screen.get("title") if screen.get("title") is not None else humanize(key.split("/")[prefix:]),
|
|
287
|
+
"caption": screen.get("caption"),
|
|
288
|
+
"variants": variants,
|
|
289
|
+
}
|
|
290
|
+
)
|
|
291
|
+
listed.sort(key=lambda sc: (rank(sc["key"]), sc["key"]))
|
|
292
|
+
|
|
293
|
+
slug = slugify(g["name"])
|
|
294
|
+
n = 2
|
|
295
|
+
while slug in slugs:
|
|
296
|
+
slug = f"{slugify(g['name'])}-{n}"
|
|
297
|
+
n += 1
|
|
298
|
+
slugs.add(slug)
|
|
299
|
+
group_title = group_set.get("title")
|
|
300
|
+
if group_title is None:
|
|
301
|
+
group_title = g.get("title") if g.get("title") is not None else g["name"]
|
|
302
|
+
built.append(
|
|
303
|
+
{
|
|
304
|
+
"name": g["name"],
|
|
305
|
+
"title": group_title,
|
|
306
|
+
"slug": slug,
|
|
307
|
+
"fit": group_set.get("fit") or "cover",
|
|
308
|
+
"sizes": [s for s in SIZES if any(v["size"] == s for sc in listed for v in sc["variants"])],
|
|
309
|
+
"screens": listed,
|
|
310
|
+
}
|
|
311
|
+
)
|
|
312
|
+
if not built:
|
|
313
|
+
_fail("the gallery manifest has no screenshots to show")
|
|
314
|
+
|
|
315
|
+
# Named groups first; the rest keep the manifest's order (the sort is stable).
|
|
316
|
+
group_rank = _rank_by(group_order)
|
|
317
|
+
built.sort(key=lambda g: group_rank(g["name"]))
|
|
318
|
+
|
|
319
|
+
return {
|
|
320
|
+
"layout": layout,
|
|
321
|
+
"themeSwitch": layout == "grid" and switch,
|
|
322
|
+
"seeAll": (
|
|
323
|
+
{"href": see_all["href"], "text": see_all["text"] if see_all.get("text") is not None else SEE_ALL_TEXT}
|
|
324
|
+
if see_all
|
|
325
|
+
else None
|
|
326
|
+
),
|
|
327
|
+
"title": title,
|
|
328
|
+
"label": title if title is not None else DEFAULT_TITLE,
|
|
329
|
+
"headingLevel": heading,
|
|
330
|
+
"id": gid,
|
|
331
|
+
"credit": credit,
|
|
332
|
+
"groups": built,
|
|
333
|
+
}
|