diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a37d4c4..ca2c9443 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -456,6 +456,9 @@ jobs: # Its wheel carries the library's built script and stylesheet. - run: bin/assets && python3.14 -m pip install --quiet build && python3.14 -m build --wheel && unzip -l dist/*.whl | grep -q visualci_gallery/static/visualci_gallery/visualci_gallery.js working-directory: clients/gallery/python + # The gallery's Rust renderer (its own workspace): the contract's golden fixtures, Askama included, and clippy. + - run: cargo test --locked --all-features && cargo clippy --locked --all-features --all-targets -- -D warnings + working-directory: clients/gallery/rust # The Compare two PDFs page runs crates/visualci-wasm in the browser (scripts/wasm.mjs builds it). - run: rustup target add wasm32-unknown-unknown # Compile cache (kache, as Cargo's rustc wrapper): the R2 bucket every machine shares (KACHE_BUCKET), else the diff --git a/.github/workflows/release-gallery-crate.yml b/.github/workflows/release-gallery-crate.yml new file mode 100644 index 00000000..d6f754d8 --- /dev/null +++ b/.github/workflows/release-gallery-crate.yml @@ -0,0 +1,39 @@ +# Publish the visualci-gallery crate (clients/gallery/rust) to crates.io. Runs for a gallery-rust-v* tag (matching the +# version in its Cargo.toml) or by hand. crates.io's trusted publishing (OIDC from this workflow) works only for a crate +# that already exists, so the first publish uses a temporary token in the CRATES_IO_TOKEN secret (kept in 1Password as +# visualci-crates-io-publish-token, Nathan's Tasks sc-9327). After that, trusted publishing is set up for this workflow, +# the secret is deleted and the token revoked; without the secret, the workflow publishes through OIDC. +name: Release gallery crate + +on: + push: + tags: ["gallery-rust-v*"] + workflow_dispatch: + +permissions: + contents: read + id-token: write + +jobs: + publish: + runs-on: ubuntu-latest + timeout-minutes: 15 + env: + CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }} + defaults: + run: + working-directory: clients/gallery/rust + steps: + - uses: actions/checkout@v4 + - name: The tag matches the crate's version + if: startsWith(github.ref, 'refs/tags/gallery-rust-v') + run: | + version=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[0].version') + test "gallery-rust-v$version" = "$GITHUB_REF_NAME" || { echo "tag $GITHUB_REF_NAME, crate $version"; exit 1; } + - run: cargo test --locked --all-features + - id: oidc + if: env.CRATES_IO_TOKEN == '' + uses: rust-lang/crates-io-auth-action@v1 + - run: cargo publish --locked + env: + CARGO_REGISTRY_TOKEN: ${{ env.CRATES_IO_TOKEN || steps.oidc.outputs.token }} diff --git a/clients/gallery/README.md b/clients/gallery/README.md index 2a647e54..15054a02 100644 --- a/clients/gallery/README.md +++ b/clients/gallery/README.md @@ -12,6 +12,6 @@ variables. pipeline. - [`python/`](python/README.md): the `visualci-gallery` package, standard library only, with the library's files for Django's static files. +- [`rust/`](rust/README.md): the `visualci-gallery` crate, from plain Rust or an Askama template. -A pnpm workspace: `pnpm install && pnpm build && pnpm test` here. Coming: the Rust crate, emitting the contract's -markup for the JS library to hydrate. +The JS packages are a pnpm workspace: `pnpm install && pnpm build && pnpm test` here. diff --git a/clients/gallery/rust/.gitignore b/clients/gallery/rust/.gitignore new file mode 100644 index 00000000..2f7896d1 --- /dev/null +++ b/clients/gallery/rust/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/clients/gallery/rust/Cargo.lock b/clients/gallery/rust/Cargo.lock new file mode 100644 index 00000000..b7074a81 --- /dev/null +++ b/clients/gallery/rust/Cargo.lock @@ -0,0 +1,560 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "askama" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6024d73179f43f15ccd2b881bfea6fee7f3a46ec53f33b52210dea749ebebaa4" +dependencies = [ + "askama_macros", + "itoa", + "percent-encoding", + "serde", + "serde_json", +] + +[[package]] +name = "askama_derive" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071ee5ebf2138e3ad180e0aacf6940c2cab5e6d8333741d9925c7bee2b153f39" +dependencies = [ + "askama_parser", + "basic-toml", + "glob", + "memchr", + "proc-macro2", + "quote", + "rustc-hash", + "serde", + "serde_derive", + "syn", +] + +[[package]] +name = "askama_macros" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643e1c7cbb6aec1d920332fe51a7c0d8219e273dcb8602db03f5263e4d16487b" +dependencies = [ + "askama_derive", +] + +[[package]] +name = "askama_parser" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c5ae75772275d268b03ab8bdccdd12117b6169ee23256942b34e46c9f476583" +dependencies = [ + "rustc-hash", + "serde", + "serde_derive", + "unicode-ident", + "winnow", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "http" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86c8de8f13bac4bb046743409c751e2343621c0293a805c143ede57c5c95c3f8" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "visualci-gallery" +version = "0.1.0" +dependencies = [ + "askama", + "regex", + "serde", + "serde_json", + "ureq", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/clients/gallery/rust/Cargo.toml b/clients/gallery/rust/Cargo.toml new file mode 100644 index 00000000..9d5dc741 --- /dev/null +++ b/clients/gallery/rust/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "visualci-gallery" +version = "0.1.0" +edition = "2024" +rust-version = "1.85" +license = "Apache-2.0" +description = "A screenshots page from VisualCI's public gallery, rendered in Rust (or an Askama template) and hydrated by the visualci-gallery script." +repository = "https://github.com/DocSpring/visualci" +homepage = "https://visualci.com/docs/gallery/" +readme = "README.md" +keywords = ["screenshots", "gallery", "visualci", "askama"] +categories = ["template-engine", "web-programming"] +include = ["src/**", "README.md"] + +# Its own workspace: the repository's root workspace is the CLI and the server. +[workspace] + +[features] +# fetch(): reads the manifest over HTTPS (blocking, with ureq). +fetch = ["dep:ureq"] +# Gallery is safe HTML to Askama: `{{ gallery }}` in a template isn't escaped. +askama = ["dep:askama"] + +[dependencies] +regex = { version = "1.11", default-features = false, features = ["std", "unicode-perl"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +askama = { version = "0.16", optional = true, default-features = false } +ureq = { version = "3", optional = true } + +[dev-dependencies] +askama = { version = "0.16" } diff --git a/clients/gallery/rust/README.md b/clients/gallery/rust/README.md new file mode 100644 index 00000000..4f2d0245 --- /dev/null +++ b/clients/gallery/rust/README.md @@ -0,0 +1,43 @@ +# visualci-gallery (Rust) + +A screenshots page from a VisualCI [public gallery](https://visualci.com/docs/gallery/) manifest, rendered in Rust as +the [gallery contract](https://github.com/DocSpring/visualci/blob/main/clients/gallery/contract/SPEC.md)'s markup. +The markup is byte for byte what the `visualci-gallery` JS library renders, so the library's script hydrates it: tabs, +light and dark, desktop and phone, and the full-size view. + +```rust,no_run +use visualci_gallery::{Gallery, Options}; + +// The manifest a build step wrote: a copy of https://app.visualci.com/g//.json. +let manifest = std::fs::read_to_string("screenshots.json")?; +let gallery = Gallery::from_json(&manifest, &Options::default().title(None))?; +println!("{gallery}"); +# Ok::<(), Box>(()) +``` + +Rendering fails when the manifest has nothing to show or the options are invalid. There is no fallback: read the +manifest when the site builds (a CI step that fails the build if VisualCI can't be read), and render from that copy. +The `fetch` feature adds a blocking `fetch(url, timeout, attempts)` for that step. + +## Askama + +With the `askama` feature (askama 0.16), `Gallery` is safe HTML, so a template writes `{{ gallery }}`: + +```rust,ignore +#[derive(askama::Template)] +#[template(path = "screenshots.html")] +struct Screenshots { gallery: visualci_gallery::Gallery } +``` + +Add the library's stylesheet and script (`visualci-gallery` on npm: `dist/gallery.css` and the ES5 `dist/gallery.iife.js`, +which sets `window.VisualCIGallery`), then +`document.querySelectorAll("[data-vg]").forEach((el) => VisualCIGallery.hydrate(el))`. + +## Options + +`Options::default()` and its setters (`title`, `heading_level`, `id`, `screen`, `order`, `group`, `group_order`, +`credit`, `layout`, `theme_switch`, `see_all`), or `Options::from_json` with the contract's JSON names. + +## Development + +`cargo test --all-features` checks the contract's golden fixtures, refusals and messages. diff --git a/clients/gallery/rust/src/lib.rs b/clients/gallery/rust/src/lib.rs new file mode 100644 index 00000000..092d1a4a --- /dev/null +++ b/clients/gallery/rust/src/lib.rs @@ -0,0 +1,118 @@ +//! A screenshots page from a VisualCI [public gallery](https://visualci.com/docs/gallery/) manifest, rendered in Rust +//! as the gallery contract's markup: byte for byte what the `visualci-gallery` JS library renders, so its script +//! hydrates it (tabs, light and dark, desktop and phone, the full-size view). +//! +//! ```no_run +//! # fn main() -> Result<(), visualci_gallery::Error> { +//! use visualci_gallery::{Gallery, Options}; +//! +//! // The manifest a build step wrote (a copy of https://app.visualci.com/g//.json). +//! let manifest = std::fs::read_to_string("screenshots.json").expect("the build writes it"); +//! let gallery = Gallery::from_json(&manifest, &Options::default().title(None))?; +//! let html = gallery.to_string(); +//! # Ok(()) } +//! ``` +//! +//! There is no fallback: rendering fails when the manifest has nothing to show or the options are invalid, and +//! [`fetch`] (feature `fetch`) fails when the manifest can't be read. Read it when the site builds, fail the build if +//! it can't be, and render from that copy. +//! +//! With the `askama` feature, [`Gallery`] is safe HTML to Askama: a template writes `{{ gallery }}`. + +mod model; +mod render; + +use std::fmt; + +pub use model::{ + DEFAULT_TITLE, Group, Model, Options, SEE_ALL_TEXT, Screen, SeeAll, Shot, Variant, build_model, humanize, + parse_shot, slugify, +}; +pub use render::{escape, render_model}; + +/// Why a gallery can't be shown. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// The manifest or the options are invalid, or nothing in the manifest can be shown. The message is the + /// contract's, word for word (contract/errors/*.message). + Invalid(String), + /// The manifest couldn't be read: "The screenshots gallery couldn't read : ". + Fetch(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Invalid(m) | Error::Fetch(m) => f.write_str(m), + } + } +} + +impl std::error::Error for Error {} + +/// A rendered gallery. Displays as its HTML; with the `askama` feature, Askama doesn't escape it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Gallery { + html: String, +} + +impl Gallery { + /// The gallery for a parsed manifest. + pub fn new(manifest: &serde_json::Value, options: &Options) -> Result { + Ok(Gallery { html: render(manifest, options)? }) + } + + /// The gallery for a manifest's JSON text (a file the build wrote, or `include_str!`). + pub fn from_json(manifest: &str, options: &Options) -> Result { + let value = serde_json::from_str(manifest) + .map_err(|e| Error::Invalid(format!("not a gallery manifest: it isn't JSON ({e})")))?; + Self::new(&value, options) + } + + pub fn as_str(&self) -> &str { + &self.html + } +} + +impl fmt::Display for Gallery { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.html) + } +} + +#[cfg(feature = "askama")] +impl askama::filters::HtmlSafe for Gallery {} + +/// The gallery's HTML for a parsed manifest. +pub fn render(manifest: &serde_json::Value, options: &Options) -> Result { + Ok(render_model(&build_model(manifest, options)?)) +} + +/// The manifest at `url`, parsed: tried `attempts` times, each within `timeout`. Fails, naming the URL, when it can't +/// be read (a network error, a timeout, a status other than 200, JSON that doesn't parse). +#[cfg(feature = "fetch")] +pub fn fetch(url: &str, timeout: std::time::Duration, attempts: u32) -> Result { + let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(timeout)).build().into(); + let attempts = attempts.max(1); + let mut last = String::new(); + for i in 0..attempts { + let result = agent.get(url).call().map_err(|e| match e { + ureq::Error::StatusCode(code) => format!("HTTP {code}"), + e => e.to_string(), + }); + match result.and_then(|mut res| { + if res.status() != 200 { + return Err(format!("HTTP {}", res.status().as_u16())); + } + let text = res.body_mut().read_to_string().map_err(|e| e.to_string())?; + serde_json::from_str(&text).map_err(|e| e.to_string()) + }) { + Ok(v) => return Ok(v), + Err(e) => last = e, + } + if i + 1 < attempts { + std::thread::sleep(std::time::Duration::from_secs(u64::from(i) + 1)); + } + } + Err(Error::Fetch(format!("The screenshots gallery couldn't read {url}: {last}"))) +} diff --git a/clients/gallery/rust/src/model.rs b/clients/gallery/rust/src/model.rs new file mode 100644 index 00000000..9ac0b660 --- /dev/null +++ b/clients/gallery/rust/src/model.rs @@ -0,0 +1,532 @@ +//! The gallery's model from a VisualCI public gallery manifest (contract/SPEC.md): a line-for-line port of the JS +//! library's model.ts, so every renderer gives the same model and markup. + +use std::collections::{HashMap, HashSet}; +use std::sync::LazyLock; + +use regex::Regex; +use serde::Serialize; +use serde_json::{Map, Value}; + +use crate::Error; + +pub const DEFAULT_TITLE: &str = "Screenshots"; +pub const SEE_ALL_TEXT: &str = "See all screenshots"; +const SIZES: [&str; 2] = ["desktop", "phone"]; +const THEMES: [&str; 2] = ["light", "dark"]; + +// 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 = + LazyLock::new(|| Regex::new(r"\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\z").unwrap()); +static WIDTH_THEME: LazyLock = LazyLock::new(|| Regex::new(r"\A([0-9]+)-(light|dark)(-2x)?\z").unwrap()); +static SCREEN_THEME: LazyLock = + LazyLock::new(|| Regex::new(r"\A((?s:.)+?)-(light|dark)(?:-([0-9]+))?(-2x)?\z").unwrap()); +static ABSOLUTE: LazyLock = + LazyLock::new(|| Regex::new(r"\A[hH][tT][tT][pP][sS]?://[^\x00-\x20\x7f]+\z").unwrap()); +static CONTROL: LazyLock = LazyLock::new(|| Regex::new(r"[\x00-\x20\x7f]").unwrap()); +static SCHEME: LazyLock = LazyLock::new(|| Regex::new(r"\A[A-Za-z][A-Za-z0-9+.-]*:").unwrap()); +static ID: LazyLock = LazyLock::new(|| Regex::new(r"\A[A-Za-z][A-Za-z0-9_-]*\z").unwrap()); + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Variant { + pub size: String, + pub theme: String, + pub url: String, + pub url2x: Option, + pub width: u64, + pub height: u64, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Screen { + pub key: String, + pub title: String, + pub caption: Option, + pub variants: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Group { + pub name: String, + pub title: String, + pub slug: String, + pub fit: String, + pub sizes: Vec, + pub screens: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct SeeAll { + pub href: String, + pub text: String, +} + +/// The manifest as the gallery shows it, with the keys of the contract fixtures' model.json. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Model { + pub layout: String, + pub theme_switch: bool, + pub see_all: Option, + pub title: Option, + pub label: String, + pub heading_level: u8, + pub id: String, + pub credit: bool, + pub groups: Vec, +} + +/// How a manifest name pairs (contract/SPEC.md, "A shot's name"). +#[derive(Debug, Clone, PartialEq)] +pub struct Shot { + /// The screen's key: the name without its theme, width and 2x parts. + pub key: String, + /// None when the name says nothing: the shot stands for both themes. + pub theme: Option, + pub size: String, + pub x2: bool, + /// The CSS width the name gives (`-1440`). + pub css_width: Option, +} + +/// `-[-][-2x]`, or `/-[-2x]`. A name in neither shape is a screen of its +/// own, in both themes. Under 768 wide is a phone; with no width, a portrait image is a phone and a landscape one a +/// desktop, unless `size` says. +pub fn parse_shot(name: &str, width: u64, height: u64, size: Option<&str>) -> Shot { + let stripped = EXTENSION.replace(name, ""); + let mut parts: Vec<&str> = stripped.split('/').collect(); + let last = parts.pop().unwrap_or(""); + let folder = parts.join("/"); + // A width too long for u64 is still a desktop's (JS compares the number, which is huge). + let sized = |w: Option<&str>| -> String { + match w { + Some(w) => if w.parse::().is_ok_and(|n| n < 768) { "phone" } else { "desktop" }.to_string(), + None => { + size.map(str::to_string).unwrap_or_else(|| if height > width { "phone" } else { "desktop" }.to_string()) + } + } + }; + let css = |w: Option<&str>| w.and_then(|w| w.parse::().ok()); + + if !folder.is_empty() { + if let Some(m) = WIDTH_THEME.captures(last) { + let w = m.get(1).map(|x| x.as_str()); + return Shot { + key: folder, + theme: Some(m[2].to_string()), + size: sized(w), + x2: m.get(3).is_some(), + css_width: css(w), + }; + } + } + if let Some(m) = SCREEN_THEME.captures(last) { + let key = if folder.is_empty() { m[1].to_string() } else { format!("{folder}/{}", &m[1]) }; + let w = m.get(3).map(|x| x.as_str()); + return Shot { key, theme: Some(m[2].to_string()), size: sized(w), x2: m.get(4).is_some(), css_width: css(w) }; + } + let key = if folder.is_empty() { last.to_string() } else { format!("{folder}/{last}") }; + Shot { key, theme: None, size: sized(None), x2: false, css_width: None } +} + +/// `["billing", "free"]` → "Billing, free". +pub fn humanize(segments: &[&str]) -> String { + static RUNS: LazyLock = LazyLock::new(|| Regex::new(r"[-_]+").unwrap()); + let text = + segments.iter().map(|s| RUNS.replace_all(s, " ").trim_matches(' ').to_string()).collect::>().join(", "); + let mut chars = text.chars(); + match chars.next() { + Some(first) => first.to_uppercase().chain(chars).collect(), + None => text, + } +} + +/// A group's name as an id: ASCII lower case, runs of anything else as one hyphen. +pub fn slugify(name: &str) -> String { + let mut out = String::new(); + let mut dash = false; + for c in name.chars() { + let c = c.to_ascii_lowercase(); + if c.is_ascii_lowercase() || c.is_ascii_digit() { + if dash && !out.is_empty() { + out.push('-'); + } + dash = false; + out.push(c); + } else { + dash = true; + } + } + if out.is_empty() { "group".to_string() } else { out } +} + +fn common_folder(keys: &[&str]) -> usize { + let folders: Vec> = keys + .iter() + .map(|k| { + let mut p: Vec<&str> = k.split('/').collect(); + p.pop(); + p + }) + .collect(); + let Some(first) = folders.first() else { return 0 }; + let mut common = first.len(); + for f in &folders[1..] { + let mut i = 0; + while i < common && i < f.len() && first[i] == f[i] { + i += 1; + } + common = i; + } + common +} + +fn rank(order: &Option>, key: &str) -> usize { + let list = order.as_deref().unwrap_or(&[]); + list.iter().position(|k| k == key).unwrap_or(list.len()) +} + +fn safe_href(value: &str) -> bool { + ABSOLUTE.is_match(value) || (!value.is_empty() && !CONTROL.is_match(value) && !SCHEME.is_match(value)) +} + +fn fail(message: impl Into) -> Result { + Err(Error::Invalid(message.into())) +} + +/// An integer as JSON has it: 1440 or 1440.0 (JavaScript can't tell them apart). +fn integral(v: &Value) -> Option { + let n = v.as_f64()?; + (n.is_finite() && n.fract() == 0.0).then_some(n) +} + +/// The largest width or height (contract/SPEC.md, "Validation"): the density maths stays exact in every language. +pub const MAX_SIZE: u64 = 1_000_000; + +fn size_of(v: Option<&Value>) -> Option { + let n = integral(v?)?; + (n > 0.0 && n <= MAX_SIZE as f64).then_some(n as u64) +} + +/// The manifest's shape (contract/SPEC.md, "Validation"): anything else is refused. +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"); + }; + for (i, g) in groups.iter().enumerate() { + let name = match g.get("name").and_then(Value::as_str) { + Some(n) if g.is_object() && !n.is_empty() => n, + _ => return fail(format!("gallery manifest group {i} has no name")), + }; + if !matches!(g.get("title"), None | Some(Value::Null) | Some(Value::String(_))) { + return fail(format!("gallery manifest group {name}: its title isn't a string")); + } + let Some(items) = g.get("items").and_then(Value::as_array) else { + return fail(format!("gallery manifest group {name} has no items")); + }; + for (j, item) in items.iter().enumerate() { + let place = format!("gallery manifest group {name}, item {j}"); + let iname = match item.get("name").and_then(Value::as_str) { + Some(n) if item.is_object() && !n.is_empty() => n, + _ => return fail(format!("{place} has no name")), + }; + if !item.get("url").and_then(Value::as_str).is_some_and(|u| ABSOLUTE.is_match(u)) { + return fail(format!("{place} ({iname}): its url isn't an http(s) URL")); + } + if size_of(item.get("width")).is_none() || size_of(item.get("height")).is_none() { + return fail(format!( + "{place} ({iname}): its width and height aren't whole numbers from 1 to {MAX_SIZE}" + )); + } + } + } + Ok(()) +} + +/// The options a site can set (contract/SPEC.md, "Input"), as JSON-shaped values so every renderer takes the same +/// ones. Build them with [`Options::default`] and the setters, or [`Options::from_json`]. +#[derive(Debug, Clone, Default)] +pub struct Options { + raw: Map, +} + +impl Options { + /// Options from a JSON object with the contract's names (`headingLevel`, `groupOrder`, `themeSwitch`, `seeAll`). + pub fn from_json(value: &Value) -> Result { + match value { + Value::Object(m) => Ok(Options { raw: m.clone() }), + _ => fail("gallery options must be an object"), + } + } + fn set(mut self, key: &str, value: Value) -> Self { + self.raw.insert(key.to_string(), value); + self + } + /// The gallery's heading and accessible name; `None` keeps the name ("Screenshots") but shows no heading. + pub fn title(self, title: Option<&str>) -> Self { + self.set("title", title.map_or(Value::Null, |t| Value::String(t.into()))) + } + pub fn heading_level(self, level: u8) -> Self { + self.set("headingLevel", level.into()) + } + pub fn id(self, id: &str) -> Self { + self.set("id", id.into()) + } + /// A screen's title and caption, by key (`ios/usage`, `overview`). + pub fn screen(mut self, key: &str, title: Option<&str>, caption: Option<&str>) -> Self { + let screens = self.raw.entry("screens").or_insert_with(|| Value::Object(Map::new())); + if let Value::Object(m) = screens { + m.insert(key.into(), serde_json::json!({ "title": title, "caption": caption })); + } + self + } + pub fn order>(self, keys: &[S]) -> Self { + self.set("order", keys.iter().map(|k| Value::String(k.as_ref().into())).collect()) + } + /// A group's title, the size of its shots whose names give no width, and how its images fit their cards + /// (`"cover"` or `"contain"`). + pub fn group(mut self, name: &str, title: Option<&str>, size: Option<&str>, fit: Option<&str>) -> Self { + let groups = self.raw.entry("groups").or_insert_with(|| Value::Object(Map::new())); + if let Value::Object(m) = groups { + m.insert(name.into(), serde_json::json!({ "title": title, "size": size, "fit": fit })); + } + self + } + pub fn group_order>(self, names: &[S]) -> Self { + self.set("groupOrder", names.iter().map(|k| Value::String(k.as_ref().into())).collect()) + } + pub fn credit(self, on: bool) -> Self { + self.set("credit", on.into()) + } + /// `"grid"` (tabs per group) or `"strip"` (one row that scrolls sideways). + pub fn layout(self, layout: &str) -> Self { + self.set("layout", layout.into()) + } + pub fn theme_switch(self, on: bool) -> Self { + self.set("themeSwitch", on.into()) + } + pub fn see_all(self, href: &str, text: Option<&str>) -> Self { + self.set("seeAll", serde_json::json!({ "href": href, "text": text })) + } + + /// 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> { + match self.raw.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) if check(v) => Ok(Some(v)), + Some(_) => fail(format!("gallery option {key} is invalid")), + } + } +} + +fn texts(keys: &'static [&'static str]) -> impl Fn(&Value) -> bool { + move |v| { + v.as_object().is_some_and(|m| { + m.values().all(|entry| { + entry.as_object().is_some_and(|e| { + e.iter().all(|(k, x)| keys.contains(&k.as_str()) && (x.is_null() || x.is_string())) + }) + }) + }) + } +} + +fn group_options(v: &Value) -> bool { + v.as_object().is_some_and(|m| { + m.values().all(|entry| { + entry.as_object().is_some_and(|e| { + e.iter().all(|(k, x)| match (k.as_str(), x) { + ("title" | "size" | "fit", Value::Null) => true, + ("title", Value::String(_)) => true, + ("size", Value::String(s)) => SIZES.contains(&s.as_str()), + ("fit", Value::String(f)) => f == "cover" || f == "contain", + _ => false, + }) + }) + }) + }) +} + +fn strings(v: &Value) -> bool { + v.as_array().is_some_and(|a| a.iter().all(Value::is_string)) +} + +fn string_list(v: Option<&Value>) -> Option> { + v.map(|v| v.as_array().unwrap().iter().map(|s| s.as_str().unwrap().to_string()).collect()) +} + +fn text_of<'a>(map: Option<&'a Value>, outer: &str, inner: &str) -> Option<&'a str> { + map?.get(outer)?.get(inner)?.as_str() +} + +/// The manifest as the gallery shows it (contract/SPEC.md). Fails when it or the options are invalid, or nothing in +/// it can be shown. +pub fn build_model(manifest: &Value, options: &Options) -> Result { + check_manifest(manifest)?; + let level = options.get("headingLevel", |v| integral(v).is_some())?.and_then(integral).unwrap_or(2.0); + let heading_level = level.clamp(1.0, 4.0) as u8; + let title = if options.raw.contains_key("title") { + options.get("title", Value::is_string)?.and_then(Value::as_str).map(str::to_string) + } else { + Some(DEFAULT_TITLE.to_string()) + }; + let id = options + .get("id", |v| v.as_str().is_some_and(|s| ID.is_match(s)))? + .and_then(Value::as_str) + .unwrap_or("vg") + .to_string(); + let screens_opt = options.get("screens", texts(&["title", "caption"]))?; + let groups_opt = options.get("groups", group_options)?; + let order = string_list(options.get("order", strings)?); + let group_order = string_list(options.get("groupOrder", strings)?); + let credit = options.get("credit", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(true); + let switch = options.get("themeSwitch", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(true); + let layout = options + .get("layout", |v| matches!(v.as_str(), Some("grid" | "strip")))? + .and_then(Value::as_str) + .unwrap_or("grid") + .to_string(); + let see_all = options.get("seeAll", |v| { + v.is_object() + && v.get("href").and_then(Value::as_str).is_some_and(safe_href) + && matches!(v.get("text"), None | Some(Value::Null) | Some(Value::String(_))) + })?; + + let mut slugs = HashSet::new(); + let mut groups: Vec = Vec::new(); + for g in manifest["groups"].as_array().unwrap() { + let gname = g["name"].as_str().unwrap(); + let size_opt = text_of(groups_opt, gname, "size"); + // Screens in the manifest's order, each with its variants in the order they were first filed. + let mut keys: Vec = Vec::new(); + let mut found: HashMap> = HashMap::new(); + for item in g["items"].as_array().unwrap() { + let (w, h) = (size_of(item.get("width")).unwrap(), size_of(item.get("height")).unwrap()); + let url = item["url"].as_str().unwrap(); + let shot = parse_shot(item["name"].as_str().unwrap(), w, h, size_opt); + let variants = found.entry(shot.key.clone()).or_insert_with(|| { + keys.push(shot.key.clone()); + Vec::new() + }); + let themes: Vec<&str> = match &shot.theme { + Some(t) => vec![t.as_str()], + None => THEMES.to_vec(), + }; + for theme in themes { + let at = match variants.iter().position(|v| v.size == shot.size && v.theme == theme) { + Some(i) => i, + None => { + variants.push(Variant { + size: shot.size.clone(), + theme: theme.into(), + url: String::new(), + url2x: None, + width: 0, + height: 0, + }); + variants.len() - 1 + } + }; + let v = &mut variants[at]; + if shot.x2 { + if v.url2x.is_none() { + v.url2x = Some(url.into()); + } + } else if v.url.is_empty() { + // An image wider than the width its name gives was taken at a higher density: shown at the + // name's width, its height rounded half up in integers (the same in every language). + match shot.css_width { + Some(cw) if w > cw => { + let height = (2 * h as u128 * cw as u128 + w as u128) / (2 * w as u128); + (v.url, v.width, v.height) = (url.into(), cw, height as u64); + } + _ => (v.url, v.width, v.height) = (url.into(), w, h), + } + } + } + } + // The screens that have something to show; titles are made from these keys only. + let mut kept: Vec<(String, Vec)> = Vec::new(); + for key in keys { + let mut variants: Vec = + found.remove(&key).unwrap().into_iter().filter(|v| !v.url.is_empty()).collect(); + variants + .sort_by_key(|v| (SIZES.iter().position(|s| *s == v.size), THEMES.iter().position(|t| *t == v.theme))); + if !variants.is_empty() { + kept.push((key, variants)); + } + } + // A screen shows both themes at each of its sizes: one theme's image never stands in for the other's. + for (key, variants) in &kept { + for v in variants { + if !variants.iter().any(|o| o.size == v.size && o.theme != v.theme) { + let other = if v.theme == "light" { "dark" } else { "light" }; + return fail(format!( + "gallery screen {key} in group {gname} has a {} {} screenshot but no {other} one", + v.theme, v.size + )); + } + } + } + if kept.is_empty() { + continue; + } + let prefix = common_folder(&kept.iter().map(|(k, _)| k.as_str()).collect::>()); + let mut list: Vec = kept + .into_iter() + .map(|(key, variants)| { + let set = screens_opt.and_then(|m| m.get(&key)); + let title = + set.and_then(|s| s.get("title")).and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| { + let parts: Vec<&str> = key.split('/').skip(prefix).collect(); + humanize(&parts) + }); + let caption = set.and_then(|s| s.get("caption")).and_then(Value::as_str).map(str::to_string); + Screen { key, title, caption, variants } + }) + .collect(); + // Rust compares strings by code point, as the contract does. + list.sort_by(|a, b| rank(&order, &a.key).cmp(&rank(&order, &b.key)).then_with(|| a.key.cmp(&b.key))); + + let base = slugify(gname); + let mut slug = base.clone(); + let mut n = 2; + while slugs.contains(&slug) { + slug = format!("{base}-{n}"); + n += 1; + } + slugs.insert(slug.clone()); + let title = text_of(groups_opt, gname, "title") + .or_else(|| g.get("title").and_then(Value::as_str)) + .unwrap_or(gname) + .to_string(); + let sizes = SIZES + .iter() + .filter(|s| list.iter().any(|sc| sc.variants.iter().any(|v| v.size == **s))) + .map(|s| s.to_string()) + .collect(); + let fit = text_of(groups_opt, gname, "fit").unwrap_or("cover").to_string(); + groups.push(Group { name: gname.into(), title, slug, fit, sizes, screens: list }); + } + if groups.is_empty() { + return fail("the gallery manifest has no screenshots to show"); + } + // Named groups first; the rest keep the manifest's order (the sort is stable). + groups.sort_by_key(|g| rank(&group_order, &g.name)); + + Ok(Model { + theme_switch: layout == "grid" && switch, + layout, + see_all: see_all.map(|v| SeeAll { + href: v["href"].as_str().unwrap().into(), + text: v.get("text").and_then(Value::as_str).unwrap_or(SEE_ALL_TEXT).into(), + }), + label: title.clone().unwrap_or_else(|| DEFAULT_TITLE.into()), + title, + heading_level, + id, + credit, + groups, + }) +} diff --git a/clients/gallery/rust/src/render.rs b/clients/gallery/rust/src/render.rs new file mode 100644 index 00000000..3d5a1836 --- /dev/null +++ b/clients/gallery/rust/src/render.rs @@ -0,0 +1,205 @@ +//! The gallery's HTML from its model: the markup every renderer emits byte for byte (contract/SPEC.md, "The +//! markup"), a line-for-line port of the JS library's render.ts. + +use crate::model::{Model, Screen, Variant}; + +/// & < > " ' as entities: the only escaping the contract allows, so every language's output is the same. +pub fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => out.push(c), + } + } + out +} + +fn size_label(size: &str) -> &'static str { + if size == "phone" { "Phone" } else { "Desktop" } +} + +fn theme_switch() -> String { + concat!( + r#"
"#, + r#""#, + r#""#, + "
" + ) + .to_string() +} + +fn size_switch(sizes: &[&str], extra: &str) -> String { + let buttons: String = sizes + .iter() + .map(|s| { + format!(r#""#, size_label(s)) + }) + .collect(); + format!(r#"
{buttons}
"#) +} + +fn image(title: &str, v: &Variant, themes: &[&str]) -> String { + let alt = format!("{title}, {}, {}", size_label(&v.size).to_lowercase(), themes.join(" and ")); + let x2 = v.url2x.as_deref().map(|u| format!(r#" data-src-2x="{}""#, escape(u))).unwrap_or_default(); + format!( + r#"{}"#, + v.size, + themes.join(" "), + escape(&v.url), + v.width, + v.height, + escape(&alt) + ) +} + +fn card(sc: &Screen, sizes: &[String], heading: &str, caption: bool, fit: &str) -> String { + let mut imgs = String::new(); + let mut shown: Vec<&str> = Vec::new(); + let mut first: Option<&Variant> = None; + for size in sizes { + let at: Vec<&Variant> = sc.variants.iter().filter(|v| &v.size == size).collect(); + if at.is_empty() { + continue; + } + shown.push(size); + first.get_or_insert(at[0]); + // Every size has both themes (the model refuses a screen without); the same image for both is shown once. + if at[0].url == at[1].url && at[0].url2x == at[1].url2x { + imgs.push_str(&image(&sc.title, at[0], &["light", "dark"])); + } else { + for v in &at { + imgs.push_str(&image(&sc.title, v, &[v.theme.as_str()])); + } + } + } + let first = first.expect("a screen has a variant at one of its sizes"); + let fit = if fit == "contain" { r#" data-vg-fit="contain""# } else { "" }; + let caption = match (&sc.caption, caption) { + (Some(c), true) => format!(r#"

{}

"#, escape(c)), + _ => String::new(), + }; + format!( + r#"
  • {imgs}<{heading} class="vg-card-title">{}{caption}
  • "#, + escape(&sc.key), + shown.join(" "), + escape(&first.url), + escape(&sc.title), + escape(&sc.title) + ) +} + +/// Every screen of every group at one size (desktop when any group has it) in one row. +fn strip_size(model: &Model) -> &'static str { + if model.groups.iter().any(|g| g.sizes.iter().any(|s| s == "desktop")) { "desktop" } else { "phone" } +} + +fn grid(model: &Model, id: &str, gh: &str, ch: &str, out: &mut Vec) { + let tabs = model.groups.len() > 1; + if tabs { + out.push(format!(r#"
    "#, escape(&model.label))); + for (i, g) in model.groups.iter().enumerate() { + out.push(format!( + r#""#, + i == 0, + if i == 0 { 0 } else { -1 }, + escape(&g.name), + slug = g.slug + )); + } + out.push("
    ".into()); + } + for (i, g) in model.groups.iter().enumerate() { + let role = + if tabs { format!(r#" role="tabpanel" aria-labelledby="{id}-tab-{}""#, g.slug) } else { String::new() }; + let hidden = if i > 0 { " hidden" } else { "" }; + out.push(format!( + r#"
    "#, + g.slug, + g.sizes.join(" ") + )); + let mut controls = if model.theme_switch { theme_switch() } else { String::new() }; + if g.sizes.len() > 1 { + controls.push_str(&size_switch(&g.sizes.iter().map(String::as_str).collect::>(), "")); + } + let controls = + if controls.is_empty() { controls } else { format!(r#"
    {controls}
    "#) }; + out.push(format!( + r#"
    <{gh} class="vg-group-title">{}{controls}
    "#, + escape(&g.title) + )); + out.push(r#"
      "#.into()); + for sc in &g.screens { + out.push(card(sc, &g.sizes, ch, true, &g.fit)); + } + out.push("
    ".into()); + out.push("
    ".into()); + } +} + +fn strip(model: &Model, id: &str, ch: &str, out: &mut Vec) { + let size = strip_size(model); + out.push(format!(r#"
    "#)); + out.push(r#"
    "#.into()); + out.push(r#"
      "#.into()); + let sizes = [size.to_string()]; + for g in &model.groups { + for sc in &g.screens { + if sc.variants.iter().any(|v| v.size == size) { + out.push(card(sc, &sizes, ch, false, &g.fit)); + } + } + } + out.push("
    ".into()); + out.push(r#"
    "#.into()); + out.push("
    ".into()); +} + +/// The gallery's markup: one line per block, no indentation, "\n" after each line. +pub fn render_model(model: &Model) -> String { + let id = escape(&model.id); + let h = |offset: u8| format!("h{}", (model.heading_level + offset).min(6)); + let below = if model.title.is_none() { 0 } else { 1 }; + let mut out: Vec = Vec::new(); + + // The size shown before the script runs: the first panel's (only it shows without the script). + let size = if model.layout == "strip" { strip_size(model).to_string() } else { model.groups[0].sizes[0].clone() }; + let source = if model.theme_switch { "" } else { r#" data-vg-theme-source="page""# }; + out.push(format!( + r#"
    "#, + model.layout, + escape(&model.label) + )); + if let Some(title) = &model.title { + out.push(format!(r#"<{h} class="vg-title">{}"#, escape(title), h = h(0))); + } + if model.layout == "strip" { + strip(model, &id, &h(below), &mut out); + } else { + grid(model, &id, &h(below), &h(below + 1), &mut out); + } + if let Some(see) = &model.see_all { + out.push(format!(r#"

    {}

    "#, escape(&see.href), escape(&see.text))); + } + if model.credit { + out.push( + r#"

    Screenshot Gallery Powered by VisualCI.com

    "# + .into(), + ); + } + out.push(format!(r#""#)); + let hb = h(below); + out.push(format!( + r#"
    <{hb} class="vg-box-title" id="{id}-box-title">
    {}{}
    "#, + if model.theme_switch { theme_switch() } else { String::new() }, + if model.layout == "grid" { size_switch(&["desktop", "phone"], " vg-box-sizes") } else { String::new() }, + )); + out.push(r#"
    "#.into()); + out.push("
    ".into()); + out.push("
    ".into()); + out.join("\n") + "\n" +} diff --git a/clients/gallery/rust/tests/contract.rs b/clients/gallery/rust/tests/contract.rs new file mode 100644 index 00000000..436f6513 --- /dev/null +++ b/clients/gallery/rust/tests/contract.rs @@ -0,0 +1,114 @@ +//! The gallery contract's golden fixtures (../contract): every fixture's manifest and options give exactly its +//! model.json and gallery.html, and every manifest in errors/ and option in option-errors/ is refused with the +//! message in its .message file. + +use std::fs; +use std::path::{Path, PathBuf}; + +use serde_json::Value; +use visualci_gallery::{Error, Gallery, Options, build_model, render}; + +fn contract() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../contract") +} + +fn read(path: &Path) -> Value { + serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap() +} + +fn listed(dir: &Path, ext: &str) -> Vec { + let mut v: Vec = fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| ext.is_empty() && p.is_dir() || p.extension().is_some_and(|x| x == ext)) + .collect(); + v.sort(); + assert!(!v.is_empty(), "nothing in {}", dir.display()); + v +} + +#[test] +fn fixtures() { + for dir in listed(&contract().join("fixtures"), "") { + let manifest = read(&dir.join("manifest.json")); + let options = Options::from_json(&read(&dir.join("options.json"))).unwrap(); + let model = build_model(&manifest, &options).unwrap_or_else(|e| panic!("{}: {e}", dir.display())); + assert_eq!(read(&dir.join("model.json")), serde_json::to_value(&model).unwrap(), "{}", dir.display()); + assert_eq!( + fs::read_to_string(dir.join("gallery.html")).unwrap(), + render(&manifest, &options).unwrap(), + "{}", + dir.display() + ); + } +} + +fn message(path: &Path) -> String { + fs::read_to_string(path.with_extension("message")).unwrap() +} + +#[test] +fn refuses_manifests() { + for path in listed(&contract().join("errors"), "json") { + match render(&read(&path), &Options::default()) { + Err(Error::Invalid(m)) => assert_eq!(message(&path), format!("{m}\n"), "{}", path.display()), + other => panic!("{}: {other:?}", path.display()), + } + } +} + +#[test] +fn refuses_options() { + let manifest = read(&contract().join("fixtures/visualci/manifest.json")); + for path in listed(&contract().join("option-errors"), "json") { + let options = Options::from_json(&read(&path)).unwrap(); + match render(&manifest, &options) { + Err(Error::Invalid(m)) => assert_eq!(message(&path), format!("{m}\n"), "{}", path.display()), + other => panic!("{}: {other:?}", path.display()), + } + } +} + +#[test] +fn builder_matches_json_options() { + let dir = contract().join("fixtures/fleetlayer"); + let manifest = read(&dir.join("manifest.json")); + let from_json = Options::from_json(&read(&dir.join("options.json"))).unwrap(); + let built = Options::default() + .title(None) + .screen( + "overview", + Some("Overview"), + Some("What needs you, every machine with its sessions, and the newest events."), + ) + .screen("access", Some("Access"), Some("Requests waiting for your approval.")) + .screen("pages-edit-preview", Some("The preview"), None) + .screen("ios/sessions", Some("Sessions"), Some("Every session on every machine.")) + .order(&["overview", "access", "ios/sessions", "ios/approval"]) + .group("Mac approver", None, Some("desktop"), Some("contain")); + assert_eq!(render(&manifest, &from_json).unwrap(), render(&manifest, &built).unwrap()); +} + +#[test] +fn gallery_displays_its_html() { + let dir = contract().join("fixtures/single-group"); + let options = Options::from_json(&read(&dir.join("options.json"))).unwrap(); + let gallery = Gallery::from_json(&fs::read_to_string(dir.join("manifest.json")).unwrap(), &options).unwrap(); + assert_eq!(fs::read_to_string(dir.join("gallery.html")).unwrap(), gallery.to_string()); +} + +#[cfg(feature = "askama")] +#[test] +fn askama_doesnt_escape_it() { + use askama::Template; + #[derive(Template)] + #[template(source = "
    {{ gallery }}
    ", ext = "html")] + struct Page { + gallery: Gallery, + } + let dir = contract().join("fixtures/single-group"); + let options = Options::from_json(&read(&dir.join("options.json"))).unwrap(); + let gallery = Gallery::new(&read(&dir.join("manifest.json")), &options).unwrap(); + let html = Page { gallery: gallery.clone() }.render().unwrap(); + assert_eq!(format!("
    {gallery}
    "), html); +}