diff --git a/clients/gallery/astro/README.md b/clients/gallery/astro/README.md index 5f72dc1ee..1a2c8519b 100644 --- a/clients/gallery/astro/README.md +++ b/clients/gallery/astro/README.md @@ -21,7 +21,9 @@ import Gallery from "visualci-astro-gallery"; The props are `visualci-gallery`'s options (`title`, `headingLevel`, `id`, `screens`, `order`, `groups`, `groupOrder`, `credit`, `layout`, `themeSwitch`, `seeAll`, `preload`, `deepLinks`, `text`) and `load()`'s (`manifest`, `timeout`, `attempts`, -`fetch`). Give the gallery your site's look with the `--vg-*` CSS variables, set on `.vg` or any element around it. +`fetch`). `` (`import { Screenshot } from "visualci-astro-gallery"`) +shows one screenshot in the reader's light or dark mode ([One screenshot](https://visualci.com/docs/gallery/screenshot/)). +Give the gallery your site's look with the `--vg-*` CSS variables, set on `.vg` or any element around it. They win over the component's defaults in any stylesheet order: ```css 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..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", @@ -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..7d95fad42 --- /dev/null +++ b/clients/gallery/astro/src/Screenshot.astro @@ -0,0 +1,24 @@ +--- +// 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 parsed = await loadManifest({ manifest, timeout, attempts, fetch }); +let html: string; +try { + html = screenshot(parsed, options); +} catch (e) { + throw new Error(`The screenshot can't show ${manifest}: ${e instanceof Error ? e.message : String(e)}`); +} +--- + + 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..da39a93fb --- /dev/null +++ b/clients/gallery/astro/test/screenshot.test.ts @@ -0,0 +1,35 @@ +// 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( + `The screenshot can't show ${MANIFEST}: gallery screen billing in group Web has no dark desktop screenshot`, + ); + }); +}); diff --git a/clients/gallery/contract/screenshots/cases/float-2x.html b/clients/gallery/contract/screenshots/cases/float-2x.html new file mode 100644 index 000000000..6186752c2 --- /dev/null +++ b/clients/gallery/contract/screenshots/cases/float-2x.html @@ -0,0 +1,4 @@ + + +Float + diff --git a/clients/gallery/contract/screenshots/cases/float-2x.json b/clients/gallery/contract/screenshots/cases/float-2x.json new file mode 100644 index 000000000..c25ac2328 --- /dev/null +++ b/clients/gallery/contract/screenshots/cases/float-2x.json @@ -0,0 +1 @@ +{"screen": "float"} diff --git a/clients/gallery/contract/screenshots/cases/float-2x.md b/clients/gallery/contract/screenshots/cases/float-2x.md new file mode 100644 index 000000000..6186752c2 --- /dev/null +++ b/clients/gallery/contract/screenshots/cases/float-2x.md @@ -0,0 +1,4 @@ + + +Float + diff --git a/clients/gallery/contract/screenshots/manifest.json b/clients/gallery/contract/screenshots/manifest.json index cdae995ed..239a14a30 100644 --- a/clients/gallery/contract/screenshots/manifest.json +++ b/clients/gallery/contract/screenshots/manifest.json @@ -117,6 +117,18 @@ "width": 1281, "height": 801 }, + { + "name": "float-light-2x", + "url": "https://app.visualci.com/g/acme/web/float-light-2x.png", + "width": 2881.0, + "height": 1801.0 + }, + { + "name": "float-dark-2x", + "url": "https://app.visualci.com/g/acme/web/float-dark-2x.png", + "width": 2881.0, + "height": 1801.0 + }, { "name": "wide-light-390-2x", "url": "https://app.visualci.com/g/acme/web/wide-light-390-2x.png", diff --git a/clients/gallery/docusaurus/README.md b/clients/gallery/docusaurus/README.md index a3483d1ae..9471b8e50 100644 --- a/clients/gallery/docusaurus/README.md +++ b/clients/gallery/docusaurus/README.md @@ -19,8 +19,12 @@ import Gallery from "visualci-gallery-docusaurus/Gallery"; ``` The component's props are the library's options, passed through as they are. The plugin takes `manifests`, `timeout` -and `attempts`, and adds the stylesheet to every page. A manifest that can't be read, or has nothing to show, fails -the build. +and `attempts`, and adds the stylesheet to every page. A manifest that can't be read fails +the build, and so does a page whose gallery has nothing to show. + +`visualci-gallery-docusaurus/Screenshot` shows one screenshot from a manifest the plugin reads, in the reader's light +or dark mode: ``. See +[One screenshot](https://visualci.com/docs/gallery/screenshot/). ## Development 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..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", @@ -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..435e96cea --- /dev/null +++ b/clients/gallery/docusaurus/src/Screenshot.tsx @@ -0,0 +1,37 @@ +// 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; +} + +function shown(manifest: string, run: () => string): string { + try { + return run(); + } catch (e) { + throw new Error(`The screenshot can't show ${manifest}: ${e instanceof Error ? e.message : String(e)}`); + } +} + +export default function Screenshot({ manifest, className, ...options }: ScreenshotProps) { + const data = usePluginData("visualci-gallery-docusaurus") as GlobalData | undefined; + const parsed = data?.manifests[manifest]; + if (parsed === undefined) { + throw new Error(`visualci-gallery-docusaurus: add ${manifest} to the plugin's manifests in docusaurus.config`); + } + return ( + screenshot(parsed, options)) }} + /> + ); +} 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/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 })); }); 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/hugo/README.md b/clients/gallery/hugo/README.md index aa9f5ed2f..c8951c543 100644 --- a/clients/gallery/hugo/README.md +++ b/clients/gallery/hugo/README.md @@ -7,8 +7,11 @@ 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 +hugo mod get github.com/DocSpring/visualci/clients/gallery/hugo@v0.4.1 ``` ```toml 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/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/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-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/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/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 - +
- + ') 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/pyproject.toml b/clients/gallery/python/pyproject.toml index a6de823f1..6519e49e7 100644 --- a/clients/gallery/python/pyproject.toml +++ b/clients/gallery/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "visualci-gallery" -version = "0.4.0" +version = "0.4.1" description = "A screenshots page from VisualCI's public gallery, rendered in Python and hydrated by the visualci-gallery script." readme = "README.md" license = "Apache-2.0" 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): diff --git a/clients/gallery/react/README.md b/clients/gallery/react/README.md index 8461e5ee0..93f32df1f 100644 --- a/clients/gallery/react/README.md +++ b/clients/gallery/react/README.md @@ -19,6 +19,9 @@ Import the stylesheet once, in the root layout: `import "visualci-gallery/galler options and `load()`'s (`manifest`, `timeout`, `attempts`, `fetch`), passed through as they are. A manifest that can't be read, or has nothing to show, throws, so a prerendered page fails the build. +``, also a server component, shows one screenshot in the reader's +light or dark mode, with no script or stylesheet ([One screenshot](https://visualci.com/docs/gallery/screenshot/)). + With HTML rendered elsewhere (`render(await load(options))` from `visualci-gallery/render` in `getStaticProps`, a loader or a build script), use `GalleryMarkup` from `visualci-gallery-react/client`: it hydrates the HTML once it's on the page and lets the gallery go on unmount. 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/package.json b/clients/gallery/react/package.json index 94eb7ab22..9c0e6ef74 100644 --- a/clients/gallery/react/package.json +++ b/clients/gallery/react/package.json @@ -1,6 +1,6 @@ { "name": "visualci-gallery-react", - "version": "0.4.0", + "version": "0.4.1", "description": "React components for a screenshots page from VisualCI's public gallery: rendered on the server (Next.js app router, or any React that renders to HTML), hydrated by visualci-gallery.", "keywords": [ "gallery", 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..36339b944 --- /dev/null +++ b/clients/gallery/react/src/screenshot.tsx @@ -0,0 +1,22 @@ +// 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 }; + +function shown(manifest: string, run: () => string): string { + try { + return run(); + } catch (e) { + throw new Error(`The screenshot can't show ${manifest}: ${e instanceof Error ? e.message : String(e)}`); + } +} + +export async function Screenshot({ manifest, timeout, attempts, fetch, className, ...options }: ScreenshotProps) { + const parsed = await loadManifest({ manifest, timeout, attempts, fetch }); + const html = shown(manifest, () => screenshot(parsed, 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..f6cb0e615 --- /dev/null +++ b/clients/gallery/react/test/screenshot.test.tsx @@ -0,0 +1,49 @@ +// 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( + `The screenshot can't show ${MANIFEST}: gallery screen billing in group Web has no dark desktop screenshot`, + ); + }); +}); diff --git a/clients/gallery/ruby/README.md b/clients/gallery/ruby/README.md index 70bb03f79..f5b3353e9 100644 --- a/clients/gallery/ruby/README.md +++ b/clients/gallery/ruby/README.md @@ -49,6 +49,11 @@ puts the shown tab, open screen and chosen values in the URL's hash), `text` (th `open`, `previous`, `next`, `close`, `back`, `forward`, `credit` and `and`: `{ label: 'Captures', close: 'Fermer' }`). Hash keys may be strings or symbols. +## One screenshot + +`VisualCI::Gallery.screenshot(manifest, screen: 'overview')` returns one screenshot as HTML, an `` or a `` with the dark shot, and the +Markdown function a README's form ([One screenshot](https://visualci.com/docs/gallery/screenshot/)). + ## Development `ruby -Ilib test/gallery_test.rb` checks the contract's golden fixtures. The example apps have their own Gemfiles: diff --git a/clients/gallery/ruby/examples/rack/Gemfile b/clients/gallery/ruby/examples/rack/Gemfile index dfd331aaa..9a434f284 100644 --- a/clients/gallery/ruby/examples/rack/Gemfile +++ b/clients/gallery/ruby/examples/rack/Gemfile @@ -12,7 +12,7 @@ end gem 'rack', '~> 3.1' gem 'rackup', '~> 2.2' gem 'webrick', '~> 1.9' -gem 'visualci-gallery', '~> 0.4.0' +gem 'visualci-gallery', '~> 0.4.1' # endregion: gems gem 'minitest', group: :test diff --git a/clients/gallery/ruby/examples/rack/Gemfile.lock b/clients/gallery/ruby/examples/rack/Gemfile.lock index be7ba354e..35447d06f 100644 --- a/clients/gallery/ruby/examples/rack/Gemfile.lock +++ b/clients/gallery/ruby/examples/rack/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: ../.. specs: - visualci-gallery (0.4.0) + visualci-gallery (0.4.1) GEM remote: https://rubygems.org/ @@ -39,7 +39,7 @@ DEPENDENCIES minitest rack (~> 3.1) rackup (~> 2.2) - visualci-gallery (~> 0.4.0)! + visualci-gallery (~> 0.4.1)! webrick (~> 1.9) BUNDLED WITH diff --git a/clients/gallery/ruby/examples/rails/Gemfile b/clients/gallery/ruby/examples/rails/Gemfile index a0f5ef7b5..6dfb108ca 100644 --- a/clients/gallery/ruby/examples/rails/Gemfile +++ b/clients/gallery/ruby/examples/rails/Gemfile @@ -10,7 +10,7 @@ gem 'railties', '~> 8.1' # The gem from this repository rather than RubyGems, so the tests run the code it ships. path '../..' do # region: install - gem 'visualci-gallery', '~> 0.4.0' + gem 'visualci-gallery', '~> 0.4.1' # endregion: install end diff --git a/clients/gallery/ruby/examples/rails/Gemfile.lock b/clients/gallery/ruby/examples/rails/Gemfile.lock index 3a867b581..ae30ac3d2 100644 --- a/clients/gallery/ruby/examples/rails/Gemfile.lock +++ b/clients/gallery/ruby/examples/rails/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: ../.. specs: - visualci-gallery (0.4.0) + visualci-gallery (0.4.1) GEM remote: https://rubygems.org/ @@ -153,7 +153,7 @@ DEPENDENCIES minitest propshaft (~> 1.3) railties (~> 8.1) - visualci-gallery (~> 0.4.0)! + visualci-gallery (~> 0.4.1)! BUNDLED WITH 2.6.9 diff --git a/clients/gallery/ruby/examples/rails/Gemfile.sprockets b/clients/gallery/ruby/examples/rails/Gemfile.sprockets index ae26870b3..4fa013875 100644 --- a/clients/gallery/ruby/examples/rails/Gemfile.sprockets +++ b/clients/gallery/ruby/examples/rails/Gemfile.sprockets @@ -9,7 +9,7 @@ gem 'railties', '~> 8.1' gem 'sprockets-rails', '~> 3.5' path '../..' do - gem 'visualci-gallery', '~> 0.4.0' + gem 'visualci-gallery', '~> 0.4.1' end gem 'minitest', group: :test diff --git a/clients/gallery/ruby/examples/rails/Gemfile.sprockets.lock b/clients/gallery/ruby/examples/rails/Gemfile.sprockets.lock index 5b833a9d3..21ecfa460 100644 --- a/clients/gallery/ruby/examples/rails/Gemfile.sprockets.lock +++ b/clients/gallery/ruby/examples/rails/Gemfile.sprockets.lock @@ -1,7 +1,7 @@ PATH remote: ../.. specs: - visualci-gallery (0.4.0) + visualci-gallery (0.4.1) GEM remote: https://rubygems.org/ @@ -157,7 +157,7 @@ DEPENDENCIES minitest railties (~> 8.1) sprockets-rails (~> 3.5) - visualci-gallery (~> 0.4.0)! + visualci-gallery (~> 0.4.1)! BUNDLED WITH 2.6.9 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/screenshot.rb b/clients/gallery/ruby/lib/visualci/gallery/screenshot.rb new file mode 100644 index 000000000..cfe16d4b9 --- /dev/null +++ b/clients/gallery/ruby/lib/visualci/gallery/screenshot.rb @@ -0,0 +1,149 @@ +# 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| + # Whole numbers, checked with the manifest, though JSON may write them as 2880.0. + w = item['width'].to_i + width = (w + 1) / 2 + height = ((2 * item['height'].to_i * width) + w) / (2 * w) + { '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'] } } + screen = screen.to_s if screen.is_a?(Symbol) + raise Error, 'screenshot option screen is required' unless screen.is_a?(String) && !screen.empty? + + group = group.to_s if group.is_a?(Symbol) + 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/lib/visualci/gallery/version.rb b/clients/gallery/ruby/lib/visualci/gallery/version.rb index a61dabfdb..04de07896 100644 --- a/clients/gallery/ruby/lib/visualci/gallery/version.rb +++ b/clients/gallery/ruby/lib/visualci/gallery/version.rb @@ -2,6 +2,6 @@ module VisualCI module Gallery - VERSION = '0.4.0' + VERSION = '0.4.1' end end diff --git a/clients/gallery/ruby/test/gallery_test.rb b/clients/gallery/ruby/test/gallery_test.rb index 8392d7063..be83d44b2 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, group: :Web, 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')) diff --git a/clients/gallery/rust/Cargo.lock b/clients/gallery/rust/Cargo.lock index 1051a051f..38f4c5067 100644 --- a/clients/gallery/rust/Cargo.lock +++ b/clients/gallery/rust/Cargo.lock @@ -683,7 +683,7 @@ checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" [[package]] name = "visualci-gallery" -version = "0.4.0" +version = "0.4.1" dependencies = [ "askama", "axum", diff --git a/clients/gallery/rust/Cargo.toml b/clients/gallery/rust/Cargo.toml index 3f4fc60c2..dffdbfd6a 100644 --- a/clients/gallery/rust/Cargo.toml +++ b/clients/gallery/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "visualci-gallery" -version = "0.4.0" +version = "0.4.1" edition = "2024" rust-version = "1.85" license = "Apache-2.0" diff --git a/clients/gallery/rust/README.md b/clients/gallery/rust/README.md index 290b0a55e..29385170b 100644 --- a/clients/gallery/rust/README.md +++ b/clients/gallery/rust/README.md @@ -72,6 +72,11 @@ use visualci_gallery::Options; let options = Options::default().deep_links(true).text("label", "Captures d'écran").text("close", "Fermer"); ``` +## One screenshot + +`screenshot(&manifest, &ScreenshotOptions::new("overview"))` returns one screenshot as HTML, an `` or a `` with the dark shot, and the +Markdown function a README's form ([One screenshot](https://visualci.com/docs/gallery/screenshot/)). + ## Development `cargo test --all-features` checks the contract's golden fixtures, refusals and messages. diff --git a/clients/gallery/rust/examples/loco/Cargo.lock b/clients/gallery/rust/examples/loco/Cargo.lock index f778d967f..dcf4875fa 100644 --- a/clients/gallery/rust/examples/loco/Cargo.lock +++ b/clients/gallery/rust/examples/loco/Cargo.lock @@ -2157,7 +2157,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "visualci-gallery" -version = "0.4.0" +version = "0.4.1" dependencies = [ "askama", "regex", diff --git a/clients/gallery/rust/examples/loco/Cargo.toml b/clients/gallery/rust/examples/loco/Cargo.toml index f9096b96e..8a205168b 100644 --- a/clients/gallery/rust/examples/loco/Cargo.toml +++ b/clients/gallery/rust/examples/loco/Cargo.toml @@ -15,7 +15,7 @@ axum = "0.8" serde = { version = "1", features = ["derive"] } tokio = { version = "1", features = ["rt-multi-thread", "macros"] } # region: dependencies -visualci-gallery = { version = "=0.4.0", features = ["askama", "fetch"] } +visualci-gallery = { version = "=0.4.1", features = ["askama", "fetch"] } askama = "0.16" # endregion: dependencies diff --git a/clients/gallery/rust/examples/loco/templates/screenshots.html b/clients/gallery/rust/examples/loco/templates/screenshots.html index a2a5fbc8e..9830721dc 100644 --- a/clients/gallery/rust/examples/loco/templates/screenshots.html +++ b/clients/gallery/rust/examples/loco/templates/screenshots.html @@ -4,13 +4,13 @@ Screenshots - +
{{ gallery }}
- + 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/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..32d8c062a --- /dev/null +++ b/clients/gallery/rust/src/screenshot.rs @@ -0,0 +1,332 @@ +//! 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| { + // Whole numbers, checked with the manifest, though JSON may write them as 2880.0. + let (w, h) = (item["width"].as_f64().unwrap() as u64, item["height"].as_f64().unwrap() as u64); + 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/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 #}