Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Canvas menu: sharp pictures on 2x and 3x screens

Adarshaeaae3a045ed
diff --git a/public/previews/presets/hd/1024/effect-agamemnon.avif b/public/previews/presets/hd/1024/effect-agamemnon.avif
index 84a1849a..a6f00f70 100644
Binary files a/public/previews/presets/hd/1024/effect-agamemnon.avif and b/public/previews/presets/hd/1024/effect-agamemnon.avif differ
diff --git a/public/previews/presets/hd/1024/effect-agamemnon.jpg b/public/previews/presets/hd/1024/effect-agamemnon.jpg
index 789ea728..51aefa8b 100644
Binary files a/public/previews/presets/hd/1024/effect-agamemnon.jpg and b/public/previews/presets/hd/1024/effect-agamemnon.jpg differ
diff --git a/public/previews/presets/hd/1024/effect-agamemnon.mp4 b/public/previews/presets/hd/1024/effect-agamemnon.mp4
index 154e9f00..cc08a365 100644
Binary files a/public/previews/presets/hd/1024/effect-agamemnon.mp4 and b/public/previews/presets/hd/1024/effect-agamemnon.mp4 differ
diff --git a/public/previews/presets/hd/1024/peak/effect-agamemnon.avif b/public/previews/presets/hd/1024/peak/effect-agamemnon.avif
index 250cb0d5..7cfd72fa 100644
Binary files a/public/previews/presets/hd/1024/peak/effect-agamemnon.avif and b/public/previews/presets/hd/1024/peak/effect-agamemnon.avif differ
diff --git a/public/previews/presets/hd/1024/peak/effect-agamemnon.jpg b/public/previews/presets/hd/1024/peak/effect-agamemnon.jpg
index 154e0d59..7fa074b3 100644
Binary files a/public/previews/presets/hd/1024/peak/effect-agamemnon.jpg and b/public/previews/presets/hd/1024/peak/effect-agamemnon.jpg differ
diff --git a/public/previews/presets/hd/320/effect-agamemnon.avif b/public/previews/presets/hd/320/effect-agamemnon.avif
index f0b3b166..c882eece 100644
Binary files a/public/previews/presets/hd/320/effect-agamemnon.avif and b/public/previews/presets/hd/320/effect-agamemnon.avif differ
diff --git a/public/previews/presets/hd/320/peak/effect-agamemnon.avif b/public/previews/presets/hd/320/peak/effect-agamemnon.avif
index 8544f20c..e28af734 100644
Binary files a/public/previews/presets/hd/320/peak/effect-agamemnon.avif and b/public/previews/presets/hd/320/peak/effect-agamemnon.avif differ
diff --git a/public/previews/presets/hd/640/effect-agamemnon.avif b/public/previews/presets/hd/640/effect-agamemnon.avif
index 21f88c74..aecf2899 100644
Binary files a/public/previews/presets/hd/640/effect-agamemnon.avif and b/public/previews/presets/hd/640/effect-agamemnon.avif differ
diff --git a/public/previews/presets/hd/640/effect-agamemnon.jpg b/public/previews/presets/hd/640/effect-agamemnon.jpg
index 8587b9ed..edc88d91 100644
Binary files a/public/previews/presets/hd/640/effect-agamemnon.jpg and b/public/previews/presets/hd/640/effect-agamemnon.jpg differ
diff --git a/public/previews/presets/hd/640/effect-agamemnon.mp4 b/public/previews/presets/hd/640/effect-agamemnon.mp4
index 27710cc7..eccb5855 100644
Binary files a/public/previews/presets/hd/640/effect-agamemnon.mp4 and b/public/previews/presets/hd/640/effect-agamemnon.mp4 differ
diff --git a/public/previews/presets/hd/640/peak/effect-agamemnon.avif b/public/previews/presets/hd/640/peak/effect-agamemnon.avif
index 6da40e78..f90f731e 100644
Binary files a/public/previews/presets/hd/640/peak/effect-agamemnon.avif and b/public/previews/presets/hd/640/peak/effect-agamemnon.avif differ
diff --git a/public/previews/presets/hd/640/peak/effect-agamemnon.jpg b/public/previews/presets/hd/640/peak/effect-agamemnon.jpg
index 7b033166..75348ad1 100644
Binary files a/public/previews/presets/hd/640/peak/effect-agamemnon.jpg and b/public/previews/presets/hd/640/peak/effect-agamemnon.jpg differ
diff --git a/public/previews/templates/hd/1024/canvas/effect-chain-fallen-angel.avif b/public/previews/templates/hd/1024/canvas/effect-chain-fallen-angel.avif
new file mode 100644
index 00000000..33dd8be7
Binary files /dev/null and b/public/previews/templates/hd/1024/canvas/effect-chain-fallen-angel.avif differ
diff --git a/public/previews/templates/hd/1024/canvas/effect-chain-fallen-angel.jpg b/public/previews/templates/hd/1024/canvas/effect-chain-fallen-angel.jpg
new file mode 100644
index 00000000..deb160c1
Binary files /dev/null and b/public/previews/templates/hd/1024/canvas/effect-chain-fallen-angel.jpg differ
diff --git a/public/previews/templates/hd/1024/canvas/effect-chain-monet-muse.avif b/public/previews/templates/hd/1024/canvas/effect-chain-monet-muse.avif
new file mode 100644
index 00000000..d3a65e41
Binary files /dev/null and b/public/previews/templates/hd/1024/canvas/effect-chain-monet-muse.avif differ
diff --git a/public/previews/templates/hd/1024/canvas/effect-chain-monet-muse.jpg b/public/previews/templates/hd/1024/canvas/effect-chain-monet-muse.jpg
new file mode 100644
index 00000000..5b577214
Binary files /dev/null and b/public/previews/templates/hd/1024/canvas/effect-chain-monet-muse.jpg differ
diff --git a/public/previews/templates/hd/1024/canvas/effect-chain-street-colossus.avif b/public/previews/templates/hd/1024/canvas/effect-chain-street-colossus.avif
new file mode 100644
index 00000000..c39ea402
Binary files /dev/null and b/public/previews/templates/hd/1024/canvas/effect-chain-street-colossus.avif differ
diff --git a/public/previews/templates/hd/1024/canvas/effect-chain-street-colossus.jpg b/public/previews/templates/hd/1024/canvas/effect-chain-street-colossus.jpg
new file mode 100644
index 00000000..85ae26e7
Binary files /dev/null and b/public/previews/templates/hd/1024/canvas/effect-chain-street-colossus.jpg differ
diff --git a/public/previews/templates/hd/320/canvas/effect-chain-fallen-angel.avif b/public/previews/templates/hd/320/canvas/effect-chain-fallen-angel.avif
new file mode 100644
index 00000000..62006987
Binary files /dev/null and b/public/previews/templates/hd/320/canvas/effect-chain-fallen-angel.avif differ
diff --git a/public/previews/templates/hd/320/canvas/effect-chain-monet-muse.avif b/public/previews/templates/hd/320/canvas/effect-chain-monet-muse.avif
new file mode 100644
index 00000000..af72e9c7
Binary files /dev/null and b/public/previews/templates/hd/320/canvas/effect-chain-monet-muse.avif differ
diff --git a/public/previews/templates/hd/320/canvas/effect-chain-street-colossus.avif b/public/previews/templates/hd/320/canvas/effect-chain-street-colossus.avif
new file mode 100644
index 00000000..967bfa97
Binary files /dev/null and b/public/previews/templates/hd/320/canvas/effect-chain-street-colossus.avif differ
diff --git a/public/previews/templates/hd/640/canvas/effect-chain-fallen-angel.avif b/public/previews/templates/hd/640/canvas/effect-chain-fallen-angel.avif
new file mode 100644
index 00000000..85ef8ff5
Binary files /dev/null and b/public/previews/templates/hd/640/canvas/effect-chain-fallen-angel.avif differ
diff --git a/public/previews/templates/hd/640/canvas/effect-chain-fallen-angel.jpg b/public/previews/templates/hd/640/canvas/effect-chain-fallen-angel.jpg
new file mode 100644
index 00000000..7b700b5f
Binary files /dev/null and b/public/previews/templates/hd/640/canvas/effect-chain-fallen-angel.jpg differ
diff --git a/public/previews/templates/hd/640/canvas/effect-chain-monet-muse.avif b/public/previews/templates/hd/640/canvas/effect-chain-monet-muse.avif
new file mode 100644
index 00000000..cbc9925f
Binary files /dev/null and b/public/previews/templates/hd/640/canvas/effect-chain-monet-muse.avif differ
diff --git a/public/previews/templates/hd/640/canvas/effect-chain-monet-muse.jpg b/public/previews/templates/hd/640/canvas/effect-chain-monet-muse.jpg
new file mode 100644
index 00000000..b42f4778
Binary files /dev/null and b/public/previews/templates/hd/640/canvas/effect-chain-monet-muse.jpg differ
diff --git a/public/previews/templates/hd/640/canvas/effect-chain-street-colossus.avif b/public/previews/templates/hd/640/canvas/effect-chain-street-colossus.avif
new file mode 100644
index 00000000..444f13c6
Binary files /dev/null and b/public/previews/templates/hd/640/canvas/effect-chain-street-colossus.avif differ
diff --git a/public/previews/templates/hd/640/canvas/effect-chain-street-colossus.jpg b/public/previews/templates/hd/640/canvas/effect-chain-street-colossus.jpg
new file mode 100644
index 00000000..56abdd52
Binary files /dev/null and b/public/previews/templates/hd/640/canvas/effect-chain-street-colossus.jpg differ
diff --git a/scripts/gen-template-hd.mjs b/scripts/gen-template-hd.mjs
new file mode 100644
index 00000000..68987ebe
--- /dev/null
+++ b/scripts/gen-template-hd.mjs
@@ -0,0 +1,213 @@
+#!/usr/bin/env node
+/**
+ * Larger copies of the template tiles' stills (src/lib/template-covers.ts), for boxes wider than the published poster
+ * on a 2x or 3x screen (the bar's Canvas menu and its phone sheet): the poster at each width in WIDTHS past the
+ * published one's and up to the render's own, as AVIF and JPEG, and an AVIF at 320 px. Made from the render the
+ * published cover was cut from (the masters pnpm eval:covers --templates reads), never enlarged from the published copy.
+ *
+ * Input: one or more masters folders (--masters, in the order to try), each laid out as pnpm eval:covers --templates
+ * reads it: <dir>/<group>/<tile id>/ holding clip.mp4 (and meta.json: { "rest": "end" | <seconds> }) or a still
+ * (still.png …). A clip is cut as the published one is (coverLoop in scripts/eval/lib/covers.mjs), so its poster is
+ * the same frame: its first, or the one it rests on. A reveal that comes with its last frame full size (poster.png)
+ * takes that, as its published still does.
+ *
+ * Output:
+ * public/previews/templates/hd/<W>/<group>/<id>.avif, .jpg the poster at width W
+ * public/previews/templates/hd/320/<group>/<id>.avif its small AVIF (the 320 px JPEG is the published thumb)
+ * src/lib/template-hd.generated.ts { "<group>/<id>": { w: [<widths>], v: "<version>" } }
+ *
+ * Check: each still is compared with the published poster (the mean difference of 128x96 grey copies, at most MATCH,
+ * as scripts/gen-preset-hd.mjs checks): a render whose frame doesn't show what the tile shows is not used.
+ *
+ * Only tiles with a cover of their own (/previews/templates/<group>/<id>.jpg): a tile that shows a preset's cover
+ * already has that preset's copies (scripts/gen-preset-hd.mjs).
+ *
+ * Run: node scripts/gen-template-hd.mjs --masters <dir> [--masters <dir> …] <group>/<id> … make these
+ * node scripts/gen-template-hd.mjs -<group>/<id> … take these out, with their files
+ * --dry-run makes and checks, and writes nothing.
+ * Needs ffmpeg on PATH (or FUOBE_FFMPEG).
+ */
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import sharp from "sharp";
+import { contentVersion, coverLoop } from "./eval/lib/covers.mjs";
+import { readTemplateManifest } from "./eval/lib/template-covers.mjs";
+
+const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
+const PUBLIC = path.join(ROOT, "public");
+const OUT_DIR = path.join(PUBLIC, "previews", "templates", "hd");
+const OUT_TS = path.join(ROOT, "src", "lib", "template-hd.generated.ts");
+/** The copies' widths, as the preset clips' (gen-preset-hd.mjs): a 262 px menu tile at 2x takes 640, a 534 px lead 1024. */
+const WIDTHS = [640, 1024];
+/** The small AVIF's width, as the JPEG thumbs' (thumbOf). */
+const SMALL_PX = 320;
+/** A clip's published poster's width (covers.mjs CLIP_PX); a still's is wider (STILL_PX), and its entry says so. */
+const PUBLISHED_PX = 512;
+const AVIF_QUALITY = 62;
+const JPEG_QUALITY = 82;
+/** How far (of 255) a copy may differ from the published poster, on average (from its mean): another frame is 10 and more. */
+const MATCH = 7;
+const STILLS = ["still.png", "still.jpg", "still.webp", "start.png", "start.jpg"];
+
+const argv = process.argv.slice(2);
+const DRY = argv.includes("--dry-run");
+const MASTERS = argv.flatMap((a, i) => (a === "--masters" && argv[i + 1] ? [argv[i + 1]] : []));
+const named = argv.filter((a, i) => !a.startsWith("--") && argv[i - 1] !== "--masters");
+
+const ffmpeg = (args, input) => {
+ const r = spawnSync(process.env.FUOBE_FFMPEG ?? "ffmpeg", args, { input, maxBuffer: 1 << 30 });
+ if (r.error?.code === "ENOENT") throw new Error("gen-template-hd needs ffmpeg on PATH");
+ if (r.status !== 0) throw new Error(`ffmpeg failed: ${String(r.stderr).trim().split("\n").at(-1)}`);
+ return r.stdout;
+};
+
+const readTs = (file) => {
+ if (!fs.existsSync(file)) return {};
+ const text = fs.readFileSync(file, "utf8");
+ return JSON.parse(text.slice(text.indexOf("= {") + 2, text.lastIndexOf("}") + 1));
+};
+
+/** A copy's file: hd/<w>/<group>/<id>.<ext>. */
+const fileOf = (w, key, ext) => path.join(OUT_DIR, String(w), ...key.split("/").slice(0, -1), `${key.split("/").at(-1)}.${ext}`);
+
+/** Every file an entry has, in a fixed order (its version is theirs). */
+const filesOf = (key, entry) => [...entry.w.flatMap((w) => [fileOf(w, key, "avif"), fileOf(w, key, "jpg")]), fileOf(SMALL_PX, key, "avif")];
+
+/** As gen-preset-hd.mjs: the mean difference of two pictures' 128x96 grey copies, each from its own mean brightness. */
+async function gap(a, b) {
+ const grey = (x) => sharp(x).resize(128, 96, { fit: "fill" }).greyscale().raw().toBuffer();
+ const [p, q] = await Promise.all([grey(a), grey(b)]);
+ const mean = (x) => x.reduce((s, v) => s + v, 0) / x.length;
+ const [mp, mq] = [mean(p), mean(q)];
+ let sum = 0;
+ for (let i = 0; i < p.length; i++) sum += Math.abs(p[i] - mp - (q[i] - mq));
+ return sum / p.length;
+}
+
+function readMeta(folder) {
+ try {
+ const meta = JSON.parse(fs.readFileSync(path.join(folder, "meta.json"), "utf8"));
+ return meta && typeof meta === "object" && !Array.isArray(meta) ? meta : {};
+ } catch {
+ return {};
+ }
+}
+
+/** A tile's master in one folder: its clip and where it rests, or its still; undefined when it has none there. */
+function masterIn(dir, key) {
+ const folder = path.join(dir, ...key.split("/"));
+ if (!fs.existsSync(folder)) return undefined;
+ const meta = readMeta(folder);
+ const rest = meta.rest === "end" ? "end" : typeof meta.rest === "number" && Number.isFinite(meta.rest) && meta.rest >= 0 ? meta.rest : undefined;
+ const clip = path.join(folder, "clip.mp4");
+ const full = path.join(folder, "poster.png");
+ if (fs.existsSync(clip)) return rest === "end" && fs.existsSync(full) ? { still: full } : { clip, rest };
+ const still = STILLS.map((s) => path.join(folder, s)).find((f) => fs.existsSync(f));
+ return still ? { still } : undefined;
+}
+
+/** The poster at width `w` as a PNG: the clip's frame it rests on (decoded as a browser shows it), or the still resized. */
+async function posterAt(m, w) {
+ if (m.still) return sharp(m.still).resize(w, null, { kernel: "lanczos3" }).png().toBuffer();
+ const { looped, rest, stream } = coverLoop(m.clip, { rest: m.rest }, `scale=${w}:-2:flags=lanczos`);
+ return ffmpeg(
+ ["-v", "error", "-f", "yuv4mpegpipe", "-i", "-", "-frames:v", "1", "-vf", "scale=in_color_matrix=bt709:in_range=tv:flags=accurate_rnd+full_chroma_int+lanczos,format=rgb24", "-c:v", "png", "-f", "image2pipe", "-"],
+ stream([looped[rest ?? 0]]),
+ );
+}
+
+const hd = readTs(OUT_TS);
+const manifest = readTemplateManifest();
+const failed = [];
+
+async function make(key) {
+ const entry = manifest[key];
+ if (!entry) return failed.push({ key, why: "not in template-covers.generated.ts" });
+ const poster = entry.poster.split("?")[0];
+ if (poster !== `/previews/templates/${key}.jpg`) return failed.push({ key, why: `it shows another cover (${poster}): that one's copies serve it` });
+ const published = path.join(PUBLIC, ...poster.split("/").filter(Boolean));
+ const publishedW = (await sharp(published).metadata()).width;
+ const misses = [];
+ for (const dir of MASTERS) {
+ const m = masterIn(dir, key);
+ if (!m) continue;
+ const own = m.still ? (await sharp(m.still).metadata()).width : probeWidth(m.clip);
+ const widths = WIDTHS.filter((w) => w > publishedW && w <= own);
+ if (!widths.length) {
+ misses.push(`${dir}: its render is ${own} px wide (nothing past the published ${publishedW} px)`);
+ continue;
+ }
+ const made = new Map();
+ let largest;
+ let ok = true;
+ for (const w of widths) {
+ const png = await posterAt(m, w);
+ const d = await gap(png, published);
+ console.log(`${key} ${w}: differs ${d.toFixed(2)} from the published poster`);
+ if (d > MATCH) {
+ misses.push(`${dir}: its ${w} px poster differs ${d.toFixed(2)} (> ${MATCH})`);
+ ok = false;
+ break;
+ }
+ made.set(fileOf(w, key, "avif"), await sharp(png).avif({ quality: AVIF_QUALITY, effort: 6 }).toBuffer());
+ made.set(fileOf(w, key, "jpg"), await sharp(png).jpeg({ quality: JPEG_QUALITY, mozjpeg: true }).toBuffer());
+ largest = png;
+ }
+ if (!ok) continue;
+ made.set(fileOf(SMALL_PX, key, "avif"), await sharp(largest).resize(SMALL_PX).avif({ quality: AVIF_QUALITY, effort: 6 }).toBuffer());
+ for (const [file, buf] of made) {
+ console.log(` ${path.relative(PUBLIC, file).split(path.sep).join("/")} ${(buf.length / 1024).toFixed(1)} KB`);
+ if (DRY) continue;
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, buf);
+ }
+ if (!DRY) hd[key] = { w: widths, ...(publishedW !== PUBLISHED_PX && { still: publishedW }) };
+ return;
+ }
+ failed.push({ key, why: misses.length ? misses.join("; ") : "no master found" });
+}
+
+/** A clip's width. */
+function probeWidth(file) {
+ const r = spawnSync(process.env.FUOBE_FFPROBE ?? "ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width", "-of", "csv=p=0", file]);
+ if (r.status !== 0) throw new Error(`ffprobe failed on ${file}`);
+ return Number(String(r.stdout).trim().split("\n")[0]);
+}
+
+for (const arg of named.filter((a) => a.startsWith("-"))) {
+ const key = arg.slice(1);
+ if (hd[key] && !DRY) for (const f of filesOf(key, hd[key])) fs.rmSync(f, { force: true });
+ delete hd[key];
+ console.log(`${key}: taken out`);
+}
+const makes = named.filter((a) => !a.startsWith("-"));
+if (makes.length && !MASTERS.length) throw new Error("copies are made from the renders: run with --masters <dir>");
+for (const key of makes) await make(key);
+if (failed.length) console.log(`not made: ${failed.map((f) => `${f.key} (${f.why})`).join(", ")}`);
+
+if (!DRY) {
+ const sorted = Object.entries(hd)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([key, e]) => {
+ const files = filesOf(key, e);
+ const missing = files.filter((f) => !fs.existsSync(f));
+ if (missing.length) throw new Error(`${key}: ${missing.length} of its copies are missing (${path.relative(ROOT, missing[0])}): make it again, or take it out with -${key}`);
+ return [key, { w: e.w, v: contentVersion(files), ...(e.still && { still: e.still }) }];
+ });
+ fs.writeFileSync(
+ OUT_TS,
+ `/**
+ * Larger copies of template tiles' posters (public/previews/templates/hd/<w>/<group>/<id>), keyed by "<group>/<tile id>":
+ * AVIF and JPEG at each width in \`w\`, and an AVIF at 320 px; \`still\`: the published poster's width, when it isn't a
+ * clip's 512 px. \`v\` is the content version every copy's URL ends in (?v=), so copies made again get new URLs. Read
+ * through src/lib/template-hd.ts. Generated by scripts/gen-template-hd.mjs: run it again rather than editing.
+ */
+export const TEMPLATE_HD: Record<string, { w: number[]; v: string; still?: number }> = {
+${sorted.map(([key, e]) => ` ${JSON.stringify(key)}: ${JSON.stringify(e).replace(/,"/g, ', "').replace(/^\{/, "{ ").replace(/\}$/, " }")}`).join(",\n")}
+};
+`,
+ );
+ console.log(`wrote ${sorted.length} entries`);
+}
diff --git a/src/components/nav/cover-thumb.tsx b/src/components/nav/cover-thumb.tsx
index b90554b5..c95bc994 100644
--- a/src/components/nav/cover-thumb.tsx
+++ b/src/components/nav/cover-thumb.tsx
@@ -23,9 +23,11 @@ interface SizeSpec {
h: number;
/**
* Which copy to load: the 96 px mini for the smallest boxes (the 320 px thumb where a cover has no mini), the 320 px
- * thumb for small boxes; fluid boxes pick between thumb and poster by `sizes`.
+ * thumb for small boxes; fluid boxes pick by `sizes` between thumb and poster, or among the cover's larger copies
+ * when it has them (MegaCover.hd).
*/
src: "mini" | "thumb" | "both";
+ /** The box's width for the srcset (a caller whose box is another width gives its own: CoverThumb's `sizes`). */
sizes: string;
}
@@ -46,8 +48,8 @@ export const COVER_SIZES: Record<CoverSize, SizeSpec> = {
pill: { box: "size-10 rounded-[10px]", w: 40, h: 40, src: "thumb", sizes: "40px" },
/** 16:9, full width: the "next to try" card. */
wide: { box: "aspect-video w-full rounded-[10px]", w: 512, h: 288, src: "both", sizes: "300px" },
- /** 16:9, full width: a menu's ready-board tile (Canvas), about 200 px wide. */
- tile16: { box: "aspect-video w-full rounded-[10px]", w: 320, h: 180, src: "thumb", sizes: "200px" },
+ /** 16:9, full width: a ready-board tile (the Canvas menu's, 222 to 262 px; the phone sheet's): its caller gives `sizes`. */
+ tile16: { box: "aspect-video w-full rounded-[10px]", w: 320, h: 180, src: "both", sizes: "262px" },
};
export function CoverThumb({
@@ -56,6 +58,7 @@ export function CoverThumb({
size,
icon,
eager,
+ sizes: boxSizes,
className,
}: {
/** A preset id with a real cover (NavEntry.cover, a goal tap's preset); undefined shows the fallback. */
@@ -67,20 +70,26 @@ export function CoverThumb({
icon?: NavIconName;
/** Load at once (a panel about to open) instead of when it comes near the screen. */
eager?: boolean;
+ /** A fluid box's width for the srcset, when it isn't its size's usual one (a lead card two tracks wide, a phone's tile). */
+ sizes?: string;
className?: string;
}) {
const nav = useNavCover(given ? undefined : id);
- const cover = given ?? nav;
+ const cover: MegaCover | undefined = given ?? nav;
const s = COVER_SIZES[size];
const small = s.src === "mini" ? (cover?.mini ?? cover?.thumb) : cover?.thumb;
+ const sizes = s.src === "both" ? (boxSizes ?? s.sizes) : undefined;
+ // Its larger copies, where it has them (the Canvas menu's covers): AVIF first, else JPEG, the narrowest at least as
+ // wide as the box on this screen, so a 2x or 3x screen never shows a copy stretched past its own pixels.
+ const hd = sizes ? cover?.hd : undefined;
// How the cover sits in a box of another shape (cover-framing.ts): a square keeps its top part by default, where faces are.
const whole = cover?.framing?.fit === "whole";
- const img = cover && (
+ const still = cover && (
// eslint-disable-next-line @next/next/no-img-element -- versioned static covers, sized by the box (no optimizer round trip)
<img
src={small}
- srcSet={s.src === "both" ? `${cover.thumb} 320w, ${cover.poster} 512w` : undefined}
- sizes={s.src === "both" ? s.sizes : undefined}
+ srcSet={hd ? hd.jpeg : sizes ? `${cover.thumb} 320w, ${cover.poster} 512w` : undefined}
+ sizes={sizes}
width={s.w}
height={s.h}
alt=""
@@ -91,6 +100,14 @@ export function CoverThumb({
style={{ objectPosition: cover.framing?.focus ?? "50% 25%" }}
/>
);
+ const img = hd ? (
+ <picture>
+ <source type="image/avif" srcSet={hd.avif} sizes={sizes} />
+ {still}
+ </picture>
+ ) : (
+ still
+ );
return (
<span aria-hidden data-cover={cover ? (id ?? "") : undefined} className={cn("relative block shrink-0 overflow-hidden bg-muted", s.box, className)}>
{cover && whole ? (
diff --git a/src/components/nav/mega-panel.tsx b/src/components/nav/mega-panel.tsx
index abf618f0..45cba091 100644
--- a/src/components/nav/mega-panel.tsx
+++ b/src/components/nav/mega-panel.tsx
@@ -38,12 +38,24 @@ function NewBadge() {
);
}
+/**
+ * The `sizes` of a picture `span` of the grid's six tracks wide (from lg), less `inset` px (a card's border), so its
+ * srcset gives a 2x or 3x screen a copy at least as wide as the box: the panel's content is at most 1680 px wide less
+ * its 24 px sides (px-6), its tracks 12 px apart (gap-x-3), so a track is (width - 108) / 6. For the Canvas menu,
+ * which shows from 1440 px only (always six tracks); a tile is one track wide (its tiles are as far apart as the tracks).
+ */
+export function trackSizes(span: number, inset = 0): string {
+ const extra = (span - 1) * 12 - inset;
+ return `(min-width: 1680px) ${Math.floor(((1680 - 108) * span) / 6) + extra}px, calc((100vw - 108px) * ${span} / 6 + ${extra}px)`;
+}
+
/**
* A column's first card: its cover, name and one line. `row` 1 under the owner's New board (Canvas), its cover shorter by
* that button. The cover's height is rounded down to the 4 px grid (a 4:3 box of a fractional column width would put
- * every row under the card on a half pixel), and its words start 12 px in, the column its features hang from.
+ * every row under the card on a half pixel), and its words start 12 px in, the column its features hang from. `span`:
+ * the tracks its column takes, when more than one (Canvas' Start here), for its picture's srcset.
*/
-export function LeadCard({ e, col, row = 0, current, inside, now, className }: { e: MegaItem; col: number; row?: number; current: boolean; inside?: boolean; now: number; className?: string }) {
+export function LeadCard({ e, col, row = 0, span = 1, current, inside, now, className }: { e: MegaItem; col: number; row?: number; span?: number; current: boolean; inside?: boolean; now: number; className?: string }) {
return (
<IntentLink
href={e.href}
@@ -59,6 +71,7 @@ export function LeadCard({ e, col, row = 0, current, inside, now, className }: {
size="lead"
icon={e.icon}
eager
+ sizes={span > 1 ? trackSizes(span, 2) : undefined}
className={cn(
"h-[round(down,75cqw,4px)] rounded-none md:max-lg:max-h-[round(down,max(56px,calc(100dvh_-_460px)),4px)]",
row ? "max-h-[round(down,max(64px,calc(100dvh_-_640px)),4px)]" : "max-h-[round(down,max(64px,calc(100dvh_-_592px)),4px)]",
@@ -188,7 +201,7 @@ function Tile({ e, col, row, current, eager }: { e: MegaItem; col: number; row:
className="nav-row nav-mark-under -m-1.5 flex min-w-0 flex-col gap-1.5 rounded-[12px] p-1.5 [container-type:inline-size]"
>
{/* 16:9, its height rounded down to the 4 px grid, so a second row of tiles sits on a whole pixel. */}
- <CoverThumb cover={e.cover} size="tile16" icon={e.icon} eager={eager} className="aspect-auto h-[round(down,56.25cqw,4px)]" />
+ <CoverThumb cover={e.cover} size="tile16" icon={e.icon} eager={eager} sizes={trackSizes(1)} className="aspect-auto h-[round(down,56.25cqw,4px)]" />
<span className="flex min-w-0 flex-col">
<span className={cn("truncate text-[13px] leading-[18px] font-medium", current && "font-semibold")}>{e.label}</span>
<span className="truncate text-[12px] leading-4 text-muted-foreground">{e.line}</span>
@@ -266,7 +279,7 @@ export function MegaColumns({ model, current, now, kind }: { model: MegaModel; c
<div key={c.id} data-group={c.id} className={cn("flex min-w-0 flex-col gap-2", place)}>
{label}
<Suspense fallback={<OwnerStartSkeleton />}>
- <CanvasOwnerStart col={col} labelledBy={labelId} fallback={c.lead && <LeadCard e={c.lead} col={col} row={1} current={false} now={now} />} />
+ <CanvasOwnerStart col={col} labelledBy={labelId} fallback={c.lead && <LeadCard e={c.lead} col={col} row={1} span={c.span} current={false} now={now} />} />
</Suspense>
</div>
);
@@ -313,7 +326,7 @@ export function MegaColumns({ model, current, now, kind }: { model: MegaModel; c
<ul aria-labelledby={labelId} className="flex flex-col gap-1">
{c.lead && (
<li>
- <LeadCard e={c.lead} col={col} current={current === c.lead.id} inside={holder === c.lead.id} now={now} className="mb-1" />
+ <LeadCard e={c.lead} col={col} span={c.span} current={current === c.lead.id} inside={holder === c.lead.id} now={now} className="mb-1" />
<SubLinks e={c.lead} col={col} row={1} current={current} />
</li>
)}
diff --git a/src/components/nav/studios-sheet.tsx b/src/components/nav/studios-sheet.tsx
index 3aeb7e0a..24cc9f27 100644
--- a/src/components/nav/studios-sheet.tsx
+++ b/src/components/nav/studios-sheet.tsx
@@ -97,12 +97,18 @@ function SeeAllTile({ href, label, name }: { href: string; label: string; name:
);
}
+/**
+ * A board card's picture width, for its srcset: half the sheet (it is the screen's width below md) less its 16 px sides,
+ * the 8 px between the two cards and each card's own 4 px padding.
+ */
+const BOARD_SIZES = "calc((100vw - 56px) / 2)";
+
/** A ready board as a phone card: its finished scene (16:9) with its name under it. */
function BoardCard({ entry, current }: { entry: MegaItem; current: boolean }) {
return (
<li className="min-w-0">
<IntentLink href={entry.href} aria-current={current ? "page" : undefined} className="nav-row nav-mark-under flex min-w-0 flex-col gap-1 rounded-[14px] p-1">
- <CoverThumb cover={entry.cover} icon={entry.icon} size="tile16" eager />
+ <CoverThumb cover={entry.cover} icon={entry.icon} size="tile16" eager sizes={BOARD_SIZES} />
<span className="truncate px-0.5 text-[12px] leading-4 font-medium">{entry.label}</span>
</IntentLink>
</li>
diff --git a/src/lib/mega-menus.server.ts b/src/lib/mega-menus.server.ts
index ef862bcf..a5c5942e 100644
--- a/src/lib/mega-menus.server.ts
+++ b/src/lib/mega-menus.server.ts
@@ -17,9 +17,11 @@ import { HOME_EFFECTS, HOME_MOTIONS, presetHref } from "@/lib/home-showcase";
import { ROW_CAPS, TILE_COLS, TILE_ROWS, type MegaColumn, type MegaCover, type MegaItem, type MegaModel } from "@/lib/mega-menus";
import { hasMini, miniOf } from "@/lib/preset-cards";
import { presetCover } from "@/lib/preset-covers";
+import { presetStillSources } from "@/lib/preset-hd";
import { PRESET_MINIS } from "@/lib/preset-minis.generated";
import { featuredAll } from "@/lib/preset-featured";
import { templateCover } from "@/lib/template-covers";
+import { templateStillSources } from "@/lib/template-hd";
import { MENU_LINES } from "@/lib/menu-lines";
/** A column of a preset menu: its name, its phone chip, and the catalog categories it holds. */
@@ -178,12 +180,16 @@ export function motionsMenu(): MegaModel {
/** Who the Canvas menu is for: a visitor (the owner sees the same boards: menus show real covers only). */
const VISITOR: Viewing = { visitor: true, hasCover: (id) => !!templateCover("canvas", id) };
-/** A template cover as a menu tile shows it: its peak frame (the finished scene), never a clip. */
+/**
+ * A template cover as a menu tile shows it: its peak frame (the finished scene), never a clip, with its larger copies
+ * (the preset's peak frame's, or the tile's own poster's), so a 2x or 3x screen gets one at least as wide as the box.
+ */
function templateMegaCover(id: string): MegaCover | undefined {
const c = templateCover("canvas", id);
if (!c) return undefined;
const framing = coverFraming(c.poster);
- return { poster: c.poster, thumb: c.thumb, ...(framing && { framing }) };
+ const hd = presetStillSources(c.poster, c.thumb) ?? templateStillSources(c.poster, c.thumb);
+ return { poster: c.poster, thumb: c.thumb, ...(hd && { hd }), ...(framing && { framing }) };
}
/**
diff --git a/src/lib/mega-menus.ts b/src/lib/mega-menus.ts
index 146919a3..1eca3998 100644
--- a/src/lib/mega-menus.ts
+++ b/src/lib/mega-menus.ts
@@ -6,6 +6,7 @@
*/
import type { CoverFraming } from "./cover-framing";
import { area } from "./nav-areas";
+import type { StillSources } from "./preset-hd";
import { entriesFor, launcherColumns, studioCount, studioSubs, STUDIO_SUBS, subLabel, subParent, type NavEntry, type NavIconName, type ViewerKind } from "./nav-model";
export type MegaId = "studios" | "apps" | "motions" | "canvas";
@@ -25,6 +26,12 @@ export interface MegaCover {
thumb: string;
/** Its 96 px copy, for a row and a phone tile (a preset's own poster only). */
mini?: string;
+ /**
+ * Its larger copies' srcsets (preset-hd.ts, template-hd.ts), so a box wider than the poster on a 2x or 3x screen
+ * gets a copy at least as wide as it shows: the Canvas menu's tiles and lead. Made on the server, so no client chunk
+ * carries the lists of copies.
+ */
+ hd?: StillSources;
/** How it sits in a box of another shape (cover-framing.ts). */
framing?: CoverFraming;
}
diff --git a/src/lib/preset-hd.generated.ts b/src/lib/preset-hd.generated.ts
index 2afc7526..580fdea8 100644
--- a/src/lib/preset-hd.generated.ts
+++ b/src/lib/preset-hd.generated.ts
@@ -139,7 +139,7 @@ export const PRESET_HD: Record<string, { w: number[]; v: string; still?: number;
"app-zooms": { "w":[640,1024], "v":"63bdec9a" },
"effect-acid": { "w":[640,1024], "v":"ce7d1136" },
"effect-act-natural": { "w":[640,1024], "v":"89cc3e40", "rest":"/examples/effect-act-natural/1/out-peak.jpg" },
- "effect-agamemnon": { "w":[640,1024], "v":"e9eb0753" },
+ "effect-agamemnon": { "w":[640,1024], "v":"9a6a449d" },
"effect-agent-reveal": { "w":[640,1024], "v":"11219636", "rest":"/examples/effect-agent-reveal/1/out-peak.jpg" },
"effect-air-bending": { "w":[1024], "v":"abb57363", "still":768 },
"effect-akrill": { "w":[640,1024], "v":"fb5b8645" },
diff --git a/src/lib/template-hd.generated.ts b/src/lib/template-hd.generated.ts
new file mode 100644
index 00000000..81f75761
--- /dev/null
+++ b/src/lib/template-hd.generated.ts
@@ -0,0 +1,11 @@
+/**
+ * Larger copies of template tiles' posters (public/previews/templates/hd/<w>/<group>/<id>), keyed by "<group>/<tile id>":
+ * AVIF and JPEG at each width in `w`, and an AVIF at 320 px; `still`: the published poster's width, when it isn't a
+ * clip's 512 px. `v` is the content version every copy's URL ends in (?v=), so copies made again get new URLs. Read
+ * through src/lib/template-hd.ts. Generated by scripts/gen-template-hd.mjs: run it again rather than editing.
+ */
+export const TEMPLATE_HD: Record<string, { w: number[]; v: string; still?: number }> = {
+ "canvas/effect-chain-fallen-angel": { "w":[640,1024], "v":"38cc902a" },
+ "canvas/effect-chain-monet-muse": { "w":[640,1024], "v":"74a2defd" },
+ "canvas/effect-chain-street-colossus": { "w":[640,1024], "v":"c7bdb6b9" }
+};
diff --git a/src/lib/template-hd.ts b/src/lib/template-hd.ts
new file mode 100644
index 00000000..1283179f
--- /dev/null
+++ b/src/lib/template-hd.ts
@@ -0,0 +1,30 @@
+/**
+ * The larger copies of a template tile's poster (template-hd.generated.ts, made by scripts/gen-template-hd.mjs): its
+ * own poster's URL as the tile holds it (/previews/templates/<group>/<id>.jpg) and the copies a box can choose from by
+ * its size and the screen's pixel ratio, as preset-hd.ts gives a preset cover's. A tile that shows a preset's cover
+ * takes that preset's copies (presetStillSources); a tile without copies keeps its published files.
+ */
+import { PUBLISHED_PX, SMALL_PX, type StillSources } from "@/lib/preset-hd";
+import { TEMPLATE_HD } from "@/lib/template-hd.generated";
+
+const POSTER = /^\/previews\/templates\/([a-z0-9-]+\/[a-z0-9-]+)\.jpg(?:\?|$)/;
+
+/** The srcsets of a tile's own poster with larger copies, or undefined. `thumb` is its 320 px JPEG (thumbOf). */
+export function templateStillSources(poster: string, thumb?: string): StillSources | undefined {
+ const key = POSTER.exec(poster)?.[1];
+ const hd = key ? TEMPLATE_HD[key] : undefined;
+ if (!key || !hd) return undefined;
+ const at = (w: number, ext: string) => `/previews/templates/hd/${w}/${key}.${ext}?v=${hd.v}`;
+ return {
+ avif: [SMALL_PX, ...hd.w].map((w) => `${at(w, "avif")} ${w}w`).join(", "),
+ jpeg: [...(thumb ? [`${thumb} ${SMALL_PX}w`] : []), `${poster} ${hd.still ?? PUBLISHED_PX}w`, ...hd.w.map((w) => `${at(w, "jpg")} ${w}w`)].join(", "),
+ };
+}
+
+/** Every copy a tile has (bare URLs): its poster at each width, AVIF and JPEG, and its 320 px AVIF. */
+export function templateHdFiles(key: string): string[] {
+ const hd = TEMPLATE_HD[key];
+ if (!hd) return [];
+ const at = (w: number, ext: string) => `/previews/templates/hd/${w}/${key}.${ext}`;
+ return [...hd.w.flatMap((w) => [at(w, "avif"), at(w, "jpg")]), at(SMALL_PX, "avif")];
+}
diff --git a/tests/e2e/mega-menus.mjs b/tests/e2e/mega-menus.mjs
index 47d23b14..47d2c3a6 100644
--- a/tests/e2e/mega-menus.mjs
+++ b/tests/e2e/mega-menus.mjs
@@ -1,6 +1,7 @@
// The bar's grouped menus in a real browser: Studios, Apps, Motions & effects and Canvas, for a guest, an account and
// the owner, at the desktop sizes they must fit without scrolling; their keys, links, loading and budgets; the phone's
-// Studios sheet with its four families; and the Canvas ready boards' covers on /canvas.
+// Studios sheet with its four families; the Canvas menu's pictures sharp on 2x and 3x screens; and the Canvas ready
+// boards' covers on /canvas.
// Usage: node tests/e2e/mega-menus.mjs [appUrl] [shotsDir]
// E2E_BROWSER=webkit (Safari's engine) or firefox runs it there (the loading and budget checks are Chromium's).
// E2E_OWNER_PASSWORD: the studio's password, when it has one. Account checks need public sign-up (throwaway qa
@@ -327,6 +328,58 @@ try {
check(w(1920) >= w(1440) - 0.5, "Studios: columns at 1920 at least as wide as at 1440", `${w(1440).toFixed(1)} → ${w(1920).toFixed(1)}`);
}
+ // 1d. Canvas' pictures are sharp: each loads a copy at least as wide as its box times the screen's pixel ratio
+ // (the copies its srcset lists: from 1680 px the lead asks 1068 px at 2x and takes the widest, 1024), in the panel at
+ // 1440 and 1920 px on a 2x screen, and on the phone sheet at 3x.
+ {
+ /** Each picture shown under `sel`: the width of the file it loaded, the width its box asks for and the widest it lists. */
+ const sharpness = (p, sel) =>
+ p.evaluate(async (sel) => {
+ const out = [];
+ for (const img of [...document.querySelectorAll(`${sel} img`)].filter((i) => i.checkVisibility() && !/\bblur/.test(i.className))) {
+ const r = img.getBoundingClientRect();
+ if (r.bottom < 0 || r.top > innerHeight) continue;
+ const probe = new Image();
+ probe.src = img.currentSrc || img.src;
+ await probe.decode().catch(() => {});
+ const listed = [img, ...(img.parentElement?.tagName === "PICTURE" ? img.parentElement.querySelectorAll("source") : [])]
+ .flatMap((x) => (x.getAttribute("srcset") ?? "").split(",").map((c) => Number(/\s(\d+)w$/.exec(c.trim())?.[1] ?? 0)));
+ const need = Math.ceil(Math.max(r.width, probe.naturalHeight ? r.height * (probe.naturalWidth / probe.naturalHeight) : 0) * devicePixelRatio);
+ out.push({ src: new URL(probe.src).pathname, file: probe.naturalWidth, need, widest: Math.max(probe.naturalWidth, ...listed) });
+ }
+ return out;
+ }, sel);
+ const report = (list) => list.map((x) => `${x.src.split("/").slice(-3).join("/")} ${x.file}/${x.need}`).join(", ");
+ for (const width of [1440, 1920]) {
+ const size = SIZES.find((s) => s.width === width);
+ const ctx = await as("guest", { viewport: size, deviceScaleFactor: 2 });
+ const p = await page(ctx);
+ await openRoute(p, `${app}/image`, { settleMs: 300 });
+ await openMenu(p, "canvas");
+ await p.waitForTimeout(500);
+ const list = await sharpness(p, "#canvas-launcher");
+ const soft = list.filter((x) => x.file < Math.min(x.need, x.widest) - 1 || (width === 1440 && x.file < x.need - 1));
+ check(list.length >= 5 && soft.length === 0, `guest ${width}x${size.height} at 2x canvas: every picture at least its box x 2 (${list.length})`, report(soft));
+ if (shots) await shot(p, `canvas-${width}-2x`);
+ await ctx.close();
+ }
+ {
+ const ctx = await as("guest", { ...PHONE, deviceScaleFactor: 3 });
+ const p = await page(ctx);
+ await openRoute(p, `${app}/image`, { settleMs: 300 });
+ await p.locator("[data-phone-tabs]").getByRole("button", { name: "Studios" }).tap();
+ const sheet = p.locator("#phone-sheet");
+ await sheet.waitFor({ state: "visible" });
+ await sheet.getByRole("group", { name: "What to show" }).getByRole("button", { name: "Canvas", exact: true }).tap();
+ await sheet.locator('[data-sheet-family="canvas"] a[href]').first().waitFor({ timeout: 10_000 });
+ await p.waitForFunction(() => [...document.querySelectorAll('[data-sheet-family="canvas"] img')].every((i) => i.complete), null, { timeout: 10_000 }).catch(() => {});
+ const list = await sharpness(p, '[data-sheet-family="canvas"]');
+ const soft = list.filter((x) => x.file < x.need - 1);
+ check(list.length >= 2 && soft.length === 0, `guest phone 390 at 3x canvas: every board's picture at least its box x 3 (${list.length})`, report(soft));
+ await ctx.close();
+ }
+ }
+
// 2. Keys, one panel at a time, links and See all (guest, 1440x900).
{
const ctx = await as("guest");
diff --git a/tests/mega-menus.test.ts b/tests/mega-menus.test.ts
index 967a6453..b26d078e 100644
--- a/tests/mega-menus.test.ts
+++ b/tests/mega-menus.test.ts
@@ -1,12 +1,13 @@
import fs from "node:fs";
import path from "node:path";
import { gzipSync } from "node:zlib";
+import sharp from "sharp";
import { describe, expect, it } from "vitest";
import { APPS, EFFECTS, MODELS, MOTIONS } from "@/lib/catalog";
import { CANVAS_TEMPLATES } from "@/lib/catalog/canvas";
import { APP_GROUPS, appsMenu, canvasMenu, EFFECT_GROUPS, LINE_MAX, menuCategory, MOTION_GROUPS, motionsMenu, presetLine, sameIdea, SERVER_MENUS, shortLine, type PresetGroup } from "@/lib/mega-menus.server";
import { megaItems, megaMove, packMenu, ROW_CAPS, studiosMenu, TILE_COLS, TILE_ROWS, unpackMenu, type MegaModel } from "@/lib/mega-menus";
-import { keyPlaces } from "@/components/nav/mega-panel";
+import { keyPlaces, trackSizes } from "@/components/nav/mega-panel";
import { CANVAS_INTRO } from "@/lib/canvas-template-cards";
import { MENU_LINES } from "@/lib/menu-lines";
import type { Preset } from "@/lib/catalog/types";
@@ -141,6 +142,47 @@ describe("the Canvas menu", () => {
expect(menu.columns.at(-1)?.more).toEqual({ href: "/canvas?tab=templates", label: "See all ready boards" });
});
+ it("gives every picture larger copies, so a 2x or 3x screen gets one at least as wide as its box", async () => {
+ const copies = (srcset: string) => srcset.split(", ").map((c) => ({ url: c.split(" ")[0], w: Number(c.split(" ")[1].slice(0, -1)) }));
+ // A copy shows what the published still shows (as tests/preset-hd.test.ts measures: 128x96 grey, each from its mean).
+ const grey = (url: string) => sharp(file(url)).resize(128, 96, { fit: "fill" }).greyscale().raw().toBuffer();
+ const gap = (a: Buffer, b: Buffer) => {
+ const mean = (x: Buffer) => x.reduce((s, v) => s + v, 0) / x.length;
+ const [ma, mb] = [mean(a), mean(b)];
+ return a.reduce((sum, v, i) => sum + Math.abs(v - ma - (b[i] - mb)), 0) / a.length;
+ };
+ // The boxes as the panel and the phone sheet draw them (tests/e2e/mega-menus.mjs measures them): a tile at 1440
+ // and 1920 px on a 2x screen, the lead (two tracks) at 1440 px on a 2x screen, a phone card at 390 px on a 3x screen.
+ const tile = [222 * 2, 262 * 2, 167 * 3];
+ const lead = [454 * 2, 167 * 3];
+ const items = [...boards.map((b) => [b, tile] as const), [menu.columns[0].lead!, lead] as const];
+ for (const [e, needs] of items) {
+ const hd = e.cover?.hd;
+ expect(hd, e.id).toBeDefined();
+ for (const set of [hd!.avif, hd!.jpeg]) {
+ const listed = copies(set);
+ for (const c of listed) expect(fs.existsSync(file(c.url)), c.url).toBe(true);
+ for (const need of needs) expect(Math.max(...listed.map((c) => c.w)), `${e.id}: ${need} px`).toBeGreaterThanOrEqual(need);
+ const widest = listed.reduce((a, b) => (b.w > a.w ? b : a));
+ expect(gap(await grey(widest.url), await grey(e.cover!.poster)), widest.url).toBeLessThan(8);
+ }
+ // The published files are among them, so a 1x screen keeps its small copy.
+ expect(hd!.jpeg, e.id).toContain(`${e.cover!.thumb} 320w`);
+ }
+ });
+
+ it("tells the browser each picture's box width: a tile one track, the lead two less its border", () => {
+ const at = (sizes: string, vw: number) => {
+ const [wide, calc] = sizes.split(", ");
+ if (vw >= 1680) return Number(/ (\d+)px$/.exec(wide)![1]);
+ const [, side, span, extra] = /^calc\(\(100vw - (\d+)px\) \* (\d+) \/ 6 \+ (-?\d+)px\)$/.exec(calc)!;
+ return ((vw - Number(side)) * Number(span)) / 6 + Number(extra);
+ };
+ // As the panel draws them (tests/e2e/mega-menus.mjs): tiles 222 and 262 px wide, the lead 454 and 534 px.
+ expect([1440, 1920].map((vw) => at(trackSizes(1), vw))).toEqual([222, 262]);
+ expect([1440, 1920].map((vw) => at(trackSizes(2, 2), vw))).toEqual([454, 534]);
+ });
+
it("holds no model name", () => {
const text = JSON.stringify(menu);
for (const name of ["Fuobe DoP", "Qwen", "free on your GPU", ...MODELS.map((m) => m.name).filter((n) => n.length > 5)]) expect(text, name).not.toContain(name);
diff --git a/tests/template-covers.test.ts b/tests/template-covers.test.ts
index f7506304..66972f89 100644
--- a/tests/template-covers.test.ts
+++ b/tests/template-covers.test.ts
@@ -18,6 +18,8 @@ import { PRESET_PREVIEWS } from "@/lib/preset-previews.generated";
import { STARTERS } from "@/lib/starters/catalog";
import { TEMPLATE_GROUPS, templateCover, type TemplateGroup } from "@/lib/template-covers";
import { TEMPLATE_COVERS } from "@/lib/template-covers.generated";
+import { templateHdFiles } from "@/lib/template-hd";
+import { TEMPLATE_HD } from "@/lib/template-hd.generated";
import { tempDir } from "./helpers/temp-dir";
/*
@@ -100,6 +102,8 @@ describe("the template covers manifest", () => {
for (const f of c.frames) for (const u of [f.src, f.thumb]) named.add(u.split("?")[0]);
if (c.video) named.add(c.video.split("?")[0]);
}
+ // The posters' larger copies (scripts/gen-template-hd.mjs, tests/template-hd.test.ts).
+ for (const key of Object.keys(TEMPLATE_HD)) for (const u of templateHdFiles(key)) named.add(u);
const dir = path.join(root, "public", "previews", "templates");
const files = fs.existsSync(dir) ? fs.readdirSync(dir, { recursive: true, encoding: "utf8" }).filter((f) => /.(jpg|mp4)$/.test(f)) : [];
const orphans = files.map((f) => `/previews/templates/${f.replaceAll("\\", "/")}`).filter((u) => !named.has(u));
diff --git a/tests/template-hd.test.ts b/tests/template-hd.test.ts
new file mode 100644
index 00000000..44064dff
--- /dev/null
+++ b/tests/template-hd.test.ts
@@ -0,0 +1,74 @@
+import fs from "node:fs";
+import path from "node:path";
+import sharp from "sharp";
+import { describe, expect, it } from "vitest";
+import { templateCover, type TemplateGroup } from "@/lib/template-covers";
+import { templateHdFiles, templateStillSources } from "@/lib/template-hd";
+import { TEMPLATE_HD } from "@/lib/template-hd.generated";
+
+/*
+ * Larger copies of template tiles' posters (scripts/gen-template-hd.mjs, src/lib/template-hd.ts): every listed copy is
+ * there at its width and weight, shows what the published poster shows, and a tile's srcsets list them, so a box takes
+ * one at least as wide as it shows.
+ */
+
+const root = process.cwd();
+const local = (url: string) => path.join(root, "public", ...url.split("?")[0].split("/").filter(Boolean));
+const grey = (file: string) => sharp(file).resize(128, 96, { fit: "fill" }).greyscale().raw().toBuffer();
+const mean = (x: Buffer) => x.reduce((s, v) => s + v, 0) / x.length;
+/** As gen-template-hd.mjs: each from its own mean brightness. */
+const gap = (a: Buffer, b: Buffer) => {
+ const [ma, mb] = [mean(a), mean(b)];
+ return a.reduce((sum, v, i) => sum + Math.abs(v - ma - (b[i] - mb)), 0) / a.length;
+};
+/** The generator checks the decoded frame against 7; its AVIF and JPEG copies add a little of their own. */
+const MATCH = 8;
+/** The most a copy may weigh, by width (a painted, detailed scene is the heaviest). */
+const MAX_STILL = { 320: 30_000, 640: 120_000, 1024: 260_000 } as Record<number, number>;
+
+const urls = (srcset: string) => srcset.split(", ").map((s) => ({ url: s.split(" ")[0], w: Number(s.split(" ")[1].slice(0, -1)) }));
+
+describe("template tiles' larger copies", () => {
+ const keys = Object.keys(TEMPLATE_HD);
+
+ it("lists tiles with a poster of their own, at widths past the published one's", () => {
+ expect(keys.length).toBeGreaterThan(0);
+ for (const key of keys) {
+ const [group, id] = key.split("/") as [TemplateGroup, string];
+ const c = templateCover(group, id);
+ expect(c?.poster, key).toMatch(new RegExp(`^/previews/templates/${key}\\.jpg\\?v=[0-9a-f]{8}$`));
+ expect(TEMPLATE_HD[key].w.every((w) => w > (TEMPLATE_HD[key].still ?? 512)), key).toBe(true);
+ }
+ });
+
+ it.each(keys)("%s: every copy is there, at its width and weight, showing the published poster", async (key) => {
+ const [group, id] = key.split("/") as [TemplateGroup, string];
+ const c = templateCover(group, id)!;
+ const src = templateStillSources(c.poster, c.thumb)!;
+ expect(src).toBeDefined();
+ const published = await grey(local(c.poster));
+ const ownW = (await sharp(local(c.poster)).metadata()).width!;
+ // The published poster and its thumb, at their own widths, then the copies.
+ expect(src.jpeg).toContain(`${c.thumb} 320w, ${c.poster} ${ownW}w`);
+ for (const { url, w } of [...urls(src.avif), ...urls(src.jpeg).filter((x) => x.w > ownW)]) {
+ expect(url).toMatch(new RegExp(`^/previews/templates/hd/${w}/${key}\\.(avif|jpg)\\?v=${TEMPLATE_HD[key].v}$`));
+ const file = local(url);
+ expect((await sharp(file).metadata()).width, url).toBe(w);
+ expect(fs.statSync(file).size, url).toBeLessThan(MAX_STILL[w]);
+ expect(gap(await grey(file), published), url).toBeLessThan(MATCH);
+ }
+ });
+
+ it("leaves no file in public/previews/templates/hd that no entry names", () => {
+ const named = new Set(keys.flatMap(templateHdFiles));
+ const dir = path.join(root, "public", "previews", "templates", "hd");
+ const files = fs.existsSync(dir) ? fs.readdirSync(dir, { recursive: true, encoding: "utf8" }).filter((f) => /\.(jpg|avif)$/.test(f)) : [];
+ expect(files.map((f) => `/previews/templates/hd/${f.replaceAll("\\", "/")}`).filter((u) => !named.has(u))).toEqual([]);
+ for (const u of named) expect(fs.existsSync(local(u)), u).toBe(true);
+ });
+
+ it("a poster without copies, or a preset's cover, keeps its own files", () => {
+ expect(templateStillSources("/previews/templates/canvas/no-such-tile.jpg?v=1", "/t.jpg")).toBeUndefined();
+ expect(templateStillSources("/previews/presets/peak/effect-agamemnon.jpg?v=1")).toBeUndefined();
+ });
+});