From 7fc662f84790fd10177e72ec869357859dbdcaad Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 10:37:34 +0000 Subject: [PATCH 01/11] Python gallery: screenshot() and screenshot_markdown(), and a visualci-screenshot block in the MkDocs plugin (sc-9561) --- .../python/examples/mkdocs/docs/overview.md | 9 + .../gallery/python/examples/mkdocs/mkdocs.yml | 1 + .../python/examples/tests/test_examples.py | 34 +++- .../python/src/visualci_gallery/__init__.py | 3 + .../src/visualci_gallery/_screenshot.py | 189 ++++++++++++++++++ .../src/visualci_gallery/mkdocs_plugin.py | 33 +-- clients/gallery/python/tests/test_gallery.py | 45 ++++- 7 files changed, 295 insertions(+), 19 deletions(-) create mode 100644 clients/gallery/python/examples/mkdocs/docs/overview.md create mode 100644 clients/gallery/python/src/visualci_gallery/_screenshot.py diff --git a/clients/gallery/python/examples/mkdocs/docs/overview.md b/clients/gallery/python/examples/mkdocs/docs/overview.md new file mode 100644 index 000000000..54e10cacc --- /dev/null +++ b/clients/gallery/python/examples/mkdocs/docs/overview.md @@ -0,0 +1,9 @@ +# Overview + +One screenshot, in the reader's light or dark mode, linked to the full-size original. + +```visualci-screenshot +manifest: https://app.visualci.com/g/acme/web.json +screen: overview +link: true +``` diff --git a/clients/gallery/python/examples/mkdocs/mkdocs.yml b/clients/gallery/python/examples/mkdocs/mkdocs.yml index 795bba296..bfa900e01 100644 --- a/clients/gallery/python/examples/mkdocs/mkdocs.yml +++ b/clients/gallery/python/examples/mkdocs/mkdocs.yml @@ -25,3 +25,4 @@ nav: - screenshots.md - tour.md - app.md + - overview.md diff --git a/clients/gallery/python/examples/tests/test_examples.py b/clients/gallery/python/examples/tests/test_examples.py index dbed30ccf..5ac6f59b6 100644 --- a/clients/gallery/python/examples/tests/test_examples.py +++ b/clients/gallery/python/examples/tests/test_examples.py @@ -307,6 +307,10 @@ def test_builds_the_site(self): self.assertLess(html.index(css), html.index(material)) lib = html.index(f'') self.assertLess(lib, html.index(f'')) + # The screenshot block: one screenshot's HTML in place of the fence. + shot = visualci_gallery.screenshot(MANIFEST, screen="overview", link=True).rstrip("\n") + self.assertIn(shot, self.page(out, "overview")) + self.assertNotIn("visualci-screenshot\nmanifest", self.page(out, "overview")) for name in ("visualci_gallery.js", "visualci_gallery.css"): self.assertEqual((STATIC / name).read_bytes(), (out / "assets/visualci_gallery" / name).read_bytes()) material = (out / "assets/visualci_gallery/material.css").read_text(encoding="utf-8") @@ -335,21 +339,39 @@ def test_refuses_a_bad_block(self): ("manifest: [", "the block isn't valid YAML"), ("manifest: https://app.visualci.com/g/acme/web.json\nlayout: carousel", "gallery option layout is invalid"), ("manifest: https://app.visualci.com/g/acme/web.json\nheadingLevel: 3", "unexpected keyword argument 'headingLevel'"), - ]: + ]: with self.subTest(text=text): tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) docs = Path(tmp.name) - for name in ("index.md", "screenshots.md", "tour.md", "app.md"): + for name in ("index.md", "screenshots.md", "tour.md", "app.md", "overview.md"): (docs / name).write_text("# Page\n", encoding="utf-8") (docs / "tour.md").write_text(f"# Tour\n\n```visualci-gallery\n{text}\n```\n", encoding="utf-8") self.assert_build_fails(f"visualci-gallery in tour.md: .*{re.escape(message)}", docs=docs) + def test_refuses_a_bad_screenshot_block(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + docs = Path(tmp.name) + for name in ("index.md", "screenshots.md", "app.md", "overview.md"): + (docs / name).write_text("# Page\n", encoding="utf-8") + (docs / "tour.md").write_text( + "# Tour\n\n```visualci-screenshot\nmanifest: https://app.visualci.com/g/acme/web.json\nscreen: pricing\n```\n", + encoding="utf-8", + ) + self.assert_build_fails("visualci-screenshot in tour.md: .*the gallery manifest has no screen pricing", docs=docs) + def test_blocks_inside_other_code_blocks_stay_code(self): - from visualci_gallery.mkdocs_plugin import gallery_blocks + from visualci_gallery.mkdocs_plugin import fenced_blocks - text = "````md\n```visualci-gallery\nmanifest: x\n```\n````\n\n~~~visualci-gallery\nmanifest: y\n~~~\n" - self.assertEqual([(6, 9, "", "manifest: y")], list(gallery_blocks(text))) + text = ( + "````md\n```visualci-gallery\nmanifest: x\n```\n````\n\n~~~visualci-gallery\nmanifest: y\n~~~\n\n" + "```visualci-screenshot\nmanifest: z\n```\n" + ) + self.assertEqual( + [(6, 9, "", "manifest: y", "visualci-gallery"), (10, 13, "", "manifest: z", "visualci-screenshot")], + list(fenced_blocks(text)), + ) def test_indented_blocks_and_raw_html(self): """A block in an admonition, in a list item, and inside raw HTML: each becomes the gallery, and no @@ -357,7 +379,7 @@ def test_indented_blocks_and_raw_html(self): tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) docs = Path(tmp.name) - for name in ("index.md", "screenshots.md", "app.md"): + for name in ("index.md", "screenshots.md", "app.md", "overview.md"): (docs / name).write_text("# Page\n", encoding="utf-8") block = lambda gid, pad: "\n".join( pad + line for line in ["```visualci-gallery", "manifest: https://app.visualci.com/g/acme/web.json", f"id: {gid}", "title: null", "```"] diff --git a/clients/gallery/python/src/visualci_gallery/__init__.py b/clients/gallery/python/src/visualci_gallery/__init__.py index f394e20b3..9191bafcb 100644 --- a/clients/gallery/python/src/visualci_gallery/__init__.py +++ b/clients/gallery/python/src/visualci_gallery/__init__.py @@ -21,6 +21,7 @@ from ._model import TEXT_DEFAULTS, GalleryError, build_model, humanize, parse_shot, slugify from ._render import escape, render_model +from ._screenshot import screenshot, screenshot_markdown __all__ = [ "TEXT_DEFAULTS", @@ -32,6 +33,8 @@ "parse_shot", "render", "render_model", + "screenshot", + "screenshot_markdown", "slugify", "static_dir", ] diff --git a/clients/gallery/python/src/visualci_gallery/_screenshot.py b/clients/gallery/python/src/visualci_gallery/_screenshot.py new file mode 100644 index 000000000..92cbd41aa --- /dev/null +++ b/clients/gallery/python/src/visualci_gallery/_screenshot.py @@ -0,0 +1,189 @@ +"""One screenshot from the gallery's manifest, for a page or a README: an , or a that shows the dark shot +when the reader's setting is dark (contract/SPEC.md, "A single screenshot"). A port of the JS library's screenshot.ts. +""" + +from __future__ import annotations + +import re +from typing import Any + +from ._model import ( + _EXTENSION, + _check_manifest, + _fail, + _is_dimensions, + _opt, + _resolve_dimensions, + build_model, + parse_shot, +) +from ._render import escape + +_SPACES = re.compile(r"[\t\n\r ]+") +_PUNCTUATION = re.compile(r"[!-/:-@\[-`{-~]") +_URL_SPECIAL = re.compile(r"[\\()&]") + + +def _given(v: Any) -> bool: + return v is not None + + +def _check(value: Any, key: str, ok) -> None: + if _given(value) and not ok(value): + _fail(f"screenshot option {key} is invalid") + + +def _screen_items(group: dict[str, Any], screen: str, dims: list[dict[str, Any]]) -> list[dict[str, Any]]: + """The screen's items in its group. When every one is a 2x shot, a 1x copy of each follows them: the 2x shots at + half their size. Otherwise the screen is the gallery's, 2x shots only as 2x copies.""" + items = [item for item in group["items"] if parse_shot(item["name"], dims)["key"] == screen] + if not all(parse_shot(item["name"], dims)["x2"] for item in items): + return items + halves = [] + for item in items: + width = (item["width"] + 1) // 2 + height = (2 * item["height"] * width + item["width"]) // (2 * item["width"]) + name = re.sub(r"-2x$", "", _EXTENSION.sub("", item["name"])) + halves.append({"name": name, "url": item["url"], "width": width, "height": height, "thumb": item.get("thumb")}) + return items + halves + + +def _pick(v: dict[str, Any], thumb: bool) -> dict[str, Any]: + if thumb: + t = v["thumb"] + return {"src": t["url"], "src2x": None, "width": t["width"], "height": t["height"]} + src2x = v["url2x"] if v["url2x"] is not None and v["url2x"] != v["url"] else None + return {"src": v["url"], "src2x": src2x, "width": v["width"], "height": v["height"]} + + +def _shown(manifest: Any, options: dict[str, Any]) -> dict[str, Any]: + _check_manifest(manifest) + dims = _resolve_dimensions(_opt(options.get("dimensions"), _is_dimensions, "dimensions")) + + def keys(dim: str) -> list[str]: + return [v["key"] for v in next(d for d in dims if d["key"] == dim)["values"]] + + screen = options.get("screen") + if not isinstance(screen, str) or screen == "": + _fail("screenshot option screen is required") + _check(options.get("group"), "group", lambda v: isinstance(v, str)) + _check(options.get("theme"), "theme", lambda v: isinstance(v, str) and v in keys("theme")) + _check(options.get("size"), "size", lambda v: isinstance(v, str) and v in keys("size")) + _check(options.get("alt"), "alt", lambda v: isinstance(v, str)) + _check(options.get("link"), "link", lambda v: isinstance(v, bool)) + _check(options.get("thumb"), "thumb", lambda v: isinstance(v, bool)) + _check(options.get("loading"), "loading", lambda v: v in ("lazy", "eager")) + + def has(g: dict[str, Any]) -> bool: + return any(parse_shot(item["name"], dims)["key"] == screen for item in g["items"]) + + if _given(options.get("group")): + group = next((g for g in manifest["groups"] if g["name"] == options["group"]), None) + if group is None: + _fail(f"the gallery manifest has no group {options['group']}") + if not has(group): + _fail(f"gallery group {group['name']} has no screen {screen}") + else: + group = next((g for g in manifest["groups"] if has(g)), None) + if group is None: + _fail(f"the gallery manifest has no screen {screen}") + model = build_model( + {"groups": [{"name": group["name"], "title": group.get("title"), "items": _screen_items(group, screen, dims)}]}, + dimensions=options.get("dimensions"), + groups=options.get("groups"), + ) + sc = model["groups"][0]["screens"][0] + order = [d["key"] for d in model["dimensions"]] + # The values shown: each dimension's option, else the first value of the screen's first variant that has the values + # chosen so far. + choice: dict[str, str] = {} + for k in order: + asked = options.get(k) if k in ("theme", "size") else None + if _given(asked): + choice[k] = asked + continue + fits = next((v for v in sc["variants"] if all(v["values"][c] == x for c, x in choice.items())), None) + choice[k] = (fits or sc["variants"][0])["values"][k] + + def find(c: dict[str, str]) -> dict[str, Any] | None: + return next((v for v in sc["variants"] if all(v["values"][k] == c[k] for k in order)), None) + + v = find(choice) + if v is None: + _fail(f"gallery screen {screen} in group {group['name']} has no {' '.join(choice[k] for k in order)} screenshot") + # The dark shot, for readers whose setting is dark, when no theme was asked for; not when it's the same image. + found = None + if not _given(options.get("theme")) and choice["theme"] != "dark": + found = find({k: "dark" if k == "theme" else choice[k] for k in order}) + dv = found if found is not None and (found["url"] != v["url"] or found["url2x"] != v["url2x"]) else None + # The small copies only when every image shown has one, so light and dark readers see the same size. + thumb = options.get("thumb") is True and v["thumb"] is not None and (dv is None or dv["thumb"] is not None) + alt = options["alt"] if _given(options.get("alt")) else sc["title"] + alt = _SPACES.sub(" ", alt) + alt = alt[1:] if alt.startswith(" ") else alt + alt = alt[:-1] if alt.endswith(" ") else alt + return { + "light": _pick(v, thumb), + "dark": _pick(dv, thumb) if dv is not None else None, + "href": v["url"], + "link": options.get("link") is True, + "alt": alt, + "loading": options.get("loading") or "lazy", + } + + +def _srcset(p: dict[str, Any]) -> str: + if p["src2x"] is None: + return escape(p["src"]) + return f"{escape(p['src'])}, {escape(p['src2x'])} 2x" + + +def _picture_html(s: dict[str, Any]) -> str: + light = s["light"] + img = ( + f'{escape(s[' + ) + open_a = f'' if s["link"] else "" + close_a = "" if s["link"] else "" + dark = s["dark"] + if dark is None: + return f"{open_a}{img}{close_a}\n" + source = ( + f'' + ) + return "\n".join([f"{open_a}", source, img, f"{close_a}"]) + "\n" + + +def screenshot(manifest: Any, **options: Any) -> str: + """One screenshot as HTML: an , or a with the dark shot for readers whose setting is dark. Options: + screen (its key, required), group, theme, size, alt, link, thumb, loading, and the gallery's dimensions and groups. + Raises GalleryError when the manifest or the options are invalid, or the screen has no shot for what's asked.""" + return _picture_html(_shown(manifest, _options(options))) + + +def screenshot_markdown(manifest: Any, **options: Any) -> str: + """One screenshot for a README: Markdown's ![alt](url), linked with link=True, or the HTML when it has a + dark shot. The same options as screenshot().""" + s = _shown(manifest, _options(options)) + if s["dark"] is not None: + return _picture_html(s) + image = f"![{_PUNCTUATION.sub(lambda m: chr(92) + m.group(0), s['alt'])}]({_markdown_url(s['light']['src'])})" + return (f"[{image}]({_markdown_url(s['href'])})" if s["link"] else image) + "\n" + + +def _markdown_url(url: str) -> str: + return _URL_SPECIAL.sub(lambda m: "\\" + m.group(0), url) + + +_NAMES = ("screen", "group", "theme", "size", "alt", "link", "thumb", "loading", "dimensions", "groups") + + +def _options(options: dict[str, Any]) -> dict[str, Any]: + for k in options: + if k not in _NAMES: + raise TypeError(f"screenshot() got an unexpected keyword argument '{k}'") + return options diff --git a/clients/gallery/python/src/visualci_gallery/mkdocs_plugin.py b/clients/gallery/python/src/visualci_gallery/mkdocs_plugin.py index bed6208ce..1cd90b6bd 100644 --- a/clients/gallery/python/src/visualci_gallery/mkdocs_plugin.py +++ b/clients/gallery/python/src/visualci_gallery/mkdocs_plugin.py @@ -1,4 +1,5 @@ -"""The MkDocs plugin: a ```visualci-gallery fenced block in any page becomes the gallery, rendered when the site builds. +"""The MkDocs plugin: a ```visualci-gallery fenced block in any page becomes the gallery, rendered when the site builds, +and a ```visualci-screenshot block one screenshot. # mkdocs.yml plugins: @@ -19,6 +20,9 @@ the gallery's sizes scaled to Material's text, and a small script that hydrates each gallery, again after Material's instant navigation. With theme_switch: false a gallery follows Material's palette toggle. +A ```visualci-screenshot block is YAML too: `manifest`, then screenshot()'s options (screen, group, theme, size, alt, +link, thumb, loading, dimensions, groups): an , or a that shows the dark shot to dark readers. + Plugin options: `timeout` (seconds for each try, default 20) and `attempts` (default 3). """ @@ -35,7 +39,7 @@ from mkdocs.plugins import BasePlugin from mkdocs.structure.files import File, Files -from . import GalleryError, fetch, render, static_dir +from . import GalleryError, fetch, render, screenshot, static_dir ASSETS = "assets/visualci_gallery" FENCE = re.compile(r"^([ \t]*)(`{3,}|~{3,})\s*([^\s`]*)[^`]*$") @@ -93,9 +97,14 @@ class GalleryConfig(Config): attempts = config_options.Type(int, default=3) -def gallery_blocks(markdown: str): - """Each ```visualci-gallery block outside other code blocks, at any indent (inside an admonition, a content tab or - a list item): (start line, end line after it, its indent, its YAML text without that indent).""" +# A block's info string, and what turns its options into HTML. +KINDS = {"visualci-gallery": render, "visualci-screenshot": screenshot} + + +def fenced_blocks(markdown: str): + """Each ```visualci-gallery or ```visualci-screenshot block outside other code blocks, at any indent (inside an + admonition, a content tab or a list item): (start line, end line after it, its indent, its YAML text without that + indent, its kind).""" lines = markdown.split("\n") i = 0 while i < len(lines): @@ -108,9 +117,9 @@ def gallery_blocks(markdown: str): end = i + 1 while end < len(lines) and not closing.match(lines[end]): end += 1 - if info == "visualci-gallery": + if info in KINDS: body = [line[len(indent) :] if line.startswith(indent) else line.lstrip() for line in lines[i + 1 : end]] - yield i, min(end + 1, len(lines)), indent, "\n".join(body) + yield i, min(end + 1, len(lines)), indent, "\n".join(body), info i = end + 1 @@ -146,23 +155,23 @@ def _manifest(self, url: str) -> Any: return self._manifests[url] def on_page_markdown(self, markdown: str, page, **kwargs): - blocks = list(gallery_blocks(markdown)) + blocks = list(fenced_blocks(markdown)) if not blocks: return markdown lines = markdown.split("\n") where = page.file.src_uri tokens = self._pages.setdefault(where, []) - for start, end, indent, text in reversed(blocks): + for start, end, indent, text, kind in reversed(blocks): try: options = yaml.safe_load(text) or {} if not isinstance(options, dict) or not isinstance(options.get("manifest"), str): raise GalleryError("the block needs manifest: ") url = options.pop("manifest") - html = render(self._manifest(url), **options) + html = KINDS[kind](self._manifest(url), **options) except yaml.YAMLError as e: - raise PluginError(f"visualci-gallery in {where}: the block isn't valid YAML: {e}") from e + raise PluginError(f"{kind} in {where}: the block isn't valid YAML: {e}") from e except (GalleryError, TypeError) as e: - raise PluginError(f"visualci-gallery in {where}: {e}") from e + raise PluginError(f"{kind} in {where}: {e}") from e # A token Markdown leaves alone, swapped for the HTML once the page is HTML (on_page_content). token = f"VISUALCIGALLERY{secrets.token_hex(8)}" self._html[token] = html diff --git a/clients/gallery/python/tests/test_gallery.py b/clients/gallery/python/tests/test_gallery.py index 41a6589a9..acfbf91d4 100644 --- a/clients/gallery/python/tests/test_gallery.py +++ b/clients/gallery/python/tests/test_gallery.py @@ -9,7 +9,17 @@ import unittest from pathlib import Path -from visualci_gallery import GalleryError, build_model, fetch, humanize, parse_shot, render, slugify +from visualci_gallery import ( + GalleryError, + build_model, + fetch, + humanize, + parse_shot, + render, + screenshot, + screenshot_markdown, + slugify, +) CONTRACT = Path(__file__).resolve().parents[2] / "contract" OPTION_NAMES = { @@ -58,6 +68,39 @@ def test_refuses_options(self): self.assert_refused(path, lambda: render(manifest, **options(read(path)))) + +class Screenshots(unittest.TestCase): + """contract/screenshots: each case's exact HTML and Markdown, and each refusal's message. Options that aren't an + object (options-*.json) can't be keyword arguments, so they don't apply here.""" + + dir = CONTRACT / "screenshots" + + def test_cases(self): + manifest = read(self.dir / "manifest.json") + paths = sorted((self.dir / "cases").glob("*.json")) + self.assertTrue(paths) + for path in paths: + with self.subTest(case=path.stem): + opts = read(path) + self.assertEqual(path.with_suffix(".html").read_text(encoding="utf-8"), screenshot(manifest, **opts)) + self.assertEqual(path.with_suffix(".md").read_text(encoding="utf-8"), screenshot_markdown(manifest, **opts)) + + def test_refusals(self): + manifest = read(self.dir / "manifest.json") + for path in sorted((self.dir / "errors").glob("*.json")): + opts = read(path) + if not isinstance(opts, dict): + continue + with self.subTest(error=path.name): + for run in (screenshot, screenshot_markdown): + with self.assertRaises(GalleryError) as e: + run(manifest, **opts) + self.assertEqual(path.with_suffix(".message").read_text(encoding="utf-8"), f"{e.exception}\n") + + def test_unknown_option(self): + with self.assertRaises(TypeError): + screenshot(read(self.dir / "manifest.json"), screen="overview", heading_level=2) + class Helpers(unittest.TestCase): def test_parse_shot(self): def shot(key, values, x2=False, css_width=None): From 11e92e27069142ebe7c5349121927b282d853cdf Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 10:38:47 +0000 Subject: [PATCH 02/11] Ruby gallery: screenshot and screenshot_markdown, and a visualci_screenshot view helper (sc-9561) --- clients/gallery/ruby/lib/visualci/gallery.rb | 1 + .../ruby/lib/visualci/gallery/engine.rb | 8 +- .../ruby/lib/visualci/gallery/screenshot.rb | 145 ++++++++++++++++++ clients/gallery/ruby/test/gallery_test.rb | 41 +++++ 4 files changed, 194 insertions(+), 1 deletion(-) create mode 100644 clients/gallery/ruby/lib/visualci/gallery/screenshot.rb diff --git a/clients/gallery/ruby/lib/visualci/gallery.rb b/clients/gallery/ruby/lib/visualci/gallery.rb index 891bf911e..372603d30 100644 --- a/clients/gallery/ruby/lib/visualci/gallery.rb +++ b/clients/gallery/ruby/lib/visualci/gallery.rb @@ -571,4 +571,5 @@ def safe_href?(value) end require_relative 'gallery/renderer' +require_relative 'gallery/screenshot' require_relative 'gallery/engine' if defined?(Rails::Engine) diff --git a/clients/gallery/ruby/lib/visualci/gallery/engine.rb b/clients/gallery/ruby/lib/visualci/gallery/engine.rb index 567a4c720..2a4e14ee5 100644 --- a/clients/gallery/ruby/lib/visualci/gallery/engine.rb +++ b/clients/gallery/ruby/lib/visualci/gallery/engine.rb @@ -2,11 +2,17 @@ module VisualCI module Gallery - # In a view: `<%= visualci_gallery(manifest, title: nil, screens: SCREENS) %>`. + # In a view: `<%= visualci_gallery(manifest, title: nil, screens: SCREENS) %>`, or one screenshot with + # `visualci_screenshot`. module Helper def visualci_gallery(manifest, **options) Gallery.render(manifest, **options).html_safe # rubocop:disable Rails/OutputSafety -- escaped by the renderer end + + # `<%= visualci_screenshot(manifest, screen: 'overview', link: true) %>`: one screenshot. + def visualci_screenshot(manifest, **options) + Gallery.screenshot(manifest, **options).html_safe # rubocop:disable Rails/OutputSafety -- escaped by the renderer + end end # Adds the helper to every view and serves app/assets (visualci_gallery.js and visualci_gallery.css, the JS diff --git a/clients/gallery/ruby/lib/visualci/gallery/screenshot.rb b/clients/gallery/ruby/lib/visualci/gallery/screenshot.rb new file mode 100644 index 000000000..3988cd612 --- /dev/null +++ b/clients/gallery/ruby/lib/visualci/gallery/screenshot.rb @@ -0,0 +1,145 @@ +# frozen_string_literal: true + +module VisualCI + # One screenshot from the gallery's manifest, for a page or a README: an , or a that shows the dark + # shot when the reader's setting is dark (SPEC.md, "A single screenshot"). A port of the JS library's screenshot.ts. + # + # VisualCI::Gallery.screenshot(manifest, screen: 'overview', link: true) + # VisualCI::Gallery.screenshot_markdown(manifest, screen: 'overview') + module Gallery + SPACES = /[\t\n\r ]+/ + PUNCTUATION = /[!-\/:-@\[-`{-~]/ + URL_SPECIAL = /[\\()&]/ + + module_function + + # One screenshot as HTML: an , or a with the dark shot for readers whose setting is dark. Options: + # screen (its key, required), group, theme, size, alt, link, thumb, loading, and the gallery's dimensions and + # groups. Raises Error when the manifest or the options are invalid, or the screen has no shot for what's asked. + def screenshot(manifest, **options) + picture_html(shown(manifest, **options)) + end + + # One screenshot for a README: Markdown's ![alt](url), linked with link: true, or the HTML when it has a + # dark shot. The same options as screenshot. + def screenshot_markdown(manifest, **options) + s = shown(manifest, **options) + return picture_html(s) if s[:dark] + + alt = s[:alt].gsub(PUNCTUATION) { |c| "\\#{c}" } + image = "![#{alt}](#{markdown_url(s[:light][:src])})" + "#{s[:link] ? "[#{image}](#{markdown_url(s[:href])})" : image}\n" + end + + def markdown_url(url) = url.gsub(URL_SPECIAL) { |c| "\\#{c}" } + + def shot_option(value, name) + return nil if value.nil? + raise Error, "screenshot option #{name} is invalid" unless yield(value) + + value + end + + # The screen's items in its group. When every one is a 2x shot, a 1x copy of each follows them: the 2x shots at + # half their size. Otherwise the screen is the gallery's, 2x shots only as 2x copies. + def screen_items(group, screen, dims) + items = group['items'].select { |item| parse_shot(item['name'], dims)[:key] == screen } + return items unless items.all? { |item| parse_shot(item['name'], dims)[:x2] } + + items + items.map do |item| + width = (item['width'] + 1) / 2 + height = ((2 * item['height'] * width) + item['width']) / (2 * item['width']) + { 'name' => item['name'].sub(EXTENSION, '').sub(/-2x\z/, ''), 'url' => item['url'], 'width' => width, + 'height' => height, 'thumb' => item['thumb'] } + end + end + + def pick(variant, thumb) + if thumb + t = variant['thumb'] + return { src: t['url'], src2x: nil, width: t['width'], height: t['height'] } + end + src2x = variant['url2x'] unless variant['url2x'].nil? || variant['url2x'] == variant['url'] + { src: variant['url'], src2x: src2x, width: variant['width'], height: variant['height'] } + end + + def shown(manifest, screen: nil, group: nil, theme: nil, size: nil, alt: nil, link: nil, thumb: nil, loading: nil, + dimensions: nil, groups: nil) + check_manifest(manifest) + given = opt(dimensions, 'dimensions') { |v| dimensions?(v) } + dims = resolve_dimensions(given && given.map { |d| dimension_entry(d) }) + keys = ->(dim) { dims.find { |d| d['key'] == dim }['values'].map { |v| v['key'] } } + raise Error, 'screenshot option screen is required' unless screen.is_a?(String) && !screen.empty? + + theme = theme.to_s if theme.is_a?(Symbol) + size = size.to_s if size.is_a?(Symbol) + loading = loading.to_s if loading.is_a?(Symbol) + shot_option(group, 'group') { |v| v.is_a?(String) } + shot_option(theme, 'theme') { |v| v.is_a?(String) && keys.call('theme').include?(v) } + shot_option(size, 'size') { |v| v.is_a?(String) && keys.call('size').include?(v) } + shot_option(alt, 'alt') { |v| v.is_a?(String) } + shot_option(link, 'link') { |v| boolean?(v) } + shot_option(thumb, 'thumb') { |v| boolean?(v) } + shot_option(loading, 'loading') { |v| %w[lazy eager].include?(v) } + has = ->(g) { g['items'].any? { |item| parse_shot(item['name'], dims)[:key] == screen } } + if group.nil? + found_group = manifest['groups'].find { |g| has.call(g) } + raise Error, "the gallery manifest has no screen #{screen}" unless found_group + else + found_group = manifest['groups'].find { |g| g['name'] == group } + raise Error, "the gallery manifest has no group #{group}" unless found_group + raise Error, "gallery group #{group} has no screen #{screen}" unless has.call(found_group) + end + one = { 'groups' => [{ 'name' => found_group['name'], 'title' => found_group['title'], + 'items' => screen_items(found_group, screen, dims) }] } + m = model(one, dimensions: dimensions, groups: groups) + sc = m['groups'][0]['screens'][0] + order = m['dimensions'].map { |d| d['key'] } + # The values shown: each dimension's option, else the first value of the screen's first variant that has the + # values chosen so far. + asked = { 'theme' => theme, 'size' => size } + choice = {} + order.each do |k| + if asked[k] + choice[k] = asked[k] + next + end + fits = sc['variants'].find { |v| choice.all? { |c, x| v['values'][c] == x } } + choice[k] = (fits || sc['variants'][0])['values'][k] + end + find = ->(c) { sc['variants'].find { |v| order.all? { |k| v['values'][k] == c[k] } } } + v = find.call(choice) + unless v + raise Error, "gallery screen #{screen} in group #{found_group['name']} has no " \ + "#{order.map { |k| choice[k] }.join(' ')} screenshot" + end + # The dark shot, for readers whose setting is dark, when no theme was asked for; not when it's the same image. + found = (find.call(order.to_h { |k| [k, k == 'theme' ? 'dark' : choice[k]] }) if theme.nil? && choice['theme'] != 'dark') + dv = found if found && (found['url'] != v['url'] || found['url2x'] != v['url2x']) + # The small copies only when every image shown has one, so light and dark readers see the same size. + use_thumb = thumb == true && !v['thumb'].nil? && (dv.nil? || !dv['thumb'].nil?) + text = (alt.nil? ? sc['title'] : alt).gsub(SPACES, ' ').delete_prefix(' ').delete_suffix(' ') + { light: pick(v, use_thumb), dark: dv && pick(dv, use_thumb), href: v['url'], link: link == true, alt: text, + loading: loading || 'lazy' } + end + + def srcset(pick) + pick[:src2x].nil? ? escape(pick[:src]) : "#{escape(pick[:src])}, #{escape(pick[:src2x])} 2x" + end + + def picture_html(s) + light = s[:light] + img = "\"#{escape(s[:alt])}\"" + open = s[:link] ? "" : '' + close = s[:link] ? '' : '' + dark = s[:dark] + return "#{open}#{img}#{close}\n" unless dark + + source = "" + "#{["#{open}", source, img, "#{close}"].join("\n")}\n" + end + end +end diff --git a/clients/gallery/ruby/test/gallery_test.rb b/clients/gallery/ruby/test/gallery_test.rb index 8392d7063..f963eb90e 100644 --- a/clients/gallery/ruby/test/gallery_test.rb +++ b/clients/gallery/ruby/test/gallery_test.rb @@ -52,6 +52,47 @@ def test_has_fixtures end end +# contract/screenshots: each case's exact HTML and Markdown, and each refusal's message. Options that aren't an +# object (options-*.json) can't be keyword arguments, so they don't apply here. +class GalleryScreenshotTest < Minitest::Test + DIR = File.expand_path('../../contract/screenshots', __dir__) + + def read(path) = JSON.parse(File.read(path, encoding: 'UTF-8')) + def manifest = read(File.join(DIR, 'manifest.json')) + def self.options(json) = json.to_h { |k, v| [k.to_sym, v] } + + Dir[File.join(DIR, 'cases', '*.json')].each do |path| + name = File.basename(path, '.json') + define_method("test_case_#{name}") do + options = self.class.options(read(path)) + assert_equal File.read(path.sub(/\.json\z/, '.html'), encoding: 'UTF-8'), VisualCI::Gallery.screenshot(manifest, **options) + assert_equal File.read(path.sub(/\.json\z/, '.md'), encoding: 'UTF-8'), + VisualCI::Gallery.screenshot_markdown(manifest, **options) + end + end + + Dir[File.join(DIR, 'errors', '*.json')].each do |path| + define_method("test_refuses_#{File.basename(path, '.json')}") do + json = read(path) + next unless json.is_a?(Hash) + + %i[screenshot screenshot_markdown].each do |method| + error = assert_raises(VisualCI::Gallery::Error) { VisualCI::Gallery.public_send(method, manifest, **self.class.options(json)) } + assert_equal File.read(path.sub(/\.json\z/, '.message'), encoding: 'UTF-8'), "#{error.message}\n" + end + end + end + + def test_has_cases + refute_empty Dir[File.join(DIR, 'cases', '*.json')] + end + + def test_symbol_values + assert_equal VisualCI::Gallery.screenshot(manifest, screen: 'overview', theme: 'dark', loading: 'eager'), + VisualCI::Gallery.screenshot(manifest, screen: 'overview', theme: :dark, loading: :eager) + end +end + # Ruby spellings: symbol keys work as well as strings. class GalleryOptionsTest < Minitest::Test MANIFEST = JSON.parse(File.read(File.expand_path('../../contract/fixtures/fleetlayer/manifest.json', __dir__), encoding: 'UTF-8')) From 8d7fbdc6712a2ee37fdb023c010bf762ffd7eadd Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 10:40:17 +0000 Subject: [PATCH 03/11] Rust gallery: screenshot() and screenshot_markdown() with ScreenshotOptions (sc-9561) --- clients/gallery/rust/src/lib.rs | 2 + clients/gallery/rust/src/model.rs | 14 +- clients/gallery/rust/src/screenshot.rs | 331 +++++++++++++++++++++++++ clients/gallery/rust/tests/contract.rs | 41 ++- 4 files changed, 380 insertions(+), 8 deletions(-) create mode 100644 clients/gallery/rust/src/screenshot.rs diff --git a/clients/gallery/rust/src/lib.rs b/clients/gallery/rust/src/lib.rs index 6847eb9b7..8528217ab 100644 --- a/clients/gallery/rust/src/lib.rs +++ b/clients/gallery/rust/src/lib.rs @@ -21,6 +21,7 @@ mod model; mod render; +mod screenshot; use std::fmt; @@ -30,6 +31,7 @@ pub use model::{ slugify, }; pub use render::{escape, render_model}; +pub use screenshot::{ScreenshotOptions, screenshot, screenshot_markdown}; /// Why a gallery can't be shown. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/clients/gallery/rust/src/model.rs b/clients/gallery/rust/src/model.rs index 13523817c..1c8b4aeac 100644 --- a/clients/gallery/rust/src/model.rs +++ b/clients/gallery/rust/src/model.rs @@ -26,7 +26,7 @@ pub const SEE_ALL_TEXT: &str = "See all screenshots"; // Whole-string matches (\A…\z), ASCII digits only and "any character" including line breaks, so every language's // regex engine agrees (contract/SPEC.md, "A shot's name"). -static EXTENSION: LazyLock = +pub(crate) static EXTENSION: LazyLock = LazyLock::new(|| Regex::new(r"\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\z").unwrap()); static KEY: LazyLock = LazyLock::new(|| Regex::new(r"\A[a-z0-9]+(-[a-z0-9]+)*\z").unwrap()); static ABSOLUTE: LazyLock = @@ -497,7 +497,7 @@ fn preload_model(v: Option<&Value>) -> Option { } /// The manifest's shape (contract/SPEC.md, "Validation"): anything else is refused. -fn check_manifest(manifest: &Value) -> Result<(), Error> { +pub(crate) fn check_manifest(manifest: &Value) -> Result<(), Error> { let Some(groups) = manifest.get("groups").filter(|_| manifest.is_object()).and_then(Value::as_array) else { return fail("not a gallery manifest: it has no groups"); }; @@ -541,7 +541,7 @@ fn check_manifest(manifest: &Value) -> Result<(), Error> { /// ones. Build them with [`Options::default`] and the setters, or [`Options::from_json`]. #[derive(Debug, Clone, Default)] pub struct Options { - raw: Map, + pub(crate) raw: Map, } impl Options { @@ -552,7 +552,7 @@ impl Options { _ => fail("gallery options must be an object"), } } - fn set(mut self, key: &str, value: Value) -> Self { + pub(crate) fn set(mut self, key: &str, value: Value) -> Self { self.raw.insert(key.to_string(), value); self } @@ -660,7 +660,7 @@ impl Options { } /// An option's value, with null meaning absent; `check` false is an error. - fn get(&self, key: &str, check: impl Fn(&Value) -> bool) -> Result, Error> { + pub(crate) fn get(&self, key: &str, check: impl Fn(&Value) -> bool) -> Result, Error> { match self.raw.get(key) { None | Some(Value::Null) => Ok(None), Some(v) if check(v) => Ok(Some(v)), @@ -705,7 +705,7 @@ fn text_or_null(v: Option<&Value>) -> bool { } /// The `dimensions` option's shape (contract/SPEC.md, "Validation"). -fn check_dimensions(list: &Value) -> bool { +pub(crate) fn check_dimensions(list: &Value) -> bool { let Some(list) = list.as_array() else { return false }; let mut keys: HashSet<&str> = HashSet::new(); let mut value_keys: HashSet = HashSet::new(); @@ -779,7 +779,7 @@ fn check_dimensions(list: &Value) -> bool { } /// The built-in dimensions with the option's changes, then the option's own (already checked). -fn resolve_dimensions(list: Option<&Value>) -> Vec { +pub(crate) fn resolve_dimensions(list: Option<&Value>) -> Vec { let given: &[Value] = list.and_then(Value::as_array).map_or(&[], Vec::as_slice); let resolve = |d: &Value, base: Option<&Dimension>| -> Dimension { let key = d["key"].as_str().unwrap().to_string(); diff --git a/clients/gallery/rust/src/screenshot.rs b/clients/gallery/rust/src/screenshot.rs new file mode 100644 index 000000000..def6da1dd --- /dev/null +++ b/clients/gallery/rust/src/screenshot.rs @@ -0,0 +1,331 @@ +//! One screenshot from the gallery's manifest, for a page or a README: an ``, or a `` that shows the +//! dark shot when the reader's setting is dark (contract/SPEC.md, "A single screenshot"). A port of the JS library's +//! screenshot.ts. + +use serde_json::{Map, Value, json}; + +use crate::Error; +use crate::model::{ + EXTENSION, Options, Variant, build_model, check_dimensions, check_manifest, parse_shot, resolve_dimensions, +}; +use crate::render::escape; + +/// What [`screenshot`] and [`screenshot_markdown`] show, as JSON-shaped values like the gallery's [`Options`]. Build +/// them with [`ScreenshotOptions::new`] and the setters, or [`ScreenshotOptions::from_json`]. +#[derive(Debug, Clone, Default)] +pub struct ScreenshotOptions { + raw: Map, +} + +impl ScreenshotOptions { + /// The screen, by its key (`overview`, `ios/sessions`), as the gallery's `screens` and `order` name it. + pub fn new(screen: &str) -> Self { + ScreenshotOptions::default().set("screen", screen.into()) + } + /// Options from a JSON object with the contract's names. + pub fn from_json(value: &Value) -> Result { + match value { + Value::Object(m) => Ok(ScreenshotOptions { raw: m.clone() }), + _ => Err(Error::Invalid("screenshot options must be an object".into())), + } + } + fn set(mut self, key: &str, value: Value) -> Self { + self.raw.insert(key.to_string(), value); + self + } + /// The group it's in. Default: the first group that has the screen. + pub fn group(self, name: &str) -> Self { + self.set("group", name.into()) + } + /// The theme value to show. Default: the screen's first, with its dark shot for readers whose setting is dark. + pub fn theme(self, theme: &str) -> Self { + self.set("theme", theme.into()) + } + /// The size value to show. Default: the screen's first that has the theme. + pub fn size(self, size: &str) -> Self { + self.set("size", size.into()) + } + /// The image's alt text. Default: the screen's title, made from its key. + pub fn alt(self, alt: &str) -> Self { + self.set("alt", alt.into()) + } + /// Link the image to its full-size original. + pub fn link(self, link: bool) -> Self { + self.set("link", link.into()) + } + /// Show the manifest's small copy where it has one. + pub fn thumb(self, thumb: bool) -> Self { + self.set("thumb", thumb.into()) + } + /// `"lazy"` (the default) or `"eager"`. + pub fn loading(self, loading: &str) -> Self { + self.set("loading", loading.into()) + } + /// The gallery options' `dimensions` and `groups`, so the screen's shots pair as they do in that gallery. + pub fn gallery(mut self, options: &Options) -> Self { + for key in ["dimensions", "groups"] { + match options.raw.get(key) { + Some(v) => self.raw.insert(key.into(), v.clone()), + None => self.raw.remove(key), + }; + } + self + } + fn get(&self, key: &str) -> Option<&Value> { + self.raw.get(key).filter(|v| !v.is_null()) + } + fn check(&self, key: &str, ok: impl Fn(&Value) -> bool) -> Result, Error> { + match self.get(key) { + Some(v) if !ok(v) => Err(Error::Invalid(format!("screenshot option {key} is invalid"))), + v => Ok(v), + } + } +} + +struct Picked { + src: String, + src2x: Option, + width: u64, + height: u64, +} + +struct Shown { + light: Picked, + dark: Option, + href: String, + link: bool, + alt: String, + loading: String, +} + +fn fail(message: String) -> Result { + Err(Error::Invalid(message)) +} + +/// The screen's items in its group. When every one is a 2x shot, a 1x copy of each follows them: the 2x shots at half +/// their size. Otherwise the screen is the gallery's, 2x shots only as 2x copies. +fn screen_items(group: &Value, screen: &str, dims: &[crate::Dimension]) -> Vec { + let items: Vec = group["items"] + .as_array() + .unwrap() + .iter() + .filter(|item| parse_shot(item["name"].as_str().unwrap(), dims).key == screen) + .cloned() + .collect(); + if !items.iter().all(|item| parse_shot(item["name"].as_str().unwrap(), dims).x2) { + return items; + } + let halves: Vec = items + .iter() + .map(|item| { + let (w, h) = (item["width"].as_u64().unwrap(), item["height"].as_u64().unwrap()); + let width = w.div_ceil(2); + let height = (2 * h * width + w) / (2 * w); + let base = EXTENSION.replace(item["name"].as_str().unwrap(), "").into_owned(); + let name = base.strip_suffix("-2x").unwrap_or(&base).to_string(); + json!({ "name": name, "url": item["url"], "width": width, "height": height, "thumb": item.get("thumb") }) + }) + .collect(); + items.into_iter().chain(halves).collect() +} + +fn pick(v: &Variant, thumb: bool) -> Picked { + match (&v.thumb, thumb) { + (Some(t), true) => Picked { src: t.url.clone(), src2x: None, width: t.width, height: t.height }, + _ => Picked { + src: v.url.clone(), + src2x: v.url2x.clone().filter(|u| *u != v.url), + width: v.width, + height: v.height, + }, + } +} + +fn shown(manifest: &Value, options: &ScreenshotOptions) -> Result { + check_manifest(manifest)?; + let dims_opt = match options.get("dimensions") { + Some(v) if !check_dimensions(v) => return fail("gallery option dimensions is invalid".into()), + v => v, + }; + let dims = resolve_dimensions(dims_opt); + let keys = |dim: &str| -> Vec { + dims.iter().find(|d| d.key == dim).unwrap().values.iter().map(|v| v.key.clone()).collect() + }; + let screen = match options.get("screen").and_then(Value::as_str) { + Some(s) if !s.is_empty() => s.to_string(), + _ => return fail("screenshot option screen is required".into()), + }; + let group_opt = options.check("group", Value::is_string)?.and_then(Value::as_str); + let theme = options.check("theme", |v| v.as_str().is_some_and(|s| keys("theme").iter().any(|k| k == s)))?; + let theme = theme.and_then(Value::as_str); + let size = options.check("size", |v| v.as_str().is_some_and(|s| keys("size").iter().any(|k| k == s)))?; + let size = size.and_then(Value::as_str); + let alt = options.check("alt", Value::is_string)?.and_then(Value::as_str); + let link = options.check("link", Value::is_boolean)?.and_then(Value::as_bool) == Some(true); + let thumb = options.check("thumb", Value::is_boolean)?.and_then(Value::as_bool) == Some(true); + let loading = options.check("loading", |v| matches!(v.as_str(), Some("lazy" | "eager")))?; + let loading = loading.and_then(Value::as_str).unwrap_or("lazy").to_string(); + let has = |g: &Value| { + g["items"] + .as_array() + .unwrap() + .iter() + .any(|item| parse_shot(item["name"].as_str().unwrap(), &dims).key == screen) + }; + let groups = manifest["groups"].as_array().unwrap(); + let group = match group_opt { + Some(name) => { + let Some(g) = groups.iter().find(|g| g["name"] == name) else { + return fail(format!("the gallery manifest has no group {name}")); + }; + if !has(g) { + return fail(format!("gallery group {name} has no screen {screen}")); + } + g + } + None => match groups.iter().find(|g| has(g)) { + Some(g) => g, + None => return fail(format!("the gallery manifest has no screen {screen}")), + }, + }; + let gname = group["name"].as_str().unwrap(); + let one = json!({ "groups": [{ + "name": gname, + "title": group.get("title").cloned().unwrap_or(Value::Null), + "items": screen_items(group, &screen, &dims), + }] }); + let mut gallery = Options::default(); + for key in ["dimensions", "groups"] { + if let Some(v) = options.get(key) { + gallery = gallery.set(key, v.clone()); + } + } + let model = build_model(&one, &gallery)?; + let sc = &model.groups[0].screens[0]; + let order: Vec<&str> = model.dimensions.iter().map(|d| d.key.as_str()).collect(); + // The values shown: each dimension's option, else the first value of the screen's first variant that has the + // values chosen so far. + let mut choice: Vec<(&str, String)> = Vec::new(); + for &k in &order { + let asked = match k { + "theme" => theme, + "size" => size, + _ => None, + }; + let value = match asked { + Some(a) => a.to_string(), + None => { + let fits = sc.variants.iter().find(|v| choice.iter().all(|(c, x)| v.values[*c] == *x)); + fits.unwrap_or(&sc.variants[0]).values[k].clone() + } + }; + choice.push((k, value)); + } + let find = |c: &[(&str, String)]| sc.variants.iter().find(|v| c.iter().all(|(k, x)| v.values[*k] == *x)); + let Some(v) = find(&choice) else { + let keys: Vec<&str> = choice.iter().map(|(_, x)| x.as_str()).collect(); + return fail(format!("gallery screen {screen} in group {gname} has no {} screenshot", keys.join(" "))); + }; + // The dark shot, for readers whose setting is dark, when no theme was asked for; not when it's the same image. + let chosen_theme = &choice.iter().find(|(k, _)| *k == "theme").unwrap().1; + let found = if theme.is_none() && chosen_theme != "dark" { + let dark: Vec<(&str, String)> = + choice.iter().map(|(k, x)| (*k, if *k == "theme" { "dark".to_string() } else { x.clone() })).collect(); + find(&dark) + } else { + None + }; + let dv = found.filter(|d| d.url != v.url || d.url2x != v.url2x); + // The small copies only when every image shown has one, so light and dark readers see the same size. + let use_thumb = thumb && v.thumb.is_some() && dv.is_none_or(|d| d.thumb.is_some()); + let text = alt.unwrap_or(&sc.title); + let mut collapsed = String::new(); + let mut space = false; + for c in text.chars() { + if matches!(c, '\t' | '\n' | '\r' | ' ') { + space = true; + } else { + if space { + collapsed.push(' '); + space = false; + } + collapsed.push(c); + } + } + if space { + collapsed.push(' '); + } + let alt = collapsed.strip_prefix(' ').unwrap_or(&collapsed); + let alt = alt.strip_suffix(' ').unwrap_or(alt).to_string(); + Ok(Shown { + light: pick(v, use_thumb), + dark: dv.map(|d| pick(d, use_thumb)), + href: v.url.clone(), + link, + alt, + loading, + }) +} + +fn srcset(p: &Picked) -> String { + match &p.src2x { + None => escape(&p.src), + Some(x2) => format!("{}, {} 2x", escape(&p.src), escape(x2)), + } +} + +fn picture_html(s: &Shown) -> String { + let l = &s.light; + let set = if l.src2x.is_some() { format!(" srcset=\"{}\"", srcset(l)) } else { String::new() }; + let img = format!( + "\"{}\"", + escape(&l.src), + l.width, + l.height, + escape(&s.alt), + s.loading + ); + let (open, close) = + if s.link { (format!("", escape(&s.href)), "") } else { (String::new(), "") }; + match &s.dark { + None => format!("{open}{img}{close}\n"), + Some(d) => { + let source = format!( + "", + srcset(d), + d.width, + d.height + ); + format!("{open}\n{source}\n{img}\n{close}\n") + } + } +} + +/// One screenshot as HTML: an ``, or a `` with the dark shot for readers whose setting is dark. Fails +/// when the manifest or the options are invalid, or the screen has no shot for what's asked. +pub fn screenshot(manifest: &Value, options: &ScreenshotOptions) -> Result { + Ok(picture_html(&shown(manifest, options)?)) +} + +fn markdown_escape(s: &str, special: impl Fn(char) -> bool) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + if special(c) { + out.push('\\'); + } + out.push(c); + } + out +} + +/// One screenshot for a README: Markdown's `![alt](url)`, linked with `link`, or the HTML `` when it has a +/// dark shot. +pub fn screenshot_markdown(manifest: &Value, options: &ScreenshotOptions) -> Result { + let s = shown(manifest, options)?; + if s.dark.is_some() { + return Ok(picture_html(&s)); + } + let url = |u: &str| markdown_escape(u, |c| matches!(c, '\\' | '(' | ')' | '&')); + let image = format!("![{}]({})", markdown_escape(&s.alt, |c| c.is_ascii_punctuation()), url(&s.light.src)); + Ok(if s.link { format!("[{image}]({})\n", url(&s.href)) } else { format!("{image}\n") }) +} diff --git a/clients/gallery/rust/tests/contract.rs b/clients/gallery/rust/tests/contract.rs index 1f73421a4..8e97e23c5 100644 --- a/clients/gallery/rust/tests/contract.rs +++ b/clients/gallery/rust/tests/contract.rs @@ -6,7 +6,9 @@ use std::fs; use std::path::{Path, PathBuf}; use serde_json::Value; -use visualci_gallery::{Error, Gallery, Options, build_model, render}; +use visualci_gallery::{ + Error, Gallery, Options, ScreenshotOptions, build_model, render, screenshot, screenshot_markdown, +}; fn contract() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../contract") @@ -194,3 +196,40 @@ fn askama_doesnt_escape_it() { let html = Page { gallery: gallery.clone() }.render().unwrap(); assert_eq!(format!("
{gallery}
"), html); } + +/// contract/screenshots: each case's exact HTML and Markdown, and each refusal's message. +#[test] +fn screenshots() { + let dir = contract().join("screenshots"); + let manifest = read(&dir.join("manifest.json")); + for path in listed(&dir.join("cases"), "json") { + let options = ScreenshotOptions::from_json(&read(&path)).unwrap(); + let html = screenshot(&manifest, &options).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + assert_eq!(fs::read_to_string(path.with_extension("html")).unwrap(), html, "{}", path.display()); + let markdown = screenshot_markdown(&manifest, &options).unwrap(); + assert_eq!(fs::read_to_string(path.with_extension("md")).unwrap(), markdown, "{}", path.display()); + } + for path in listed(&dir.join("errors"), "json") { + let want = fs::read_to_string(path.with_extension("message")).unwrap(); + let result = ScreenshotOptions::from_json(&read(&path)).and_then(|o| { + let markdown = screenshot_markdown(&manifest, &o); + assert!(markdown.is_err(), "{}: the Markdown form must refuse it too", path.display()); + screenshot(&manifest, &o) + }); + match result { + Err(Error::Invalid(message)) => assert_eq!(want, format!("{message}\n"), "{}", path.display()), + other => panic!("{}: want a refusal, got {other:?}", path.display()), + } + } +} + +#[test] +fn screenshot_builder() { + let manifest = read(&contract().join("screenshots/manifest.json")); + let built = ScreenshotOptions::new("overview").theme("dark").link(true).loading("eager"); + let json = ScreenshotOptions::from_json( + &serde_json::json!({"screen": "overview", "theme": "dark", "link": true, "loading": "eager"}), + ) + .unwrap(); + assert_eq!(screenshot(&manifest, &json).unwrap(), screenshot(&manifest, &built).unwrap()); +} From b1182729425f92149293434f4410517453057e14 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 10:41:59 +0000 Subject: [PATCH 04/11] Gallery: loadManifest() in the JS library, and a React server component with an example page (sc-9561) --- clients/gallery/js/src/index.ts | 2 +- clients/gallery/js/src/load.ts | 15 ++++-- clients/gallery/js/src/render-entry.ts | 2 +- .../react/examples/next/app/overview/page.tsx | 13 +++++ clients/gallery/react/src/index.ts | 5 +- clients/gallery/react/src/screenshot.tsx | 13 +++++ clients/gallery/react/test/examples.test.ts | 8 +++- .../gallery/react/test/screenshot.test.tsx | 47 +++++++++++++++++++ 8 files changed, 97 insertions(+), 8 deletions(-) create mode 100644 clients/gallery/react/examples/next/app/overview/page.tsx create mode 100644 clients/gallery/react/src/screenshot.tsx create mode 100644 clients/gallery/react/test/screenshot.test.tsx diff --git a/clients/gallery/js/src/index.ts b/clients/gallery/js/src/index.ts index a4408a82d..941e94501 100644 --- a/clients/gallery/js/src/index.ts +++ b/clients/gallery/js/src/index.ts @@ -31,7 +31,7 @@ export type { export { render, escapeHtml } from "./render.js"; export { screenshot, screenshotMarkdown, type ScreenshotOptions } from "./screenshot.js"; export { hydrate, type Gallery, type HydrateOptions } from "./hydrate.js"; -export { load, type LoadOptions } from "./load.js"; +export { load, loadManifest, type LoadOptions, type ManifestSource } from "./load.js"; /** Renders the gallery into an empty element and hydrates it. When the manifest can't be read, the element says so * and the promise rejects. */ diff --git a/clients/gallery/js/src/load.ts b/clients/gallery/js/src/load.ts index a1e6ba214..1e113da42 100644 --- a/clients/gallery/js/src/load.ts +++ b/clients/gallery/js/src/load.ts @@ -2,7 +2,8 @@ import { buildModel, type Manifest, type Model, type Options } from "./model.js"; -export interface LoadOptions extends Options { +/** Where the manifest is and how to read it. */ +export interface ManifestSource { /** The manifest's URL: `https://app.visualci.com/g//.json`. */ manifest: string; /** How long to wait for it, in milliseconds. Default 20000. */ @@ -13,6 +14,8 @@ export interface LoadOptions extends Options { fetch?: typeof fetch; } +export interface LoadOptions extends Options, ManifestSource {} + /** A signal that aborts after `ms` (AbortSignal.timeout is missing before Safari 16). */ function timeout(ms: number): AbortSignal { if (typeof AbortSignal.timeout === "function") return AbortSignal.timeout(ms); @@ -21,8 +24,8 @@ function timeout(ms: number): AbortSignal { return controller.signal; } -/** Fetches the manifest and builds its model. Throws, naming the URL, when it can't be read or shows nothing. */ -export async function load(options: LoadOptions): Promise { +/** Fetches the manifest, parsed. Throws, naming the URL, when it can't be read. */ +export async function loadManifest(options: ManifestSource): Promise { const get = options.fetch ?? fetch; const attempts = Math.max(1, options.attempts ?? 3); let last: unknown; @@ -43,6 +46,12 @@ export async function load(options: LoadOptions): Promise { `The screenshots gallery couldn't read ${options.manifest}: ${last instanceof Error ? last.message : String(last)}`, ); } + return manifest; +} + +/** Fetches the manifest and builds its model. Throws, naming the URL, when it can't be read or shows nothing. */ +export async function load(options: LoadOptions): Promise { + const manifest = await loadManifest(options); try { return buildModel(manifest, options); } catch (e) { diff --git a/clients/gallery/js/src/render-entry.ts b/clients/gallery/js/src/render-entry.ts index 007d22059..a7ddd0111 100644 --- a/clients/gallery/js/src/render-entry.ts +++ b/clients/gallery/js/src/render-entry.ts @@ -14,4 +14,4 @@ export type { } from "./model.js"; export { render, escapeHtml } from "./render.js"; export { screenshot, screenshotMarkdown, type ScreenshotOptions } from "./screenshot.js"; -export { load, type LoadOptions } from "./load.js"; +export { load, loadManifest, type LoadOptions, type ManifestSource } from "./load.js"; diff --git a/clients/gallery/react/examples/next/app/overview/page.tsx b/clients/gallery/react/examples/next/app/overview/page.tsx new file mode 100644 index 000000000..b96d03ed1 --- /dev/null +++ b/clients/gallery/react/examples/next/app/overview/page.tsx @@ -0,0 +1,13 @@ +import { Screenshot } from "visualci-gallery-react"; + +export const metadata = { title: "Overview" }; + +export default function Overview() { + return ( + <> +

Overview

+ {/* One screenshot, in the reader's light or dark mode, linked to the full-size original. */} + + + ); +} diff --git a/clients/gallery/react/src/index.ts b/clients/gallery/react/src/index.ts index 3301f4c5d..eb4bf1a58 100644 --- a/clients/gallery/react/src/index.ts +++ b/clients/gallery/react/src/index.ts @@ -1,5 +1,6 @@ -// visualci-gallery-react: `import { Gallery } from "visualci-gallery-react"` in a server component (Next.js app -// router), or `import { GalleryMarkup } from "visualci-gallery-react/client"` with HTML rendered elsewhere (a loader, +// visualci-gallery-react: `import { Gallery, Screenshot } from "visualci-gallery-react"` in a server component +// (Next.js app router), or `import { GalleryMarkup } from "visualci-gallery-react/client"` with HTML rendered elsewhere (a loader, // getStaticProps, a build script). The stylesheet is the library's: `import "visualci-gallery/gallery.css"`. export { Gallery, type GalleryProps } from "./gallery.js"; export { GalleryMarkup, type GalleryMarkupProps } from "./gallery-markup.js"; +export { Screenshot, type ScreenshotProps } from "./screenshot.js"; diff --git a/clients/gallery/react/src/screenshot.tsx b/clients/gallery/react/src/screenshot.tsx new file mode 100644 index 000000000..16d0895da --- /dev/null +++ b/clients/gallery/react/src/screenshot.tsx @@ -0,0 +1,13 @@ +// One screenshot, as an async server component: it reads the manifest and renders the screen's , or a +// that shows the dark shot to readers whose setting is dark. It needs no script or stylesheet. A manifest that can't +// be read, or a screen with no shot for what's asked, throws, so a static build fails. +import { loadManifest, screenshot, type ManifestSource, type ScreenshotOptions } from "visualci-gallery/render"; + +/** The screenshot's options (screen, group, theme, size, alt, link, thumb, loading, dimensions, groups) and how to + * read the manifest (manifest, timeout, attempts, fetch). */ +export type ScreenshotProps = ScreenshotOptions & ManifestSource & { className?: string }; + +export async function Screenshot({ manifest, timeout, attempts, fetch, className, ...options }: ScreenshotProps) { + const html = screenshot(await loadManifest({ manifest, timeout, attempts, fetch }), options); + return ; +} diff --git a/clients/gallery/react/test/examples.test.ts b/clients/gallery/react/test/examples.test.ts index 49ba4e785..5f1c0e2f4 100644 --- a/clients/gallery/react/test/examples.test.ts +++ b/clients/gallery/react/test/examples.test.ts @@ -7,7 +7,7 @@ import { execFileSync } from "node:child_process"; import { existsSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { buildModel, render, type Manifest, type Options } from "visualci-gallery/render"; +import { buildModel, render, screenshot, type Manifest, type Options } from "visualci-gallery/render"; const site = join(import.meta.dirname, "../examples/next"); const fixture = join(import.meta.dirname, "../../contract/fixtures/fleetlayer/manifest.json"); @@ -79,6 +79,12 @@ describe("examples/next", () => { expect(html).toContain('id="theme-toggle"'); }); + it("app/overview/page.tsx: one screenshot, a with the dark shot for dark readers", () => { + const shot = screenshot(JSON.parse(readFileSync(fixture, "utf8")) as Manifest, { screen: "overview", link: true }); + expect(shot).toContain(""); + expect(page("overview")).toContain(`${shot}`); + }); + it("fails the build, naming the manifest, when it can't be read", () => { let error: (Error & { stdout?: Buffer; stderr?: Buffer }) | undefined; try { diff --git a/clients/gallery/react/test/screenshot.test.tsx b/clients/gallery/react/test/screenshot.test.tsx new file mode 100644 index 000000000..94c7cbd5b --- /dev/null +++ b/clients/gallery/react/test/screenshot.test.tsx @@ -0,0 +1,47 @@ +// The Screenshot component's markup is the contract's: for each case in contract/screenshots, exactly its HTML inside +// one . A manifest that can't be read, or a screen with no shot for what's asked, throws. +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { renderToString } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { Screenshot } from "../src/index.js"; + +const dir = join(import.meta.dirname, "../../contract/screenshots"); +const manifest = readFileSync(join(dir, "manifest.json"), "utf8"); +const serve = + (body: string, status = 200) => + async () => + new Response(body, { status }); +const MANIFEST = "https://app.visualci.com/g/acme/web.json"; + +describe("Screenshot", () => { + const cases = readdirSync(join(dir, "cases")) + .filter((f) => f.endsWith(".json")) + .sort(); + for (const file of cases) { + it(`renders the ${file} case's markup`, async () => { + const options = JSON.parse(readFileSync(join(dir, "cases", file), "utf8")); + const html = renderToString(await Screenshot({ ...options, manifest: MANIFEST, fetch: serve(manifest) })); + expect(html).toBe(`${readFileSync(join(dir, "cases", file.replace(/\.json$/, ".html")), "utf8")}`); + }); + } + + it("takes a class for its span", async () => { + const html = renderToString( + await Screenshot({ screen: "billing", className: "hero", manifest: MANIFEST, fetch: serve(manifest) }), + ); + expect(html).toMatch(/^ { + await expect( + Screenshot({ screen: "overview", manifest: MANIFEST, attempts: 1, fetch: serve("", 503) }), + ).rejects.toThrow(`The screenshots gallery couldn't read ${MANIFEST}: HTTP 503`); + }); + + it("fails when the screen has no shot for what's asked", async () => { + await expect( + Screenshot({ screen: "billing", theme: "dark", manifest: MANIFEST, fetch: serve(manifest) }), + ).rejects.toThrow("gallery screen billing in group Web has no dark desktop screenshot"); + }); +}); From 681b54fc1c12d0f07bedf14c9ae69f7079b5339c Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 10:42:36 +0000 Subject: [PATCH 05/11] Astro gallery: a component, with an example page (sc-9561) --- .../examples/site/src/pages/overview.astro | 15 +++++++++ clients/gallery/astro/package.json | 3 +- clients/gallery/astro/src/Screenshot.astro | 18 ++++++++++ clients/gallery/astro/src/index.ts | 3 +- clients/gallery/astro/test/examples.test.ts | 8 ++++- clients/gallery/astro/test/screenshot.test.ts | 33 +++++++++++++++++++ 6 files changed, 77 insertions(+), 3 deletions(-) create mode 100644 clients/gallery/astro/examples/site/src/pages/overview.astro create mode 100644 clients/gallery/astro/src/Screenshot.astro create mode 100644 clients/gallery/astro/test/screenshot.test.ts diff --git a/clients/gallery/astro/examples/site/src/pages/overview.astro b/clients/gallery/astro/examples/site/src/pages/overview.astro new file mode 100644 index 000000000..5aabfbcb9 --- /dev/null +++ b/clients/gallery/astro/examples/site/src/pages/overview.astro @@ -0,0 +1,15 @@ +--- +import { Screenshot } from "visualci-astro-gallery"; +--- + + + + + Overview + + +

Overview

+ + + + diff --git a/clients/gallery/astro/package.json b/clients/gallery/astro/package.json index df3d9efc1..61336210e 100644 --- a/clients/gallery/astro/package.json +++ b/clients/gallery/astro/package.json @@ -23,7 +23,8 @@ "type": "module", "exports": { ".": "./src/index.ts", - "./Gallery.astro": "./src/Gallery.astro" + "./Gallery.astro": "./src/Gallery.astro", + "./Screenshot.astro": "./src/Screenshot.astro" }, "scripts": { "test": "vitest run" diff --git a/clients/gallery/astro/src/Screenshot.astro b/clients/gallery/astro/src/Screenshot.astro new file mode 100644 index 000000000..b20931285 --- /dev/null +++ b/clients/gallery/astro/src/Screenshot.astro @@ -0,0 +1,18 @@ +--- +// One screenshot from a VisualCI public gallery manifest, rendered when the site builds: the screen's , or a +// that shows the dark shot to readers whose setting is dark. It needs no script or stylesheet. A manifest +// that can't be read, or a screen with no shot for what's asked, fails the build. +// +// +// +// The props are the library's screenshot options (screen, group, theme, size, alt, link, thumb, loading, dimensions, +// groups) and how to read the manifest (manifest, timeout, attempts, fetch). +import { loadManifest, screenshot, type ManifestSource, type ScreenshotOptions } from "visualci-gallery/render"; + +export type Props = ScreenshotOptions & ManifestSource; + +const { manifest, timeout, attempts, fetch, ...options } = Astro.props; +const html = screenshot(await loadManifest({ manifest, timeout, attempts, fetch }), options); +--- + + diff --git a/clients/gallery/astro/src/index.ts b/clients/gallery/astro/src/index.ts index 5b5691eab..d84b242f5 100644 --- a/clients/gallery/astro/src/index.ts +++ b/clients/gallery/astro/src/index.ts @@ -1,3 +1,4 @@ -// visualci-astro-gallery: `import Gallery from "visualci-astro-gallery"`. +// visualci-astro-gallery: `import Gallery, { Screenshot } from "visualci-astro-gallery"`. export { default } from "./Gallery.astro"; export type { Props } from "./Gallery.astro"; +export { default as Screenshot } from "./Screenshot.astro"; diff --git a/clients/gallery/astro/test/examples.test.ts b/clients/gallery/astro/test/examples.test.ts index 93ded6cc6..6ed585c1e 100644 --- a/clients/gallery/astro/test/examples.test.ts +++ b/clients/gallery/astro/test/examples.test.ts @@ -7,7 +7,7 @@ import { execFileSync } from "node:child_process"; import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; -import { buildModel, render, type Manifest } from "visualci-gallery/render"; +import { buildModel, render, screenshot, type Manifest } from "visualci-gallery/render"; const site = join(import.meta.dirname, "../examples/site"); const fixture = join(import.meta.dirname, "../../contract/fixtures/fleetlayer/manifest.json"); @@ -114,6 +114,12 @@ describe("examples/site", () => { expect(root.dataset.vgTheme).toBe("light"); }); + it("overview.astro: one screenshot, a with the dark shot for dark readers", () => { + const shot = screenshot(JSON.parse(readFileSync(fixture, "utf8")) as Manifest, { screen: "overview", link: true }); + expect(shot).toContain(""); + expect(page("overview")).toContain(shot.trim()); + }); + it("app.astro: with themeSwitch={false} the gallery follows the layout's toggle", async () => { await open("app"); const root = q("section.vg"); diff --git a/clients/gallery/astro/test/screenshot.test.ts b/clients/gallery/astro/test/screenshot.test.ts new file mode 100644 index 000000000..56a604140 --- /dev/null +++ b/clients/gallery/astro/test/screenshot.test.ts @@ -0,0 +1,33 @@ +// The Screenshot component's markup is the contract's: for each case in contract/screenshots, rendering it with the +// case's options gives exactly its HTML. A screen with no shot for what's asked fails the render. +import { experimental_AstroContainer as AstroContainer } from "astro/container"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import Screenshot from "../src/Screenshot.astro"; + +const dir = join(import.meta.dirname, "../../contract/screenshots"); +const manifest = readFileSync(join(dir, "manifest.json"), "utf8"); +const fetch = async () => new Response(manifest); +const MANIFEST = "https://app.visualci.com/g/acme/web.json"; + +describe("Screenshot", () => { + for (const file of readdirSync(join(dir, "cases")) + .filter((f) => f.endsWith(".json")) + .sort()) { + it(`renders the ${file} case's markup`, async () => { + const container = await AstroContainer.create(); + const html = await container.renderToString(Screenshot, { + props: { ...JSON.parse(readFileSync(join(dir, "cases", file), "utf8")), manifest: MANIFEST, fetch }, + }); + expect(html).toBe(readFileSync(join(dir, "cases", file.replace(/\.json$/, ".html")), "utf8")); + }); + } + + it("fails when the screen has no shot for what's asked", async () => { + const container = await AstroContainer.create(); + await expect( + container.renderToString(Screenshot, { props: { screen: "billing", theme: "dark", manifest: MANIFEST, fetch } }), + ).rejects.toThrow("gallery screen billing in group Web has no dark desktop screenshot"); + }); +}); From 5056c62e3aecd0dd7431d3f1ea5eb05e791fdc31 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 10:43:21 +0000 Subject: [PATCH 06/11] Docusaurus gallery: a Screenshot component, with an example page (sc-9561) --- .../examples/site/docs/overview.mdx | 9 +++++++ clients/gallery/docusaurus/package.json | 4 ++++ clients/gallery/docusaurus/src/Screenshot.tsx | 24 +++++++++++++++++++ .../gallery/docusaurus/test/examples.test.ts | 8 ++++++- 4 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 clients/gallery/docusaurus/examples/site/docs/overview.mdx create mode 100644 clients/gallery/docusaurus/src/Screenshot.tsx diff --git a/clients/gallery/docusaurus/examples/site/docs/overview.mdx b/clients/gallery/docusaurus/examples/site/docs/overview.mdx new file mode 100644 index 000000000..72212f365 --- /dev/null +++ b/clients/gallery/docusaurus/examples/site/docs/overview.mdx @@ -0,0 +1,9 @@ +--- +title: Overview +--- + +import Screenshot from "visualci-gallery-docusaurus/Screenshot"; + +One screenshot, in the reader's light or dark mode, linked to the full-size original. + + diff --git a/clients/gallery/docusaurus/package.json b/clients/gallery/docusaurus/package.json index caf1ee5af..b7e3ac08e 100644 --- a/clients/gallery/docusaurus/package.json +++ b/clients/gallery/docusaurus/package.json @@ -30,6 +30,10 @@ "./Gallery": { "types": "./dist/Gallery.d.ts", "default": "./dist/Gallery.js" + }, + "./Screenshot": { + "types": "./dist/Screenshot.d.ts", + "default": "./dist/Screenshot.js" } }, "scripts": { diff --git a/clients/gallery/docusaurus/src/Screenshot.tsx b/clients/gallery/docusaurus/src/Screenshot.tsx new file mode 100644 index 000000000..9c7877cf5 --- /dev/null +++ b/clients/gallery/docusaurus/src/Screenshot.tsx @@ -0,0 +1,24 @@ +// visualci-gallery-docusaurus/Screenshot: one screenshot, in MDX or a React page: the screen's , or a +// that shows the dark shot to readers whose setting is dark. Its manifest must be one of the plugin's `manifests`, +// read when the site built; the props are the library's screenshot options. It needs no script. +// +// import Screenshot from "visualci-gallery-docusaurus/Screenshot"; +// +import { usePluginData } from "@docusaurus/useGlobalData"; +import { screenshot, type ScreenshotOptions } from "visualci-gallery/render"; +import type { GlobalData } from "./index.js"; + +export interface ScreenshotProps extends ScreenshotOptions { + /** The manifest's URL, as it appears in the plugin's `manifests`. */ + manifest: string; + className?: string; +} + +export default function Screenshot({ manifest, className, ...options }: ScreenshotProps) { + const data = usePluginData("visualci-gallery-docusaurus") as GlobalData | undefined; + const parsed = data?.manifests[manifest]; + if (!parsed) { + throw new Error(`visualci-gallery-docusaurus: add ${manifest} to the plugin's manifests in docusaurus.config`); + } + return ; +} diff --git a/clients/gallery/docusaurus/test/examples.test.ts b/clients/gallery/docusaurus/test/examples.test.ts index 581cafcaf..2d2019995 100644 --- a/clients/gallery/docusaurus/test/examples.test.ts +++ b/clients/gallery/docusaurus/test/examples.test.ts @@ -7,7 +7,7 @@ import { execFileSync } from "node:child_process"; import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { buildModel, render, type Manifest, type Options } from "visualci-gallery/render"; +import { buildModel, render, screenshot, type Manifest, type Options } from "visualci-gallery/render"; const site = join(import.meta.dirname, "../examples/site"); const fixture = join(import.meta.dirname, "../../contract/fixtures/fleetlayer/manifest.json"); @@ -76,6 +76,12 @@ describe("examples/site", () => { ); }); + it("docs/overview.mdx: one screenshot, a with the dark shot for dark readers", () => { + const shot = screenshot(JSON.parse(readFileSync(fixture, "utf8")) as Manifest, { screen: "overview", link: true }); + expect(shot).toContain(""); + expect(page("docs/overview")).toContain(`${shot}`); + }); + it("docs/app.mdx: with themeSwitch={false} the gallery follows Docusaurus's toggle", () => { expect(page("docs/app")).toContain(markup({ title: null, themeSwitch: false })); }); From 21f3e580735e049d522f220589d035dbcbaa3a90 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 10:45:03 +0000 Subject: [PATCH 07/11] VitePress gallery: a component, with an example page; both plugins only read the manifests, and each component checks what it shows (sc-9561) --- clients/gallery/docusaurus/src/index.ts | 29 ++++---------- .../gallery/docusaurus/test/plugin.test.ts | 8 ++-- .../vitepress/examples/site/overview.md | 5 +++ clients/gallery/vitepress/package.json | 4 ++ clients/gallery/vitepress/src/Screenshot.ts | 38 +++++++++++++++++++ clients/gallery/vitepress/src/index.ts | 28 +++----------- clients/gallery/vitepress/src/theme.ts | 8 ++-- .../gallery/vitepress/test/examples.test.ts | 8 +++- clients/gallery/vitepress/test/plugin.test.ts | 6 +-- .../gallery/vitepress/test/screenshot.test.ts | 30 +++++++++++++++ clients/gallery/vitepress/test/theme.test.ts | 4 +- clients/gallery/vitepress/vitest.config.ts | 6 ++- 12 files changed, 117 insertions(+), 57 deletions(-) create mode 100644 clients/gallery/vitepress/examples/site/overview.md create mode 100644 clients/gallery/vitepress/src/Screenshot.ts create mode 100644 clients/gallery/vitepress/test/screenshot.test.ts diff --git a/clients/gallery/docusaurus/src/index.ts b/clients/gallery/docusaurus/src/index.ts index be8aa887d..f2fa3a4c9 100644 --- a/clients/gallery/docusaurus/src/index.ts +++ b/clients/gallery/docusaurus/src/index.ts @@ -1,11 +1,12 @@ // visualci-gallery-docusaurus: the plugin. It reads each manifest in `manifests` when the site builds (or the dev // server starts) and hands them to the Gallery component as the plugin's global data; it adds the library's -// stylesheet to every page. A manifest that can't be read, or has nothing to show, fails the build. +// stylesheet to every page. A manifest that can't be read fails the build, as does a gallery or a screenshot it +// can't show. // // plugins: [["visualci-gallery-docusaurus", { manifests: ["https://app.visualci.com/g/acme/web.json"] }]] import { createRequire } from "node:module"; import type { LoadContext, Plugin } from "@docusaurus/types"; -import { load, type Manifest } from "visualci-gallery/render"; +import { loadManifest, type Manifest } from "visualci-gallery/render"; export interface PluginOptions { /** The manifests the site's galleries show: `https://app.visualci.com/g//.json`. */ @@ -25,26 +26,10 @@ export interface GlobalData { export const PLUGIN_NAME = "visualci-gallery-docusaurus"; -/** Reads one manifest with load()'s retries and checks (it throws when the manifest can't be read or shows nothing), - * keeping the parsed JSON for the component to render with each gallery's own options. */ -async function read(url: string, options: PluginOptions): Promise { - const get = options.fetch ?? fetch; - let manifest: Manifest | undefined; - await load({ - manifest: url, - timeout: options.timeout, - attempts: options.attempts, - fetch: async (input, init) => { - const res = await get(input, init); - if (res.ok) - manifest = (await res - .clone() - .json() - .catch(() => undefined)) as Manifest | undefined; - return res; - }, - }); - return manifest!; +/** Reads one manifest with loadManifest()'s retries (it throws when the manifest can't be read), keeping the parsed + * JSON for the components to render with each one's own options: a gallery or a screenshot checks what it shows. */ +function read(url: string, options: PluginOptions): Promise { + return loadManifest({ manifest: url, timeout: options.timeout, attempts: options.attempts, fetch: options.fetch }); } export default function visualciGallery(_context: LoadContext, options: PluginOptions): Plugin { diff --git a/clients/gallery/docusaurus/test/plugin.test.ts b/clients/gallery/docusaurus/test/plugin.test.ts index 62ac2ceb4..858ac94f1 100644 --- a/clients/gallery/docusaurus/test/plugin.test.ts +++ b/clients/gallery/docusaurus/test/plugin.test.ts @@ -1,5 +1,5 @@ // The plugin on its own: it reads each manifest into its global data, refuses a config without manifests, and fails -// (so the build does) when a manifest can't be read or has nothing to show. +// (so the build does) when a manifest can't be read. import { readFileSync } from "node:fs"; import { join } from "node:path"; import type { LoadContext } from "@docusaurus/types"; @@ -45,7 +45,9 @@ describe("visualci-gallery-docusaurus", () => { ); }); - it("fails when a manifest has nothing to show", async () => { - await expect(content({ manifests: [MANIFEST], fetch: serve('{"groups":[]}') })).rejects.toThrow(/can't show/); + it("keeps a manifest as it was read: the components check what they show", async () => { + await expect(content({ manifests: [MANIFEST], fetch: serve('{"groups":[]}') })).resolves.toEqual({ + manifests: { [MANIFEST]: { groups: [] } }, + }); }); }); diff --git a/clients/gallery/vitepress/examples/site/overview.md b/clients/gallery/vitepress/examples/site/overview.md new file mode 100644 index 000000000..189c38c52 --- /dev/null +++ b/clients/gallery/vitepress/examples/site/overview.md @@ -0,0 +1,5 @@ +# Overview + +One screenshot, in the reader's light or dark mode, linked to the full-size original. + + diff --git a/clients/gallery/vitepress/package.json b/clients/gallery/vitepress/package.json index c4f6ff825..87775aa4f 100644 --- a/clients/gallery/vitepress/package.json +++ b/clients/gallery/vitepress/package.json @@ -32,6 +32,10 @@ "types": "./dist/Gallery.d.ts", "default": "./dist/Gallery.js" }, + "./Screenshot": { + "types": "./dist/Screenshot.d.ts", + "default": "./dist/Screenshot.js" + }, "./theme": { "types": "./dist/theme.d.ts", "default": "./dist/theme.js" diff --git a/clients/gallery/vitepress/src/Screenshot.ts b/clients/gallery/vitepress/src/Screenshot.ts new file mode 100644 index 000000000..b19456a66 --- /dev/null +++ b/clients/gallery/vitepress/src/Screenshot.ts @@ -0,0 +1,38 @@ +// visualci-gallery-vitepress/Screenshot: one screenshot, as a Vue component: the screen's , or a that +// shows the dark shot to readers whose setting is dark. Its manifest must be one of the plugin's `manifests`, read +// when the site built; the other props are the library's screenshot options. It needs no script. +// +// +import { computed, defineComponent, h, type PropType } from "vue"; +import { screenshot, type ScreenshotOptions } from "visualci-gallery/render"; +import data from "virtual:visualci-gallery"; + +export default defineComponent({ + name: "Screenshot", + props: { + /** The manifest's URL, as it appears in the plugin's `manifests`. */ + manifest: { type: String, required: true }, + screen: { type: String, required: true }, + group: String, + theme: String, + size: String, + alt: String, + link: Boolean, + thumb: Boolean, + loading: String as PropType<"lazy" | "eager">, + dimensions: Array as PropType, + groups: Object as PropType, + }, + setup(props) { + const html = computed(() => { + const parsed = data.manifests[props.manifest]; + if (!parsed) + throw new Error( + `visualci-gallery-vitepress: add ${props.manifest} to the plugin's manifests in the Vite config`, + ); + const { manifest: _, ...options } = props; + return screenshot(parsed, options as ScreenshotOptions); + }); + return () => h("span", { innerHTML: html.value }); + }, +}); diff --git a/clients/gallery/vitepress/src/index.ts b/clients/gallery/vitepress/src/index.ts index 5ebc5a06b..0e3f56b81 100644 --- a/clients/gallery/vitepress/src/index.ts +++ b/clients/gallery/vitepress/src/index.ts @@ -1,11 +1,11 @@ // visualci-gallery-vitepress: the Vite plugin. It reads each manifest in `manifests` when the site builds (or the dev // server starts) and serves them to the Gallery component as the module virtual:visualci-gallery. A manifest that -// can't be read, or has nothing to show, fails the build. +// can't be read fails the build, as does a gallery or a screenshot it can't show. // // // .vitepress/config.ts // vite: { plugins: [visualciGallery({ manifests: ["https://app.visualci.com/g/acme/web.json"] })] } import type { Plugin } from "vite"; -import { load, type Manifest } from "visualci-gallery/render"; +import { loadManifest, type Manifest } from "visualci-gallery/render"; export interface PluginOptions { /** The manifests the site's galleries show: `https://app.visualci.com/g//.json`. */ @@ -22,26 +22,10 @@ const PACKAGE = "visualci-gallery-vitepress"; const ID = "virtual:visualci-gallery"; const RESOLVED = `\0${ID}`; -/** Reads one manifest with load()'s retries and checks (it throws when the manifest can't be read or shows nothing), - * keeping the parsed JSON for the component to render with each gallery's own options. */ -async function read(url: string, options: PluginOptions): Promise { - const get = options.fetch ?? fetch; - let manifest: Manifest | undefined; - await load({ - manifest: url, - timeout: options.timeout, - attempts: options.attempts, - fetch: async (input, init) => { - const res = await get(input, init); - if (res.ok) - manifest = (await res - .clone() - .json() - .catch(() => undefined)) as Manifest | undefined; - return res; - }, - }); - return manifest!; +/** Reads one manifest with loadManifest()'s retries (it throws when the manifest can't be read), keeping the parsed + * JSON for the components to render with each one's own options: a gallery or a screenshot checks what it shows. */ +function read(url: string, options: PluginOptions): Promise { + return loadManifest({ manifest: url, timeout: options.timeout, attempts: options.attempts, fetch: options.fetch }); } export function visualciGallery(options: PluginOptions): Plugin { diff --git a/clients/gallery/vitepress/src/theme.ts b/clients/gallery/vitepress/src/theme.ts index 1146ba6a8..6709b9522 100644 --- a/clients/gallery/vitepress/src/theme.ts +++ b/clients/gallery/vitepress/src/theme.ts @@ -1,12 +1,13 @@ -// visualci-gallery-vitepress/theme: for the site's .vitepress/theme/index.ts. enhanceApp() registers for -// every page's Markdown and, in the browser, keeps in step with VitePress's dark mode (it marks dark -// with ), so a gallery with themeSwitch false follows the site's toggle. +// visualci-gallery-vitepress/theme: for the site's .vitepress/theme/index.ts. enhanceApp() registers and +// for every page's Markdown and, in the browser, keeps in step with VitePress's dark +// mode (it marks dark with ), so a gallery with themeSwitch false follows the site's toggle. // // import DefaultTheme from "vitepress/theme"; // import { enhanceApp } from "visualci-gallery-vitepress/theme"; // export default { extends: DefaultTheme, enhanceApp }; import type { App } from "vue"; import Gallery from "./Gallery.js"; +import Screenshot from "./Screenshot.js"; let following = false; @@ -25,5 +26,6 @@ export function followDarkClass(): void { export function enhanceApp({ app }: { app: App }): void { app.component("Gallery", Gallery); + app.component("Screenshot", Screenshot); followDarkClass(); } diff --git a/clients/gallery/vitepress/test/examples.test.ts b/clients/gallery/vitepress/test/examples.test.ts index a678ab8de..75531c9e5 100644 --- a/clients/gallery/vitepress/test/examples.test.ts +++ b/clients/gallery/vitepress/test/examples.test.ts @@ -7,7 +7,7 @@ import { execFileSync } from "node:child_process"; import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { buildModel, render, type Manifest, type Options } from "visualci-gallery/render"; +import { buildModel, render, screenshot, type Manifest, type Options } from "visualci-gallery/render"; const site = join(import.meta.dirname, "../examples/site"); const fixture = join(import.meta.dirname, "../../contract/fixtures/fleetlayer/manifest.json"); @@ -81,6 +81,12 @@ describe("examples/site", () => { expect(page("app")).toContain(markup({ title: null, themeSwitch: false })); }); + it("overview.md: one screenshot, a with the dark shot for dark readers", () => { + const shot = screenshot(JSON.parse(readFileSync(fixture, "utf8")) as Manifest, { screen: "overview", link: true }); + expect(shot).toContain(""); + expect(page("overview")).toContain(`${shot}`); + }); + it("fails the build, naming the manifest, when it can't be read", () => { let error: (Error & { stdout?: Buffer; stderr?: Buffer }) | undefined; try { diff --git a/clients/gallery/vitepress/test/plugin.test.ts b/clients/gallery/vitepress/test/plugin.test.ts index b96ddae44..a932b300f 100644 --- a/clients/gallery/vitepress/test/plugin.test.ts +++ b/clients/gallery/vitepress/test/plugin.test.ts @@ -1,5 +1,5 @@ // The plugin on its own: it serves each manifest as the virtual module, refuses a config without manifests, and fails -// (so the build does) when a manifest can't be read or has nothing to show. +// (so the build does) when a manifest can't be read. import { readFileSync } from "node:fs"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; @@ -46,8 +46,8 @@ describe("visualci-gallery-vitepress", () => { await expect(call(p, "buildStart")).rejects.toThrow(`The screenshots gallery couldn't read ${MANIFEST}: HTTP 503`); }); - it("fails the build when a manifest has nothing to show", async () => { + it("keeps a manifest as it was read: the components check what they show", async () => { const p = visualciGallery({ manifests: [MANIFEST], fetch: serve('{"groups":[]}') }); - await expect(call(p, "buildStart")).rejects.toThrow(/can't show/); + await expect(call(p, "buildStart")).resolves.toBeUndefined(); }); }); diff --git a/clients/gallery/vitepress/test/screenshot.test.ts b/clients/gallery/vitepress/test/screenshot.test.ts new file mode 100644 index 000000000..f41a6e08f --- /dev/null +++ b/clients/gallery/vitepress/test/screenshot.test.ts @@ -0,0 +1,30 @@ +// The Screenshot component's markup is the contract's: for each case in contract/screenshots, Vue's server renderer +// gives exactly its HTML inside one . +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { createSSRApp, h } from "vue"; +import { renderToString } from "vue/server-renderer"; +import { describe, expect, it } from "vitest"; +import Screenshot from "../src/Screenshot.js"; + +const dir = join(import.meta.dirname, "../../contract/screenshots"); +const manifest = "https://app.visualci.com/g/acme/screenshots.json"; +const app = (props: Record) => createSSRApp({ render: () => h(Screenshot, props as never) }); + +describe("Screenshot", () => { + for (const file of readdirSync(join(dir, "cases")) + .filter((f) => f.endsWith(".json")) + .sort()) { + it(`renders the ${file} case's markup`, async () => { + const options = JSON.parse(readFileSync(join(dir, "cases", file), "utf8")); + const html = readFileSync(join(dir, "cases", file.replace(/\.json$/, ".html")), "utf8"); + expect(await renderToString(app({ manifest, ...options }))).toBe(`${html}`); + }); + } + + it("fails when the screen has no shot for what's asked", async () => { + await expect(renderToString(app({ manifest, screen: "billing", theme: "dark" }))).rejects.toThrow( + "gallery screen billing in group Web has no dark desktop screenshot", + ); + }); +}); diff --git a/clients/gallery/vitepress/test/theme.test.ts b/clients/gallery/vitepress/test/theme.test.ts index 13cc1cb02..61a371b4d 100644 --- a/clients/gallery/vitepress/test/theme.test.ts +++ b/clients/gallery/vitepress/test/theme.test.ts @@ -1,8 +1,9 @@ // @vitest-environment jsdom -// enhanceApp registers , and follows VitePress's `dark` class from then on. +// enhanceApp registers and , and follows VitePress's `dark` class from then on. import { describe, expect, it, vi } from "vitest"; import { enhanceApp } from "../src/theme.js"; import Gallery from "../src/Gallery.js"; +import Screenshot from "../src/Screenshot.js"; describe("visualci-gallery-vitepress/theme", () => { it("registers the component and mirrors the dark class to data-theme", async () => { @@ -11,6 +12,7 @@ describe("visualci-gallery-vitepress/theme", () => { const component = vi.fn(); enhanceApp({ app: { component } as never }); expect(component).toHaveBeenCalledWith("Gallery", Gallery); + expect(component).toHaveBeenCalledWith("Screenshot", Screenshot); expect(html.dataset.theme).toBe("dark"); html.classList.remove("dark"); await vi.waitFor(() => expect(html.dataset.theme).toBe("light")); diff --git a/clients/gallery/vitepress/vitest.config.ts b/clients/gallery/vitepress/vitest.config.ts index 45d6deb3b..6ddd87d04 100644 --- a/clients/gallery/vitepress/vitest.config.ts +++ b/clients/gallery/vitepress/vitest.config.ts @@ -1,5 +1,6 @@ // The tests' Vite has the plugin, with every contract fixture's manifest served by a stub fetch at -// https://app.visualci.com/g/acme/.json, so the component's virtual module is the real one. +// https://app.visualci.com/g/acme/.json, and contract/screenshots' at .../acme/screenshots.json, so the +// components' virtual module is the real one. import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { defineConfig } from "vitest/config"; @@ -12,9 +13,10 @@ const url = (name: string) => `https://app.visualci.com/g/acme/${name}.json`; export default defineConfig({ plugins: [ visualciGallery({ - manifests: names.map(url), + manifests: names.map(url).concat(url("screenshots")), fetch: async (input) => { const name = String(input).replace(/^.*\/acme\/|\.json$/g, ""); + if (name === "screenshots") return new Response(readFileSync(join(fixtures, "../screenshots/manifest.json"))); return new Response(readFileSync(join(fixtures, name, "manifest.json"))); }, }), From 6e40fe1d7870a7c202e8e2fbb1770591b5f82dd1 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 10:48:23 +0000 Subject: [PATCH 08/11] Docs: One screenshot, a page for the screenshot embed and its components, with a changelog line (sc-9561) --- ...11-gallery-libraries-041-one-screenshot.md | 1 + frontend/content/docs/gallery.md | 2 + frontend/content/docs/gallery/docusaurus.md | 2 +- frontend/content/docs/gallery/mkdocs.md | 1 + frontend/content/docs/gallery/screenshot.md | 133 ++++++++++++++++++ frontend/content/docs/gallery/vitepress.md | 2 +- frontend/src/docs/nav.ts | 2 +- plugin/skills/visualci-gallery/SKILL.md | 2 + 8 files changed, 142 insertions(+), 3 deletions(-) create mode 100644 frontend/content/changelog/2026-12-06-0311-gallery-libraries-041-one-screenshot.md create mode 100644 frontend/content/docs/gallery/screenshot.md diff --git a/frontend/content/changelog/2026-12-06-0311-gallery-libraries-041-one-screenshot.md b/frontend/content/changelog/2026-12-06-0311-gallery-libraries-041-one-screenshot.md new file mode 100644 index 000000000..dfd22f3a0 --- /dev/null +++ b/frontend/content/changelog/2026-12-06-0311-gallery-libraries-041-one-screenshot.md @@ -0,0 +1 @@ +**Gallery libraries 0.4.1: one screenshot.** Each gallery library can show a single screenshot in a page or a README: an ``, or a `` with the dark shot for readers whose setting is dark, with its size set. `screenshot()` returns the HTML and `screenshotMarkdown()` (`screenshot_markdown` in Ruby, Python and Rust) the Markdown; React, Astro, Docusaurus and VitePress have a `` component, MkDocs a `visualci-screenshot` block, and Hugo a `visualci-screenshot` shortcode. [One screenshot](/docs/gallery/screenshot/) diff --git a/frontend/content/docs/gallery.md b/frontend/content/docs/gallery.md index 6467cdeb4..a8c2ccf74 100644 --- a/frontend/content/docs/gallery.md +++ b/frontend/content/docs/gallery.md @@ -26,6 +26,8 @@ A gallery library turns the manifest into a screenshots page: a tab for each gro They all render the same HTML, take the same [options](/docs/gallery/options/), and take your site's look through CSS variables. A page built at deploy time fails its build when the manifest can't be read, so it never ships without its screenshots. +For one screenshot in a page or a README, in the reader's light or dark mode, see [One screenshot](/docs/gallery/screenshot/). + To set one up from a prompt, an agent with VisualCI's MCP server loads the `visualci-gallery` skill with `get_skill`, or reads this page's Markdown copy. The steps, for any stack: diff --git a/frontend/content/docs/gallery/docusaurus.md b/frontend/content/docs/gallery/docusaurus.md index 7a9a19b2d..6d9a13509 100644 --- a/frontend/content/docs/gallery/docusaurus.md +++ b/frontend/content/docs/gallery/docusaurus.md @@ -140,7 +140,7 @@ The gallery follows the site's own light and dark toggle. ## When the manifest can't be read -The plugin tries three times, 20 seconds each, then fails the build with an error that names the URL. It also fails when the manifest has nothing to show, and a page fails when a prop is invalid. The site you have keeps serving its last build until VisualCI answers again. +The plugin tries three times, 20 seconds each, then fails the build with an error that names the URL. A page fails when its gallery has nothing to show or a prop is invalid. The site you have keeps serving its last build until VisualCI answers again. ## Pinning the version diff --git a/frontend/content/docs/gallery/mkdocs.md b/frontend/content/docs/gallery/mkdocs.md index 64b832786..0e7aeb3fa 100644 --- a/frontend/content/docs/gallery/mkdocs.md +++ b/frontend/content/docs/gallery/mkdocs.md @@ -46,6 +46,7 @@ nav: - screenshots.md - tour.md - app.md + - overview.md ``` It takes `timeout` (seconds for each try, default 20) and `attempts` (default 3): `- visualci-gallery: {timeout: 30}`. diff --git a/frontend/content/docs/gallery/screenshot.md b/frontend/content/docs/gallery/screenshot.md new file mode 100644 index 000000000..3b01b08c4 --- /dev/null +++ b/frontend/content/docs/gallery/screenshot.md @@ -0,0 +1,133 @@ +--- +title: One screenshot +description: Show one screenshot from your VisualCI gallery in a page or a README, in the reader's light or dark mode, with the same gallery libraries and components. +--- + +A [screenshots page](/docs/gallery/) shows every screen. Sometimes a page needs just one: the overview at the top of the docs, the dashboard in a README. Each gallery library can render one screenshot from the same manifest: an ``, or a `` that shows the dark shot to readers whose setting is dark. It has its width and height set, so the page doesn't jump while it loads, and it's lazy-loaded unless you ask otherwise. + +It needs no stylesheet or script. Install the library for your stack as its guide says; every snippet below is a file from that library's example site, which VisualCI's tests build and check. + +## In a framework + +Each framework's package has a `Screenshot` component next to its `Gallery`. It reads the manifest when the site builds, and the build fails when the manifest can't be read or the screen isn't in it. + +[React and Next.js](/docs/gallery/react/), a server component: + + +```tsx +import { Screenshot } from "visualci-gallery-react"; + +export const metadata = { title: "Overview" }; + +export default function Overview() { + return ( + <> +

Overview

+ {/* One screenshot, in the reader's light or dark mode, linked to the full-size original. */} + + + ); +} +``` + +[Astro](/docs/gallery/astro/): + + +```astro +--- +import { Screenshot } from "visualci-astro-gallery"; +--- + + + + + Overview + + +

Overview

+ + + + +``` + +[Docusaurus](/docs/gallery/docusaurus/), with the plugin in `docusaurus.config.js` as for a gallery: + + +```mdx +--- +title: Overview +--- + +import Screenshot from "visualci-gallery-docusaurus/Screenshot"; + +One screenshot, in the reader's light or dark mode, linked to the full-size original. + + +``` + +[VitePress](/docs/gallery/vitepress/), with the plugin and the theme as for a gallery (the theme registers `` too): + + +```md +# Overview + +One screenshot, in the reader's light or dark mode, linked to the full-size original. + + +``` + +[MkDocs](/docs/gallery/mkdocs/), a `visualci-screenshot` fenced block in any page: + + +````md +# Overview + +One screenshot, in the reader's light or dark mode, linked to the full-size original. + +```visualci-screenshot +manifest: https://app.visualci.com/g/acme/web.json +screen: overview +link: true +``` +```` + +## In your own code + +The libraries have two functions that take a parsed manifest and the options below, and return a string: + +- `screenshot` returns the HTML. +- `screenshotMarkdown` (`screenshot_markdown` in Ruby, Python and Rust) returns Markdown for a README: `![alt](url)`, or `[![alt](url)](url)` with `link`. When the screen has a dark shot it returns the HTML ``, which GitHub and most Markdown renderers show as it is. + +Both raise an error when an option is invalid or the screen has no shot for what's asked. A script that writes your README when the build passes can call `screenshotMarkdown` with the manifest it fetched. For a screen with no dark shot, it returns: + + +```md +![Billing](https://app.visualci.com/g/acme/web/billing-light.png) +``` + +and for one with a dark shot: + + +```html + + +Overview + +``` + +A Markdown image shows at the file's own size, so a README that wants a smaller picture uses `thumb`, or a screen taken at a smaller width. + +## Options + +- `screen` (required): the screen's key, as the gallery's `screens` and `order` name it: `overview`, `ios/sessions`. +- `group`: the group it's in. Default: the first group that has the screen. +- `theme`: the theme to show, such as `light`. Default: the screen's first, with its dark shot for readers whose setting is dark. When you set it, only that theme's shot is shown. +- `size`: the size to show, such as `phone`. Default: the screen's first that has the theme. +- `alt`: the image's alt text. Default: the screen's title, made from its key. +- `link`: link the image to its full-size original. Default false. +- `thumb`: show the manifest's small copy, where every image shown has one. Default false. +- `loading`: `lazy` (the default) or `eager`, for a screenshot near the top of the page. +- `dimensions` and `groups`: as the gallery's [options](/docs/gallery/options/) of the same names, so the screen's shots pair the same way they do in your gallery. + +Shots that only come as 2x files are shown at half their size, with the 2x file for sharp screens. diff --git a/frontend/content/docs/gallery/vitepress.md b/frontend/content/docs/gallery/vitepress.md index 22e0abf9e..76614f949 100644 --- a/frontend/content/docs/gallery/vitepress.md +++ b/frontend/content/docs/gallery/vitepress.md @@ -131,7 +131,7 @@ The gallery follows VitePress's own light and dark toggle. ## When the manifest can't be read -The plugin tries three times, 20 seconds each, then fails the build with an error that names the URL. It also fails when the manifest has nothing to show, and a page fails when an option is invalid. The site you have keeps serving its last build until VisualCI answers again. +The plugin tries three times, 20 seconds each, then fails the build with an error that names the URL. A page fails when its gallery has nothing to show or an option is invalid. The site you have keeps serving its last build until VisualCI answers again. ## Pinning the version diff --git a/frontend/src/docs/nav.ts b/frontend/src/docs/nav.ts index 52644d6b1..b7deae775 100644 --- a/frontend/src/docs/nav.ts +++ b/frontend/src/docs/nav.ts @@ -29,7 +29,7 @@ export const docsSections: DocsSection[] = [ }, { title: 'Public gallery', - slugs: ['gallery', 'gallery/js', 'gallery/astro', 'gallery/react', 'gallery/docusaurus', 'gallery/vitepress', 'gallery/mkdocs', 'gallery/hugo', 'gallery/ruby', 'gallery/python', 'gallery/rust', 'gallery/options', 'gallery/without-ci'], + slugs: ['gallery', 'gallery/js', 'gallery/astro', 'gallery/react', 'gallery/docusaurus', 'gallery/vitepress', 'gallery/mkdocs', 'gallery/hugo', 'gallery/ruby', 'gallery/python', 'gallery/rust', 'gallery/screenshot', 'gallery/options', 'gallery/without-ci'], }, { title: 'Reference', slugs: ['reference/cli', 'reference/config', 'reference/api', 'reference/access', 'reference/credits', 'self-hosting', 'self-hosting/environment-variables', 'support'] }, ] diff --git a/plugin/skills/visualci-gallery/SKILL.md b/plugin/skills/visualci-gallery/SKILL.md index edcf81cf5..05598dc60 100644 --- a/plugin/skills/visualci-gallery/SKILL.md +++ b/plugin/skills/visualci-gallery/SKILL.md @@ -31,6 +31,8 @@ A gallery library turns the manifest into a screenshots page: a tab for each gro They all render the same HTML, take the same [options](https://visualci.com/docs/gallery/options.md), and take your site's look through CSS variables. A page built at deploy time fails its build when the manifest can't be read, so it never ships without its screenshots. +For one screenshot in a page or a README, in the reader's light or dark mode, see [One screenshot](https://visualci.com/docs/gallery/screenshot.md). + To set one up from a prompt, an agent with VisualCI's MCP server loads the `visualci-gallery` skill with `get_skill`, or reads this page's Markdown copy. The steps, for any stack: From d474b7f4dd5a332eb64624926f46781cd6c66f39 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 10:54:23 +0000 Subject: [PATCH 09/11] Hugo gallery: a visualci-screenshot shortcode and partial, with an example page; the framework check opens each site's overview page (sc-9561) --- clients/gallery/hugo/README.md | 3 + .../hugo/examples/site/content/overview.md | 7 + .../visualci-gallery/screenshot-find.html | 8 ++ .../visualci-gallery/screenshot-html.html | 13 ++ .../visualci-gallery/screenshot-markdown.html | 14 ++ .../visualci-gallery/screenshot-pick.html | 12 ++ .../visualci-gallery/screenshot-srcset.html | 4 + .../visualci-gallery/screenshot.html | 126 ++++++++++++++++++ .../_partials/visualci-screenshot.html | 39 ++++++ .../_shortcodes/visualci-screenshot.html | 12 ++ clients/gallery/hugo/tests/layouts/home.html | 21 +++ frontend/content/docs/gallery/hugo.md | 4 + frontend/content/docs/gallery/screenshot.md | 13 ++ scripts/screenshots/gallery-frameworks.mjs | 27 +++- 14 files changed, 297 insertions(+), 6 deletions(-) create mode 100644 clients/gallery/hugo/examples/site/content/overview.md create mode 100644 clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-find.html create mode 100644 clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-html.html create mode 100644 clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-markdown.html create mode 100644 clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-pick.html create mode 100644 clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-srcset.html create mode 100644 clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot.html create mode 100644 clients/gallery/hugo/layouts/_partials/visualci-screenshot.html create mode 100644 clients/gallery/hugo/layouts/_shortcodes/visualci-screenshot.html diff --git a/clients/gallery/hugo/README.md b/clients/gallery/hugo/README.md index aa9f5ed2f..abf7500cd 100644 --- a/clients/gallery/hugo/README.md +++ b/clients/gallery/hugo/README.md @@ -7,6 +7,9 @@ script and stylesheet (this module's version, from jsDelivr when the site builds fingerprinted) bring it to life. A manifest that can't be read, or has nothing to show, and invalid options fail the build. Needs Hugo 0.146 or later. +For one screenshot, in the reader's light or dark mode, `{{< visualci-screenshot screen="overview" ... >}}` and the +`visualci-screenshot.html` partial ([One screenshot](https://visualci.com/docs/gallery/screenshot/)). + ```sh hugo mod get github.com/DocSpring/visualci/clients/gallery/hugo@v0.4.0 ``` diff --git a/clients/gallery/hugo/examples/site/content/overview.md b/clients/gallery/hugo/examples/site/content/overview.md new file mode 100644 index 000000000..c71c26149 --- /dev/null +++ b/clients/gallery/hugo/examples/site/content/overview.md @@ -0,0 +1,7 @@ +--- +title: Overview +--- + +One screenshot, in the reader's light or dark mode, linked to the full-size original. + +{{< visualci-screenshot manifest="https://app.visualci.com/g/acme/web.json" screen="overview" link=true >}} diff --git a/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-find.html b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-find.html new file mode 100644 index 000000000..c6098282a --- /dev/null +++ b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-find.html @@ -0,0 +1,8 @@ +{{- /* The screen's variant with exactly the values in .choice for every dimension in .order, or nil. */ -}} +{{- $found := index dict "none" -}} +{{- range $v := .variants -}} + {{- $match := true -}} + {{- range $k := $.order }}{{ if ne (index $v.values $k) (index $.choice $k) }}{{ $match = false }}{{ end }}{{ end -}} + {{- if $match }}{{ $found = $v }}{{ break }}{{ end -}} +{{- end -}} +{{- return $found -}} diff --git a/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-html.html b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-html.html new file mode 100644 index 000000000..6f98c845e --- /dev/null +++ b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-html.html @@ -0,0 +1,13 @@ +{{- /* A screenshot (. is screenshot.html's shown) as HTML: an , or a with the dark shot. */ -}} +{{- $e := "visualci-gallery/escape.html" -}} +{{- $l := .light -}} +{{- $srcset := cond (ne $l.src2x nil) (printf ` srcset="%s"` (partial "visualci-gallery/screenshot-srcset.html" $l)) "" -}} +{{- $img := printf `%s` (partial $e $l.src) $srcset $l.width $l.height (partial $e .alt) .loading -}} +{{- $open := cond .link (printf `` (partial $e .href)) "" -}} +{{- $close := cond .link "" "" -}} +{{- $out := printf "%s%s%s\n" $open $img $close -}} +{{- with .dark -}} + {{- $source := printf `` (partial "visualci-gallery/screenshot-srcset.html" .) .width .height -}} + {{- $out = printf "%s\n%s\n%s\n%s\n" $open $source $img $close -}} +{{- end -}} +{{- return $out -}} diff --git a/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-markdown.html b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-markdown.html new file mode 100644 index 000000000..c5cfc6d3c --- /dev/null +++ b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-markdown.html @@ -0,0 +1,14 @@ +{{- /* A screenshot (. is screenshot.html's shown) for a README: Markdown's ![alt](url), linked when asked, or the HTML + when it has a dark shot. Markdown's backslash escapes every ASCII punctuation character in the alt, and the +characters that would end a URL, start an escape or an entity in it. */ -}} +{{- $out := "" -}} +{{- if .dark -}} + {{- $out = partial "visualci-gallery/screenshot-html.html" . -}} +{{- else -}} + {{- $alt := replaceRE "([!-/:-@\\[-`{-~])" `\$1` .alt -}} + {{- $url := `([\\()&])` -}} + {{- $out = printf "![%s](%s)" $alt (replaceRE $url `\$1` .light.src) -}} + {{- if .link }}{{ $out = printf "[%s](%s)" $out (replaceRE $url `\$1` .href) }}{{ end -}} + {{- $out = printf "%s\n" $out -}} +{{- end -}} +{{- return $out -}} diff --git a/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-pick.html b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-pick.html new file mode 100644 index 000000000..d4ebd0084 --- /dev/null +++ b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-pick.html @@ -0,0 +1,12 @@ +{{- /* The image a screenshot shows of variant .v: its small copy when .thumb, else its URL with its 2x copy's (nil when +it has none or it's the same file), and its size. */ -}} +{{- $v := .v -}} +{{- $out := dict -}} +{{- if .thumb -}} + {{- $out = dict "src" $v.thumb.url "src2x" nil "width" $v.thumb.width "height" $v.thumb.height -}} +{{- else -}} + {{- $src2x := index dict "none" -}} + {{- if and (ne $v.url2x nil) (ne $v.url2x $v.url) }}{{ $src2x = $v.url2x }}{{ end -}} + {{- $out = dict "src" $v.url "src2x" $src2x "width" $v.width "height" $v.height -}} +{{- end -}} +{{- return $out -}} diff --git a/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-srcset.html b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-srcset.html new file mode 100644 index 000000000..0729cf81f --- /dev/null +++ b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot-srcset.html @@ -0,0 +1,4 @@ +{{- /* An image's URL with its 2x copy's, as a srcset. */ -}} +{{- $out := partial "visualci-gallery/escape.html" .src -}} +{{- if ne .src2x nil }}{{ $out = printf "%s, %s 2x" $out (partial "visualci-gallery/escape.html" .src2x) }}{{ end -}} +{{- return $out -}} diff --git a/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot.html b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot.html new file mode 100644 index 000000000..c3e797027 --- /dev/null +++ b/clients/gallery/hugo/layouts/_partials/visualci-gallery/screenshot.html @@ -0,0 +1,126 @@ +{{- /* One screenshot (contract/SPEC.md, "A single screenshot"): {shown} or {error}, the first problem's message. .manifest +(parsed), .options (a map in the contract's spelling: screen, group, theme, size, alt, link, thumb, loading, dimensions, +groups). A port of the JS library's screenshot.ts. shown is {light, dark (or nil), href, link, alt, loading}, light and +dark each {src, src2x (or nil), width, height}. */ -}} +{{- $m := .manifest -}} +{{- $o := .options -}} +{{- $kind := "visualci-gallery/kind.html" -}} +{{- $err := partial "visualci-gallery/check-manifest.html" $m -}} +{{- if and (not $err) (ne (partial $kind $o) "map") }}{{ $err = "screenshot options must be an object" }}{{ end -}} +{{- $dims := slice -}} +{{- if not $err -}} + {{- $dv := index $o "dimensions" -}} + {{- if and (ne $dv nil) (not (partial "visualci-gallery/check-dimensions.html" $dv)) -}} + {{- $err = "gallery option dimensions is invalid" -}} + {{- else -}} + {{- $dims = partial "visualci-gallery/resolve-dimensions.html" $dv -}} + {{- end -}} +{{- end -}} +{{- $screen := "" -}} +{{- if not $err -}} + {{- $screen = index $o "screen" -}} + {{- if or (ne (partial $kind $screen) "string") (eq $screen "") }}{{ $err = "screenshot option screen is required" }}{{ end -}} +{{- end -}} +{{- if not $err -}} + {{- $keys := dict -}} + {{- range $dims }}{{ $ks := slice }}{{ range .values }}{{ $ks = $ks | append .key }}{{ end }}{{ $keys = merge $keys (dict .key $ks) }}{{ end -}} + {{- range $name := slice "group" "theme" "size" "alt" "link" "thumb" "loading" -}} + {{- $v := index $o $name -}} + {{- if eq $v nil }}{{ continue }}{{ end -}} + {{- $k := partial $kind $v -}} + {{- $ok := false -}} + {{- if in (slice "group" "alt") $name }}{{ $ok = eq $k "string" -}} + {{- else if in (slice "theme" "size") $name }}{{ $ok = and (eq $k "string") (in (index $keys $name) $v) -}} + {{- else if in (slice "link" "thumb") $name }}{{ $ok = eq $k "bool" -}} + {{- else }}{{ $ok = and (eq $k "string") (in (slice "lazy" "eager") $v) }}{{ end -}} + {{- if not $ok }}{{ $err = printf "screenshot option %s is invalid" $name }}{{ break }}{{ end -}} + {{- end -}} +{{- end -}} +{{- $group := dict -}} +{{- $items := slice -}} +{{- if not $err -}} + {{- $want := index $o "group" -}} + {{- $found := false -}} + {{- range $g := $m.groups -}} + {{- if and (ne $want nil) (ne $g.name $want) }}{{ continue }}{{ end -}} + {{- $mine := slice -}} + {{- range $g.items -}} + {{- if eq (partial "visualci-gallery/parse-shot.html" (dict "name" .name "dims" $dims)).key $screen }}{{ $mine = $mine | append . }}{{ end -}} + {{- end -}} + {{- if ne $want nil -}} + {{- $found = true -}} + {{- if not $mine }}{{ $err = printf "gallery group %s has no screen %s" $g.name $screen }}{{ end -}} + {{- $group = $g -}}{{- $items = $mine -}} + {{- break -}} + {{- end -}} + {{- if $mine }}{{ $found = true }}{{ $group = $g }}{{ $items = $mine }}{{ break }}{{ end -}} + {{- end -}} + {{- if not $found -}} + {{- if ne $want nil }}{{ $err = printf "the gallery manifest has no group %s" $want }}{{ else }}{{ $err = printf "the gallery manifest has no screen %s" $screen }}{{ end -}} + {{- end -}} +{{- end -}} +{{- $out := dict -}} +{{- if not $err -}} + {{- /* When every item is a 2x shot, a 1x copy of each follows them: the 2x shots at half their size. */ -}} + {{- $all2x := true -}} + {{- range $items }}{{ if not (partial "visualci-gallery/parse-shot.html" (dict "name" .name "dims" $dims)).x2 }}{{ $all2x = false }}{{ end }}{{ end -}} + {{- if $all2x -}} + {{- $halves := slice -}} + {{- range $items -}} + {{- $w := int .width -}} + {{- $h := int .height -}} + {{- $hw := div (add $w 1) 2 -}} + {{- $hh := div (add (mul 2 $h $hw) $w) (mul 2 $w) -}} + {{- $name := replaceRE `-2x\z` "" (replaceRE `\.([pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\z` "" .name) -}} + {{- $halves = $halves | append (dict "name" $name "url" .url "width" $hw "height" $hh "thumb" (index . "thumb")) -}} + {{- end -}} + {{- $items = $items | append $halves -}} + {{- end -}} + {{- $opts := dict -}} + {{- range $k := slice "dimensions" "groups" }}{{ if ne (index $o $k) nil }}{{ $opts = merge $opts (dict $k (index $o $k)) }}{{ end }}{{ end -}} + {{- $one := dict "groups" (slice (dict "name" $group.name "title" (index $group "title") "items" $items)) -}} + {{- $r := partial "visualci-gallery/model.html" (dict "manifest" $one "options" $opts) -}} + {{- $err = $r.error -}} + {{- if not $err -}} + {{- $sc := index (index $r.model.groups 0).screens 0 -}} + {{- $order := slice -}} + {{- range $r.model.dimensions }}{{ $order = $order | append .key }}{{ end -}} + {{- /* The values shown: each dimension's option, else the first value of the screen's first variant that has the + values chosen so far. */ -}} + {{- $choice := dict -}} + {{- range $k := $order -}} + {{- $asked := cond (in (slice "theme" "size") $k) (index $o $k) nil -}} + {{- if ne $asked nil }}{{ $choice = merge $choice (dict $k $asked) }}{{ continue }}{{ end -}} + {{- $fits := index $sc.variants 0 -}} + {{- range $v := $sc.variants -}} + {{- $match := true -}} + {{- range $c, $x := $choice }}{{ if ne (index $v.values $c) $x }}{{ $match = false }}{{ end }}{{ end -}} + {{- if $match }}{{ $fits = $v }}{{ break }}{{ end -}} + {{- end -}} + {{- $choice = merge $choice (dict $k (index $fits.values $k)) -}} + {{- end -}} + {{- $v := partial "visualci-gallery/screenshot-find.html" (dict "variants" $sc.variants "order" $order "choice" $choice) -}} + {{- if not $v -}} + {{- $named := slice -}} + {{- range $order }}{{ $named = $named | append (index $choice .) }}{{ end -}} + {{- $err = printf "gallery screen %s in group %s has no %s screenshot" $screen $group.name (delimit $named " ") -}} + {{- else -}} + {{- /* The dark shot, for readers whose setting is dark, when no theme was asked for; not when it's the same image. */ -}} + {{- $dv := index dict "none" -}} + {{- if and (eq (index $o "theme") nil) (ne $choice.theme "dark") -}} + {{- $found := partial "visualci-gallery/screenshot-find.html" (dict "variants" $sc.variants "order" $order "choice" (merge $choice (dict "theme" "dark"))) -}} + {{- if and $found (or (ne $found.url $v.url) (ne $found.url2x $v.url2x)) }}{{ $dv = $found }}{{ end -}} + {{- end -}} + {{- /* The small copies only when every image shown has one, so light and dark readers see the same size. */ -}} + {{- $thumb := and (eq (index $o "thumb") true) (ne $v.thumb nil) (or (not $dv) (ne $dv.thumb nil)) -}} + {{- $alt := cond (ne (index $o "alt") nil) (index $o "alt") $sc.title -}} + {{- $alt = strings.TrimSuffix " " (strings.TrimPrefix " " (replaceRE `[\t\n\r ]+` " " $alt)) -}} + {{- $dark := index dict "none" -}} + {{- with $dv }}{{ $dark = partial "visualci-gallery/screenshot-pick.html" (dict "v" . "thumb" $thumb) }}{{ end -}} + {{- $out = dict "light" (partial "visualci-gallery/screenshot-pick.html" (dict "v" $v "thumb" $thumb)) "dark" $dark "href" $v.url "link" (eq (index $o "link") true) "alt" $alt "loading" (index $o "loading" | default "lazy") -}} + {{- end -}} + {{- end -}} +{{- end -}} +{{- $result := dict "shown" $out -}} +{{- if $err }}{{ $result = dict "error" $err }}{{ end -}} +{{- return $result -}} diff --git a/clients/gallery/hugo/layouts/_partials/visualci-screenshot.html b/clients/gallery/hugo/layouts/_partials/visualci-screenshot.html new file mode 100644 index 000000000..46c49a4c8 --- /dev/null +++ b/clients/gallery/hugo/layouts/_partials/visualci-screenshot.html @@ -0,0 +1,39 @@ +{{- /* One screenshot from a VisualCI gallery, rendered when the site builds: an , or a that shows the dark +shot to readers whose setting is dark. + + {{ partial "visualci-screenshot.html" (dict "manifest" "https://app.visualci.com/g/acme/web.json" "screen" "overview" "link" true) }} + +"manifest" is the gallery manifest's URL (or a manifest already parsed), "markdown" true gives Markdown for a README in +place of HTML, and every other key a screenshot option in the contract's spelling: screen (required), group, theme, +size, alt, link, thumb, loading, dimensions, groups. A manifest that can't be read, a screen it doesn't have and invalid +options fail the build. It needs no script or stylesheet. */ -}} +{{- $where := .where -}} +{{- if not $where }}{{ $where = "a template" }}{{ with .page }}{{ $where = .RelPermalink }}{{ end }}{{ end -}} +{{- $known := slice "screen" "group" "theme" "size" "alt" "link" "thumb" "loading" "dimensions" "groups" -}} +{{- $options := dict -}} +{{- $err := "" -}} +{{- range $k, $v := . -}} + {{- if in (slice "page" "manifest" "where" "markdown") $k }}{{ continue }}{{ end -}} + {{- if not (in $known $k) }}{{ $err = printf "unknown option %s (the options are %s)" $k (delimit $known ", ") }}{{ break }}{{ end -}} + {{- $options = merge $options (dict $k $v) -}} +{{- end -}} +{{- $manifest := .manifest -}} +{{- if $err -}} +{{- else if eq (printf "%T" $manifest) "string" -}} + {{- $read := partial "visualci-gallery/fetch.html" $manifest -}} + {{- $err = $read.error -}} + {{- $manifest = $read.manifest -}} +{{- else if eq $manifest nil -}} + {{- $err = "the screenshot needs a manifest: its URL, https://app.visualci.com/g//.json" -}} +{{- end -}} +{{- $out := "" -}} +{{- if not $err -}} + {{- $r := partial "visualci-gallery/screenshot.html" (dict "manifest" $manifest "options" $options) -}} + {{- $err = $r.error -}} + {{- if not $err }}{{ $out = partial (cond (eq .markdown true) "visualci-gallery/screenshot-markdown.html" "visualci-gallery/screenshot-html.html") $r.shown }}{{ end -}} +{{- end -}} +{{- if $err -}} + {{- errorf "visualci-screenshot in %s: %s" $where $err -}} +{{- else -}} + {{- $out | safeHTML -}} +{{- end -}} diff --git a/clients/gallery/hugo/layouts/_shortcodes/visualci-screenshot.html b/clients/gallery/hugo/layouts/_shortcodes/visualci-screenshot.html new file mode 100644 index 000000000..3ff98df3a --- /dev/null +++ b/clients/gallery/hugo/layouts/_shortcodes/visualci-screenshot.html @@ -0,0 +1,12 @@ +{{- /* {{< visualci-screenshot manifest="https://app.visualci.com/g/acme/web.json" screen="overview" link=true >}} + +One screenshot from the gallery's manifest, in the reader's light or dark mode. Options in the contract's spelling +(screen, group, theme, size, alt, link, thumb, loading); the partial visualci-screenshot.html takes dimensions and +groups too. An invalid option, or a screen the manifest doesn't have, fails the build. */ -}} +{{- if not .IsNamedParams -}} + {{- errorf "visualci-screenshot in %s: %s" .Position `its parameters need names: manifest="https://app.visualci.com/g//.json" screen="overview"` -}} +{{- else -}} + {{- $args := dict -}} + {{- range $k, $v := .Params }}{{ $args = merge $args (dict $k $v) }}{{ end -}} + {{- partial "visualci-screenshot.html" (merge $args (dict "page" .Page "where" (string .Position))) -}} +{{- end -}} diff --git a/clients/gallery/hugo/tests/layouts/home.html b/clients/gallery/hugo/tests/layouts/home.html index 5840a14a4..8d82196a3 100644 --- a/clients/gallery/hugo/tests/layouts/home.html +++ b/clients/gallery/hugo/tests/layouts/home.html @@ -83,5 +83,26 @@ {{- $got := partial "visualci-gallery/check-names.html" .options -}} {{- if ne $got .want }}{{ $fails = $fails | append (printf "names %v: want %q, got %q" .options .want $got) }}{{ end -}} {{- end -}} +{{- /* One screenshot: every case's options give exactly its .html and .md, and every error's options are refused with +its message (contract/screenshots). */ -}} +{{- $shots := transform.Unmarshal (resources.Get "contract/screenshots/manifest.json") -}} +{{- range $res := resources.Match "contract/screenshots/cases/*.json" -}} + {{- $count = add $count 1 -}} + {{- $r := partial "visualci-gallery/screenshot.html" (dict "manifest" $shots "options" (transform.Unmarshal .)) -}} + {{- with $r.error }}{{ $fails = $fails | append (printf "%s: refused: %s" $res.Name .) }}{{ else -}} + {{- range $ext, $p := dict "html" "visualci-gallery/screenshot-html.html" "md" "visualci-gallery/screenshot-markdown.html" -}} + {{- $want := (resources.Get (replace $res.Name ".json" (printf ".%s" $ext))).Content -}} + {{- $got := partial $p $r.shown -}} + {{- if ne $got $want }}{{ $fails = $fails | append (printf "%s (%s) differs\n%s" $res.Name $ext (partial "first-difference.html" (dict "want" $want "got" $got))) }}{{ end -}} + {{- end -}} + {{- end -}} +{{- end -}} +{{- range resources.Match "contract/screenshots/errors/*.json" -}} + {{- $count = add $count 1 -}} + {{- $options := cond (eq (trim .Content " \n") "null") nil (transform.Unmarshal .) -}} + {{- $r := partial "visualci-gallery/screenshot.html" (dict "manifest" $shots "options" $options) -}} + {{- $want := strings.TrimSuffix "\n" (resources.Get (replace .Name ".json" ".message")).Content -}} + {{- if ne $r.error $want }}{{ $fails = $fails | append (printf "%s: want %q, got %q" .Name $want (string $r.error)) }}{{ end -}} +{{- end -}} {{- range $fails }}{{ errorf "%s" . }}{{ end -}} {{- printf "%d checked, %d failed\n" $count (len $fails) -}} diff --git a/frontend/content/docs/gallery/hugo.md b/frontend/content/docs/gallery/hugo.md index 78f34a7c8..2b39f3f67 100644 --- a/frontend/content/docs/gallery/hugo.md +++ b/frontend/content/docs/gallery/hugo.md @@ -92,6 +92,10 @@ The `visualci-gallery.html` partial takes the page, `manifest` and the options i `manifest` can also be a manifest you've already read, from your site's data files for one. +## One screenshot + +The `visualci-screenshot` shortcode shows one screen from the same manifest, in the reader's light or dark mode, with no script or stylesheet. See [One screenshot](/docs/gallery/screenshot/) for its options and the partial. + ## Theming Set the `--vg-*` variables to your site's tokens, and the gallery's colours follow its light and dark mode. Declare `color-scheme` for each mode too: the gallery's other colours follow it. From the example site's `static/site.css`: diff --git a/frontend/content/docs/gallery/screenshot.md b/frontend/content/docs/gallery/screenshot.md index 3b01b08c4..3e61578d6 100644 --- a/frontend/content/docs/gallery/screenshot.md +++ b/frontend/content/docs/gallery/screenshot.md @@ -92,6 +92,19 @@ link: true ``` ```` +[Hugo](/docs/gallery/hugo/), a `visualci-screenshot` shortcode in any page (or the `visualci-screenshot.html` partial in a template, which takes `markdown: true` for Markdown): + + +```md +--- +title: Overview +--- + +One screenshot, in the reader's light or dark mode, linked to the full-size original. + +{{< visualci-screenshot manifest="https://app.visualci.com/g/acme/web.json" screen="overview" link=true >}} +``` + ## In your own code The libraries have two functions that take a parsed manifest and the options below, and return a string: diff --git a/scripts/screenshots/gallery-frameworks.mjs b/scripts/screenshots/gallery-frameworks.mjs index 3cc76a946..fd5b3eee4 100644 --- a/scripts/screenshots/gallery-frameworks.mjs +++ b/scripts/screenshots/gallery-frameworks.mjs @@ -3,7 +3,8 @@ // (the contract's fleetlayer fixture as its manifest), served, and checked in Chromium. The page hydrates with no console // error (a React or Vue hydration mismatch logs one), the gallery's switches and full-size view work, a client-side // navigation to another page hydrates its gallery (a plain link's page load, on Hugo's static site), and a gallery with -// the theme switch off follows the site's own light and dark toggle. +// the theme switch off follows the site's own light and dark toggle. The overview page shows one screenshot, a linked +// with its dark shot. // Then the tour page's shots, at 1440 and 390 px wide, light and dark, as `gallery-frameworks//-.png`. // // node gallery-frameworks.mjs [--out out/shots] [--only next,docusaurus,vitepress,mkdocs,hugo] @@ -98,14 +99,14 @@ const SITES = { dir: join(gallery, 'react/examples/next'), build: (dir) => run(join(dir, 'node_modules/.bin/next'), ['build'], dir), start: (dir, port) => spawn(join(dir, 'node_modules/.bin/next'), ['start', '-p', String(port)], { cwd: dir, stdio: 'ignore' }), - pages: { gallery: '/screenshots', tour: '/tour', app: '/app' }, + pages: { gallery: '/screenshots', tour: '/tour', app: '/app', screenshot: '/overview' }, toggle: '#theme-toggle', }, docusaurus: { dir: join(gallery, 'docusaurus/examples/site'), build: (dir) => run(join(dir, 'node_modules/.bin/docusaurus'), ['build'], dir), root: 'build', - pages: { gallery: '/docs/screenshots', tour: '/docs/tour', app: '/docs/app' }, + pages: { gallery: '/docs/screenshots', tour: '/docs/tour', app: '/docs/app', screenshot: '/docs/overview' }, // Docusaurus 3.10 cycles system, light, dark. toggle: 'button[aria-label*="dark and light mode"]', }, @@ -113,7 +114,7 @@ const SITES = { dir: join(gallery, 'vitepress/examples/site'), build: (dir) => run(join(dir, 'node_modules/.bin/vitepress'), ['build'], dir), root: '.vitepress/dist', - pages: { gallery: '/screenshots', tour: '/tour', app: '/app' }, + pages: { gallery: '/screenshots', tour: '/tour', app: '/app', screenshot: '/overview' }, toggle: '.VPNavBar button.VPSwitchAppearance', }, mkdocs: { @@ -121,14 +122,14 @@ const SITES = { // Material's instant navigation treats only the sitemap's URLs, made from site_url, as the site's own pages. build: (dir, base) => run(process.env.GALLERY_PYTHON || 'python3', ['-c', MKDOCS_BUILD, fixture], dir, { ...process.env, SITE_URL: `${base}/` }), root: 'site', - pages: { gallery: '/screenshots/', tour: '/tour/', app: '/app/' }, + pages: { gallery: '/screenshots/', tour: '/tour/', app: '/app/', screenshot: '/overview/' }, toggle: 'form[data-md-component="palette"] label:not([hidden])', }, hugo: { dir: join(gallery, 'hugo/examples/site'), build: buildHugo, root: 'public', - pages: { gallery: '/screenshots/', tour: '/tour/', app: '/app/' }, + pages: { gallery: '/screenshots/', tour: '/tour/', app: '/app/', screenshot: '/overview/' }, toggle: '#theme-toggle', // A static site: a link loads the next page, whose gallery hydrates on load. reloads: true, @@ -221,6 +222,20 @@ async function check(browser, name, base, sizes) { .then(() => true, () => false) } if (!changed) fail(`the gallery stayed ${before} when the site's toggle switched theme`) + + // One screenshot (the Screenshot component, or MkDocs's and Hugo's block): a with the dark shot, linked to + // the full-size original, its image loaded. + await page.goto(base + site.pages.screenshot) + await page.waitForLoadState('networkidle') + const shot = await page.$$eval('a > picture', (pictures) => + pictures.map((p) => { + const img = p.querySelector('img') + img.loading = 'eager' + return { source: !!p.querySelector('source[media="(prefers-color-scheme: dark)"]'), href: p.parentElement.getAttribute('href'), src: img.getAttribute('src') } + }), + ) + if (shot.length !== 1 || !shot[0].source || shot[0].href !== shot[0].src) fail(`the overview page should show one linked with a dark source, not ${JSON.stringify(shot)}`) + await page.waitForFunction(() => document.querySelector('a > picture img')?.naturalWidth > 0, null, { timeout: 15000 }).catch(() => fail("the overview page's screenshot didn't load")) if (errors.length) fail('console errors on the pages') await ctx.close() } From bef7e772811239611829465f44cae1b99d310648 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 14:13:42 +0000 Subject: [PATCH 10/11] Gallery 0.4.1: every package, the examples and the guides (sc-9561) --- clients/gallery/astro/package.json | 2 +- clients/gallery/docusaurus/package.json | 2 +- clients/gallery/hugo/README.md | 2 +- clients/gallery/hugo/examples/site/go.mod | 2 +- .../_partials/visualci-gallery/version.html | 2 +- clients/gallery/js/examples/cdn/index.html | 4 ++-- clients/gallery/js/package.json | 2 +- clients/gallery/python/pyproject.toml | 2 +- clients/gallery/react/package.json | 2 +- clients/gallery/ruby/examples/rack/Gemfile | 2 +- .../gallery/ruby/examples/rack/Gemfile.lock | 4 ++-- clients/gallery/ruby/examples/rails/Gemfile | 2 +- .../gallery/ruby/examples/rails/Gemfile.lock | 4 ++-- .../ruby/examples/rails/Gemfile.sprockets | 2 +- .../examples/rails/Gemfile.sprockets.lock | 4 ++-- .../ruby/lib/visualci/gallery/version.rb | 2 +- clients/gallery/rust/Cargo.lock | 2 +- clients/gallery/rust/Cargo.toml | 2 +- clients/gallery/rust/examples/loco/Cargo.lock | 2 +- clients/gallery/rust/examples/loco/Cargo.toml | 2 +- .../examples/loco/templates/screenshots.html | 4 ++-- .../rust/examples/loco/tests/screenshots.rs | 4 ++-- clients/gallery/rust/examples/plain.rs | 4 ++-- clients/gallery/rust/templates/home.html | 4 ++-- .../gallery/rust/templates/screenshots.html | 4 ++-- clients/gallery/rust/tests/examples.rs | 4 ++-- clients/gallery/vitepress/package.json | 2 +- frontend/content/docs/gallery/astro.md | 6 ++--- frontend/content/docs/gallery/docusaurus.md | 4 ++-- frontend/content/docs/gallery/hugo.md | 4 ++-- frontend/content/docs/gallery/js.md | 12 +++++----- frontend/content/docs/gallery/mkdocs.md | 4 ++-- frontend/content/docs/gallery/python.md | 4 ++-- frontend/content/docs/gallery/react.md | 6 ++--- frontend/content/docs/gallery/ruby.md | 6 ++--- frontend/content/docs/gallery/rust.md | 24 +++++++++---------- frontend/content/docs/gallery/vitepress.md | 4 ++-- 37 files changed, 74 insertions(+), 74 deletions(-) diff --git a/clients/gallery/astro/package.json b/clients/gallery/astro/package.json index 61336210e..1f6972482 100644 --- a/clients/gallery/astro/package.json +++ b/clients/gallery/astro/package.json @@ -1,6 +1,6 @@ { "name": "visualci-astro-gallery", - "version": "0.4.0", + "version": "0.4.1", "description": "An Astro component for a screenshots page from VisualCI's public gallery: rendered at build time, hydrated by visualci-gallery.", "keywords": [ "astro-component", diff --git a/clients/gallery/docusaurus/package.json b/clients/gallery/docusaurus/package.json index b7e3ac08e..0a9a63fad 100644 --- a/clients/gallery/docusaurus/package.json +++ b/clients/gallery/docusaurus/package.json @@ -1,6 +1,6 @@ { "name": "visualci-gallery-docusaurus", - "version": "0.4.0", + "version": "0.4.1", "description": "A Docusaurus plugin and component for a screenshots page from VisualCI's public gallery: the manifest is read when the site builds, the gallery rendered into each page's HTML and hydrated by visualci-gallery.", "keywords": [ "docusaurus", diff --git a/clients/gallery/hugo/README.md b/clients/gallery/hugo/README.md index abf7500cd..c8951c543 100644 --- a/clients/gallery/hugo/README.md +++ b/clients/gallery/hugo/README.md @@ -11,7 +11,7 @@ For one screenshot, in the reader's light or dark mode, `{{< visualci-screenshot `visualci-screenshot.html` partial ([One screenshot](https://visualci.com/docs/gallery/screenshot/)). ```sh -hugo mod get github.com/DocSpring/visualci/clients/gallery/hugo@v0.4.0 +hugo mod get github.com/DocSpring/visualci/clients/gallery/hugo@v0.4.1 ``` ```toml diff --git a/clients/gallery/hugo/examples/site/go.mod b/clients/gallery/hugo/examples/site/go.mod index 6ae022340..c7fa4def1 100644 --- a/clients/gallery/hugo/examples/site/go.mod +++ b/clients/gallery/hugo/examples/site/go.mod @@ -2,4 +2,4 @@ module acme.example/site go 1.22 -require github.com/DocSpring/visualci/clients/gallery/hugo v0.4.0 +require github.com/DocSpring/visualci/clients/gallery/hugo v0.4.1 diff --git a/clients/gallery/hugo/layouts/_partials/visualci-gallery/version.html b/clients/gallery/hugo/layouts/_partials/visualci-gallery/version.html index ae423215d..ba170ba58 100644 --- a/clients/gallery/hugo/layouts/_partials/visualci-gallery/version.html +++ b/clients/gallery/hugo/layouts/_partials/visualci-gallery/version.html @@ -1,3 +1,3 @@ {{- /* The visualci-gallery release this module renders for: its script and stylesheet come from this version. Bumped with every gallery package (../README.md, "Releasing"). */ -}} -{{- return "0.4.0" -}} +{{- return "0.4.1" -}} diff --git a/clients/gallery/js/examples/cdn/index.html b/clients/gallery/js/examples/cdn/index.html index d43a5dd3e..446881051 100644 --- a/clients/gallery/js/examples/cdn/index.html +++ b/clients/gallery/js/examples/cdn/index.html @@ -3,11 +3,11 @@ Screenshots - +
- + + diff --git a/clients/gallery/rust/examples/loco/tests/screenshots.rs b/clients/gallery/rust/examples/loco/tests/screenshots.rs index aa2468029..2e2432f2a 100644 --- a/clients/gallery/rust/examples/loco/tests/screenshots.rs +++ b/clients/gallery/rust/examples/loco/tests/screenshots.rs @@ -74,10 +74,10 @@ async fn serves_the_screenshots_page() { let gallery = render(&manifest, &Options::default().heading_level(1)).unwrap(); let at = html.find(&gallery).unwrap_or_else(|| panic!("the gallery isn't in the page:\n{html}")); assert!(html[..at].contains( - r#""# + r#""# )); assert!(html[at..].contains(concat!( - r#""#, + r#""#, "\n", r#""#, ))); diff --git a/clients/gallery/rust/examples/plain.rs b/clients/gallery/rust/examples/plain.rs index 09620b2ea..c0e272a9c 100644 --- a/clients/gallery/rust/examples/plain.rs +++ b/clients/gallery/rust/examples/plain.rs @@ -21,10 +21,10 @@ pub fn page(manifest_url: &str) -> Result { Screenshots - + -{gallery} +{gallery} diff --git a/clients/gallery/rust/templates/home.html b/clients/gallery/rust/templates/home.html index 23a3a32d2..6c9ea1cff 100644 --- a/clients/gallery/rust/templates/home.html +++ b/clients/gallery/rust/templates/home.html @@ -4,7 +4,7 @@ Home - +
@@ -12,7 +12,7 @@

Acme

Everything your team needs, in one place.

{{ band }}
- + diff --git a/clients/gallery/rust/templates/screenshots.html b/clients/gallery/rust/templates/screenshots.html index 79184cbaf..ab6e6b8e8 100644 --- a/clients/gallery/rust/templates/screenshots.html +++ b/clients/gallery/rust/templates/screenshots.html @@ -4,7 +4,7 @@ Screenshots - + {# region: theme #}