visualci-gallery 0.1.0__py3-none-any.whl
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/__init__.py +71 -0
- visualci_gallery/_model.py +333 -0
- visualci_gallery/_render.py +169 -0
- visualci_gallery/py.typed +0 -0
- visualci_gallery/static/visualci_gallery/visualci_gallery.css +434 -0
- visualci_gallery/static/visualci_gallery/visualci_gallery.js +1064 -0
- visualci_gallery-0.1.0.dist-info/METADATA +60 -0
- visualci_gallery-0.1.0.dist-info/RECORD +9 -0
- visualci_gallery-0.1.0.dist-info/WHEEL +4 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""The gallery's HTML from its model: the markup every renderer emits byte for byte (contract/SPEC.md, "The markup"),
|
|
2
|
+
a line-for-line port of the JS library's render.ts."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
SIZE_LABEL = {"desktop": "Desktop", "phone": "Phone"}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def escape(s: str) -> str:
|
|
12
|
+
"""& < > " ' as entities: the only escaping the contract allows, so every language's output is the same."""
|
|
13
|
+
return (
|
|
14
|
+
s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """).replace("'", "'")
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _theme_switch() -> str:
|
|
19
|
+
return (
|
|
20
|
+
'<div class="vg-seg" role="group" aria-label="Theme">'
|
|
21
|
+
'<button type="button" data-vg-set-theme="light" aria-pressed="false">Light</button>'
|
|
22
|
+
'<button type="button" data-vg-set-theme="dark" aria-pressed="false">Dark</button>'
|
|
23
|
+
"</div>"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _size_switch(sizes: list[str], extra: str = "") -> str:
|
|
28
|
+
buttons = "".join(
|
|
29
|
+
f'<button type="button" data-vg-set-size="{s}" aria-pressed="false">{SIZE_LABEL[s]}</button>' for s in sizes
|
|
30
|
+
)
|
|
31
|
+
return f'<div class="vg-seg{extra}" role="group" aria-label="Screen size">{buttons}</div>'
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _image(title: str, v: dict[str, Any], themes: list[str]) -> str:
|
|
35
|
+
alt = f"{title}, {SIZE_LABEL[v['size']].lower()}, {' and '.join(themes)}"
|
|
36
|
+
return (
|
|
37
|
+
f'<img class="vg-img" data-vg-size="{v["size"]}" data-vg-theme="{" ".join(themes)}" src="{escape(v["url"])}"'
|
|
38
|
+
+ (f' data-src-2x="{escape(v["url2x"])}"' if v["url2x"] else "")
|
|
39
|
+
+ f' width="{v["width"]}" height="{v["height"]}" alt="{escape(alt)}" loading="lazy" decoding="async">'
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _card(sc: dict[str, Any], sizes: list[str], heading: str, caption: bool, fit: str) -> str:
|
|
44
|
+
imgs: list[str] = []
|
|
45
|
+
shown: list[str] = []
|
|
46
|
+
first = None
|
|
47
|
+
for size in sizes:
|
|
48
|
+
at = [v for v in sc["variants"] if v["size"] == size]
|
|
49
|
+
if not at:
|
|
50
|
+
continue
|
|
51
|
+
shown.append(size)
|
|
52
|
+
first = first or at[0]
|
|
53
|
+
# Every size has both themes (the model refuses a screen without); the same image for both is shown once.
|
|
54
|
+
if at[0]["url"] == at[1]["url"] and at[0]["url2x"] == at[1]["url2x"]:
|
|
55
|
+
imgs.append(_image(sc["title"], at[0], ["light", "dark"]))
|
|
56
|
+
else:
|
|
57
|
+
imgs.extend(_image(sc["title"], v, [v["theme"]]) for v in at)
|
|
58
|
+
assert first is not None
|
|
59
|
+
return (
|
|
60
|
+
f'<li class="vg-card" data-vg-screen="{escape(sc["key"])}" data-vg-sizes="{" ".join(shown)}"'
|
|
61
|
+
+ (' data-vg-fit="contain"' if fit == "contain" else "")
|
|
62
|
+
+ ">"
|
|
63
|
+
+ f'<a class="vg-thumb" href="{escape(first["url"])}" data-vg-open aria-label="{escape(sc["title"])}: view full size">'
|
|
64
|
+
+ "".join(imgs)
|
|
65
|
+
+ "</a>"
|
|
66
|
+
+ f'<{heading} class="vg-card-title">{escape(sc["title"])}</{heading}>'
|
|
67
|
+
+ (f'<p class="vg-caption">{escape(sc["caption"])}</p>' if caption and sc["caption"] is not None else "")
|
|
68
|
+
+ "</li>"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _strip_size(model: dict[str, Any]) -> str:
|
|
73
|
+
"""Every screen of every group at one size (desktop when any group has it) in one row."""
|
|
74
|
+
return "desktop" if any("desktop" in g["sizes"] for g in model["groups"]) else "phone"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _grid(model: dict[str, Any], gid: str, gh: str, ch: str, out: list[str]) -> None:
|
|
78
|
+
tabs = len(model["groups"]) > 1
|
|
79
|
+
if tabs:
|
|
80
|
+
out.append(f'<div class="vg-tabs" role="tablist" aria-label="{escape(model["label"])}">')
|
|
81
|
+
for i, g in enumerate(model["groups"]):
|
|
82
|
+
out.append(
|
|
83
|
+
f'<button type="button" role="tab" id="{gid}-tab-{g["slug"]}" aria-controls="{gid}-panel-{g["slug"]}"'
|
|
84
|
+
f' aria-selected="{"true" if i == 0 else "false"}" tabindex="{0 if i == 0 else -1}">{escape(g["name"])}</button>'
|
|
85
|
+
)
|
|
86
|
+
out.append("</div>")
|
|
87
|
+
for i, g in enumerate(model["groups"]):
|
|
88
|
+
out.append(
|
|
89
|
+
f'<div class="vg-panel" id="{gid}-panel-{g["slug"]}" data-vg-sizes="{" ".join(g["sizes"])}"'
|
|
90
|
+
+ (f' role="tabpanel" aria-labelledby="{gid}-tab-{g["slug"]}"' if tabs else "")
|
|
91
|
+
+ (" hidden" if i > 0 else "")
|
|
92
|
+
+ ">"
|
|
93
|
+
)
|
|
94
|
+
controls = (_theme_switch() if model["themeSwitch"] else "") + (
|
|
95
|
+
_size_switch(g["sizes"]) if len(g["sizes"]) > 1 else ""
|
|
96
|
+
)
|
|
97
|
+
out.append(
|
|
98
|
+
f'<div class="vg-bar"><{gh} class="vg-group-title">{escape(g["title"])}</{gh}>'
|
|
99
|
+
+ (f'<div class="vg-controls">{controls}</div>' if controls else "")
|
|
100
|
+
+ "</div>"
|
|
101
|
+
)
|
|
102
|
+
out.append('<ul class="vg-grid">')
|
|
103
|
+
out.extend(_card(sc, g["sizes"], ch, True, g["fit"]) for sc in g["screens"])
|
|
104
|
+
out.append("</ul>")
|
|
105
|
+
out.append("</div>")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _strip(model: dict[str, Any], gid: str, ch: str, out: list[str]) -> None:
|
|
109
|
+
size = _strip_size(model)
|
|
110
|
+
out.append(f'<div class="vg-panel" id="{gid}-strip" data-vg-sizes="{size}">')
|
|
111
|
+
out.append(
|
|
112
|
+
'<div class="vg-strip"><button type="button" class="vg-icon vg-strip-prev" data-vg-scroll="-1" aria-label="Scroll back">‹</button>'
|
|
113
|
+
)
|
|
114
|
+
out.append('<ul class="vg-grid vg-track">')
|
|
115
|
+
for g in model["groups"]:
|
|
116
|
+
for sc in g["screens"]:
|
|
117
|
+
if any(v["size"] == size for v in sc["variants"]):
|
|
118
|
+
out.append(_card(sc, [size], ch, False, g["fit"]))
|
|
119
|
+
out.append("</ul>")
|
|
120
|
+
out.append('<button type="button" class="vg-icon vg-strip-next" data-vg-scroll="1" aria-label="Scroll forward">›</button></div>')
|
|
121
|
+
out.append("</div>")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def render_model(model: dict[str, Any]) -> str:
|
|
125
|
+
"""The gallery's markup: one line per block, no indentation, "\\n" after each line."""
|
|
126
|
+
gid = escape(model["id"])
|
|
127
|
+
|
|
128
|
+
def h(offset: int) -> str:
|
|
129
|
+
return f"h{min(model['headingLevel'] + offset, 6)}"
|
|
130
|
+
|
|
131
|
+
below = 0 if model["title"] is None else 1
|
|
132
|
+
out: list[str] = []
|
|
133
|
+
|
|
134
|
+
# The size shown before the script runs: the first panel's (only it shows without the script).
|
|
135
|
+
size = _strip_size(model) if model["layout"] == "strip" else model["groups"][0]["sizes"][0]
|
|
136
|
+
out.append(
|
|
137
|
+
f'<section class="vg" data-vg data-vg-layout="{model["layout"]}" aria-label="{escape(model["label"])}" data-vg-size="{size}"'
|
|
138
|
+
+ ("" if model["themeSwitch"] else ' data-vg-theme-source="page"')
|
|
139
|
+
+ ">"
|
|
140
|
+
)
|
|
141
|
+
if model["title"] is not None:
|
|
142
|
+
out.append(f'<{h(0)} class="vg-title">{escape(model["title"])}</{h(0)}>')
|
|
143
|
+
if model["layout"] == "strip":
|
|
144
|
+
_strip(model, gid, h(below), out)
|
|
145
|
+
else:
|
|
146
|
+
_grid(model, gid, h(below), h(below + 1), out)
|
|
147
|
+
|
|
148
|
+
if model["seeAll"]:
|
|
149
|
+
out.append(
|
|
150
|
+
f'<p class="vg-see-all"><a href="{escape(model["seeAll"]["href"])}">{escape(model["seeAll"]["text"])}</a></p>'
|
|
151
|
+
)
|
|
152
|
+
if model["credit"]:
|
|
153
|
+
out.append('<p class="vg-credit">Screenshots by <a href="https://visualci.com">VisualCI</a></p>')
|
|
154
|
+
out.append(f'<dialog class="vg-box" aria-labelledby="{gid}-box-title">')
|
|
155
|
+
out.append(
|
|
156
|
+
f'<div class="vg-box-bar"><{h(below)} class="vg-box-title" id="{gid}-box-title"></{h(below)}>'
|
|
157
|
+
+ '<div class="vg-controls">'
|
|
158
|
+
+ (_theme_switch() if model["themeSwitch"] else "")
|
|
159
|
+
+ (_size_switch(["desktop", "phone"], " vg-box-sizes") if model["layout"] == "grid" else "")
|
|
160
|
+
+ '<button type="button" class="vg-icon" data-vg-step="-1" aria-label="Previous screen">‹</button>'
|
|
161
|
+
+ '<button type="button" class="vg-icon" data-vg-step="1" aria-label="Next screen">›</button>'
|
|
162
|
+
+ "</div>"
|
|
163
|
+
+ '<button type="button" class="vg-icon" data-vg-close aria-label="Close">×</button>'
|
|
164
|
+
+ "</div>"
|
|
165
|
+
)
|
|
166
|
+
out.append('<div class="vg-box-view"></div>')
|
|
167
|
+
out.append("</dialog>")
|
|
168
|
+
out.append("</section>")
|
|
169
|
+
return "\n".join(out) + "\n"
|
|
File without changes
|