Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

feat: read a stylesheet as a gallery of previews

rpone44683bd8a2e8
diff --git a/test/playground-discover.test.ts b/test/playground-discover.test.ts
new file mode 100644
index 00000000..4542c6ba
--- /dev/null
+++ b/test/playground-discover.test.ts
@@ -0,0 +1,76 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+
+import { discover } from "../tools/playground/src/svs/discover.js";
+import { within } from "../tools/playground/src/server/browse.js";
+
+const repoRoot = fileURLToPath(new URL("..", import.meta.url)).replace(/\/$/u, "");
+const golden = readFileSync(
+ fileURLToPath(new URL("../examples/talking-film-golden/studio.svs", import.meta.url)),
+ "utf8",
+);
+
+test("a stylesheet is read as a list of things to preview", () => {
+ const found = discover("studio.svs", golden);
+ assert.equal(found.sheetId, "studio");
+
+ // A Film Recipe is not a preview subject: it says how big the frame is.
+ assert.deepEqual(found.canvases, [{
+ path: "film.vertical", width: 1080, height: 1920, fps: 30, clearColor: "#09090B",
+ }]);
+
+ assert.deepEqual(
+ found.subjects.map((subject) => [subject.path, subject.component.id]),
+ [
+ ["caption.dialogue", "caption"],
+ ["caption.alice", "caption"],
+ ["caption.bob", "caption"],
+ ["text.title", "text-track"],
+ ],
+ );
+
+ // Reported rather than dropped. These are real Recipes with no preview yet,
+ // and naming them is the difference between a gap and a silent omission.
+ assert.deepEqual(
+ found.unmatched.map((entry) => entry.path),
+ ["font.inter-semibold", "font.inter-black", "speech.full", "broll.product", "caption.short-cues"],
+ );
+});
+
+test("Recipes sharing a path prefix are told apart by their shape", () => {
+ const found = discover("studio.svs", golden);
+ // caption.dialogue previews; caption.short-cues is Gemini planning config.
+ assert.ok(found.subjects.some((subject) => subject.path === "caption.dialogue"));
+ assert.ok(found.unmatched.some((entry) => entry.path === "caption.short-cues"));
+});
+
+test("each Recipe carries its own draft, so like-shaped ones stay distinct", () => {
+ const subjects = discover("studio.svs", golden).subjects;
+ assert.equal(new Set(subjects.map((subject) => subject.key)).size, subjects.length);
+ const alice = subjects.find((subject) => subject.path === "caption.alice")!;
+ const bob = subjects.find((subject) => subject.path === "caption.bob")!;
+ const fill = (value: unknown) => (value as Record<string, unknown>)["fill"];
+ assert.equal(fill(alice.parameters), "#73FBD3");
+ assert.notEqual(fill(alice.parameters), fill(bob.parameters));
+});
+
+test("a source that is not a stylesheet is refused by name", () => {
+ assert.throws(
+ () => discover("main.svml", '<?svml using="@narratage/text@1"?>\n<svml/>\n'),
+ /not a stylesheet/u,
+ );
+});
+
+test("browsing cannot leave the repository", () => {
+ assert.equal(within(repoRoot, "examples"), `${repoRoot}/examples`);
+ assert.equal(within(repoRoot, "."), repoRoot);
+ // Containment is checked on the resolved path, so traversal is refused
+ // however it is spelled.
+ assert.equal(within(repoRoot, ".."), undefined);
+ assert.equal(within(repoRoot, "examples/../.."), undefined);
+ assert.equal(within(repoRoot, "/etc/passwd"), undefined);
+ // A sibling directory whose name merely starts with the root is not inside it.
+ assert.equal(within("/srv/app", "/srv/app-secrets/key"), undefined);
+});
diff --git a/tools/playground-source-bytes.test.mjs b/tools/playground-source-bytes.test.mjs
new file mode 100644
index 00000000..6b09f1d9
--- /dev/null
+++ b/tools/playground-source-bytes.test.mjs
@@ -0,0 +1,39 @@
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+/**
+ * Source files must stay text.
+ *
+ * A raw control byte in a string literal works at runtime and reads as an
+ * ordinary separator in an editor, so it survives review — but git then treats
+ * the file as binary and stops producing diffs or merging it at all. Writing
+ * the escape sequence instead costs nothing and keeps the file reviewable.
+ */
+
+const root = fileURLToPath(new URL("..", import.meta.url));
+
+function tracked() {
+ return execFileSync(
+ "git",
+ ["ls-files", "-c", "-o", "--exclude-standard", "tools/playground", "test"],
+ { cwd: root, encoding: "utf8" },
+ ).trim().split("\n").filter((path) => /\.(?:ts|mjs|js|html|css|json)$/u.test(path));
+}
+
+test("no playground source carries a raw control byte", () => {
+ const offenders = [];
+ for (const path of tracked()) {
+ const bytes = readFileSync(new URL(path, new URL("..", import.meta.url)));
+ for (const [index, byte] of bytes.entries()) {
+ // Tab, newline and carriage return are the only control bytes text needs.
+ if (byte < 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) {
+ offenders.push(`${path}: byte 0x${byte.toString(16).padStart(2, "0")} at offset ${index}`);
+ break;
+ }
+ }
+ }
+ assert.deepEqual(offenders, [], `write the escape sequence instead:\n${offenders.join("\n")}`);
+});
diff --git a/tools/playground/src/server/browse.ts b/tools/playground/src/server/browse.ts
new file mode 100644
index 00000000..77bd2252
--- /dev/null
+++ b/tools/playground/src/server/browse.ts
@@ -0,0 +1,129 @@
+import { readdir, readFile, stat } from "node:fs/promises";
+import type { ServerResponse } from "node:http";
+import { extname, relative, resolve, sep } from "node:path";
+import type { Plugin } from "vite";
+
+/**
+ * A read-only window onto the repository for the browser.
+ *
+ * A browser cannot list a directory, and the File System Access API cannot
+ * follow `src: ./assets/Inter-SemiBold.woff2` out of a stylesheet without a
+ * second grant for its parent. Serving the listing from the dev server avoids
+ * both, and keeps every path decision on this side where it can be checked.
+ */
+
+const SHEET = new Set([".svs"]);
+const MEDIA = new Set([
+ ".png", ".jpg", ".jpeg", ".webp", ".gif", ".avif",
+ ".mp4", ".webm", ".mov", ".m4a", ".mp3", ".wav",
+ ".woff2", ".woff", ".otf", ".ttf",
+]);
+
+const MEDIA_TYPES: Readonly<Record<string, string>> = {
+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
+ ".webp": "image/webp", ".gif": "image/gif", ".avif": "image/avif",
+ ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime",
+ ".m4a": "audio/mp4", ".mp3": "audio/mpeg", ".wav": "audio/wav",
+ ".woff2": "font/woff2", ".woff": "font/woff",
+ ".otf": "font/otf", ".ttf": "font/ttf",
+};
+
+const SKIP = new Set(["node_modules", ".git", ".svml", "dist", ".DS_Store"]);
+
+export type DirectoryEntry = {
+ readonly name: string;
+ readonly kind: "dir" | "file";
+};
+
+export type DirectoryListing = {
+ readonly dir: string;
+ readonly parent: string | undefined;
+ readonly entries: readonly DirectoryEntry[];
+};
+
+/**
+ * Resolves a request path inside the root, or returns undefined.
+ *
+ * Containment is checked after resolution, on the resolved path, so `..` and
+ * symlinked escapes are both refused rather than merely discouraged.
+ */
+export function within(root: string, requested: string): string | undefined {
+ const target = resolve(root, requested);
+ if (target !== root && !target.startsWith(root + sep)) return undefined;
+ return target;
+}
+
+export async function listDirectory(root: string, dir: string): Promise<DirectoryListing> {
+ const target = within(root, dir);
+ if (target === undefined) throw new Error("Path is outside the repository.");
+ const entries = await readdir(target, { withFileTypes: true });
+ const visible = entries
+ .filter((entry) => !SKIP.has(entry.name) && !entry.name.startsWith("."))
+ .flatMap((entry): DirectoryEntry[] => {
+ if (entry.isDirectory()) return [{ name: entry.name, kind: "dir" }];
+ const extension = extname(entry.name).toLowerCase();
+ if (!SHEET.has(extension) && !MEDIA.has(extension)) return [];
+ return [{ name: entry.name, kind: "file" }];
+ });
+ visible.sort((left, right) =>
+ left.kind === right.kind
+ ? left.name.localeCompare(right.name)
+ : left.kind === "dir" ? -1 : 1);
+ const here = relative(root, target);
+ return {
+ dir: here,
+ parent: target === root ? undefined : relative(root, resolve(target, "..")),
+ entries: visible,
+ };
+}
+
+function fail(response: ServerResponse, status: number, message: string): void {
+ response.statusCode = status;
+ response.setHeader("content-type", "application/json");
+ response.end(JSON.stringify({ error: message }));
+}
+
+function json(response: ServerResponse, value: unknown): void {
+ response.setHeader("content-type", "application/json");
+ response.end(JSON.stringify(value));
+}
+
+export function playgroundBrowsePlugin(root: string): Plugin {
+ return {
+ name: "svml-playground-browse",
+ configureServer(server) {
+ server.middlewares.use("/__pg", (request, response, next) => {
+ void (async () => {
+ const url = new URL(request.url ?? "/", "http://localhost");
+ try {
+ if (url.pathname === "/list") {
+ json(response, await listDirectory(root, url.searchParams.get("dir") ?? "."));
+ return;
+ }
+ const file = url.searchParams.get("file");
+ if (file === null) { fail(response, 400, "file is required"); return; }
+ const target = within(root, file);
+ if (target === undefined) { fail(response, 403, "Path is outside the repository."); return; }
+ const info = await stat(target);
+ if (!info.isFile()) { fail(response, 404, "Not a file."); return; }
+
+ if (url.pathname === "/read") {
+ response.setHeader("content-type", "text/plain; charset=utf-8");
+ response.end(await readFile(target, "utf8"));
+ return;
+ }
+ if (url.pathname === "/asset") {
+ const extension = extname(target).toLowerCase();
+ response.setHeader("content-type", MEDIA_TYPES[extension] ?? "application/octet-stream");
+ response.end(await readFile(target));
+ return;
+ }
+ next();
+ } catch (error) {
+ fail(response, 404, error instanceof Error ? error.message : String(error));
+ }
+ })();
+ });
+ },
+ };
+}
diff --git a/tools/playground/src/svml.ts b/tools/playground/src/svml.ts
index bbf1b3db..a13c06e6 100644
--- a/tools/playground/src/svml.ts
+++ b/tools/playground/src/svml.ts
@@ -53,3 +53,9 @@ export type {
export { renderTextTrack, sealTextTrackProgram } from "@narratage/text-track";
export type { TextItem, TextTrackProgram } from "@narratage/text-track";
+
+export { parseSvs } from "@narratage/svs";
+export type { ParsedSvsSheet, SvsRecipe } from "@narratage/svs";
+
+export { maskSourceHeader, parseSourceHeader } from "@narratage/source";
+export type { SourceHeader } from "@narratage/source";
diff --git a/tools/playground/src/svs/discover.ts b/tools/playground/src/svs/discover.ts
new file mode 100644
index 00000000..25ee4495
--- /dev/null
+++ b/tools/playground/src/svs/discover.ts
@@ -0,0 +1,100 @@
+import { matchRecipe } from "../registry/index.js";
+import type { PreviewComponent } from "../registry/index.js";
+import { maskSourceHeader, parseSourceHeader, parseSvs } from "../svml.js";
+import type { CanonicalValue } from "../svml.js";
+
+/** The Film Recipe key set, from packages/film/src/surface.ts. */
+const FILM_KEYS = ["background", "frame-rate", "height", "width"];
+
+export type CanvasOffer = {
+ readonly path: string;
+ readonly width: number;
+ readonly height: number;
+ readonly fps: number;
+ readonly clearColor: string;
+};
+
+export type PreviewSubject = {
+ readonly key: string;
+ readonly path: string;
+ readonly component: PreviewComponent;
+ readonly parameters: CanonicalValue;
+ readonly content: CanonicalValue;
+};
+
+export type Discovery = {
+ readonly sheetId: string | undefined;
+ readonly subjects: readonly PreviewSubject[];
+ /** Film Recipes are not previewable; they say how big the frame is. */
+ readonly canvases: readonly CanvasOffer[];
+ /** Everything else, named so the gaps are visible rather than silent. */
+ readonly unmatched: readonly { readonly path: string; readonly keys: readonly string[] }[];
+};
+
+function keySet(names: readonly string[]): string {
+ return [...names].sort().join("\u0000");
+}
+
+function numberOf(value: CanonicalValue | undefined, fallback: number): number {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : fallback;
+}
+
+/**
+ * Reads a stylesheet as a list of things to preview.
+ *
+ * A sheet is a discovery source, never a dependency: what it produces is form
+ * values, and from that point the form is the only source of truth. An
+ * unmatched Recipe is reported rather than dropped — `font.*` and
+ * `caption.short-cues` are real Recipes the playground simply cannot draw, and
+ * saying so is more useful than showing nothing.
+ */
+export function discover(name: string, source: string): Discovery {
+ // The Source Header is mandatory and is not the sheet. Masking it rather than
+ // slicing it is what the compiler does: every offset a Recipe reports still
+ // points at the right place in the file the author is looking at.
+ const header = parseSourceHeader(name, source);
+ if (!header.using.startsWith("@narratage/svs@")) {
+ throw new Error(`${name} is a ${header.using} source, not a stylesheet.`);
+ }
+ const sheet = parseSvs(name, maskSourceHeader(source, header));
+ const subjects: PreviewSubject[] = [];
+ const canvases: CanvasOffer[] = [];
+ const unmatched: { path: string; keys: readonly string[] }[] = [];
+
+ for (const [index, parsed] of sheet.recipes.entries()) {
+ const recipe = parsed.value;
+ const keys = Object.keys(recipe.properties);
+
+ if (keySet(keys) === keySet(FILM_KEYS)) {
+ canvases.push({
+ path: recipe.path,
+ width: numberOf(recipe.properties["width"], 1080),
+ height: numberOf(recipe.properties["height"], 1920),
+ fps: numberOf(recipe.properties["frame-rate"], 30),
+ clearColor: String(recipe.properties["background"] ?? "#000000"),
+ });
+ continue;
+ }
+
+ const component = matchRecipe(recipe.properties);
+ if (component === undefined || component.fromRecipe === undefined) {
+ unmatched.push({ path: recipe.path, keys: [...keys].sort() });
+ continue;
+ }
+ subjects.push({
+ key: `${index}:${recipe.path}`,
+ path: recipe.path,
+ component,
+ parameters: component.fromRecipe(recipe.properties),
+ content: component.defaults().content,
+ });
+ }
+
+ return {
+ ...(sheet.id === undefined ? { sheetId: undefined } : { sheetId: sheet.id }),
+ subjects,
+ canvases,
+ unmatched,
+ };
+}
diff --git a/tools/playground/src/ui/browse.ts b/tools/playground/src/ui/browse.ts
new file mode 100644
index 00000000..a9d43a34
--- /dev/null
+++ b/tools/playground/src/ui/browse.ts
@@ -0,0 +1,112 @@
+export const BROWSE_CSS = `
+.browse { display: flex; flex-direction: column; gap: 5px; }
+.browse-path {
+ color: var(--muted); font-size: 11px; font-family: ui-monospace, monospace;
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; direction: rtl; text-align: left;
+}
+.browse-list {
+ max-height: 190px; overflow-y: auto; border: 1px solid var(--line);
+ border-radius: 6px; background: #131316;
+}
+.browse-list button {
+ display: block; width: 100%; text-align: left; border: 0; background: none;
+ color: var(--text); padding: 4px 9px; font: inherit; font-size: 12px; cursor: pointer;
+}
+.browse-list button:hover { background: #1c1c21; }
+.browse-list button.dir { color: var(--muted); }
+.browse-list button.sheet { color: var(--accent); }
+.browse-empty { padding: 8px 9px; color: var(--muted); font-size: 12px; }
+`;
+
+type Entry = { readonly name: string; readonly kind: "dir" | "file" };
+type Listing = {
+ readonly dir: string;
+ readonly parent: string | undefined;
+ readonly entries: readonly Entry[];
+};
+
+async function list(dir: string): Promise<Listing> {
+ const response = await fetch(`/__pg/list?dir=${encodeURIComponent(dir)}`);
+ if (!response.ok) throw new Error(`Cannot read ${dir || "the repository root"}.`);
+ return await response.json() as Listing;
+}
+
+export async function readSheet(path: string): Promise<string> {
+ const response = await fetch(`/__pg/read?file=${encodeURIComponent(path)}`);
+ if (!response.ok) throw new Error(`Cannot read ${path}.`);
+ return await response.text();
+}
+
+export type Browser = {
+ readonly element: HTMLElement;
+ open(dir: string): void;
+};
+
+/**
+ * A directory list, starting at the repository root.
+ *
+ * Only directories and stylesheets are offered, because those are the only
+ * things this panel can act on. A folder with neither reads as empty, which is
+ * the truth about what the playground can do with it.
+ */
+export function createBrowser(onSheet: (path: string) => void): Browser {
+ const element = document.createElement("div");
+ element.className = "browse";
+ const path = document.createElement("div");
+ path.className = "browse-path";
+ const listing = document.createElement("div");
+ listing.className = "browse-list";
+ element.append(path, listing);
+
+ let current = ".";
+
+ function open(dir: string): void {
+ current = dir;
+ void list(dir).then((result) => {
+ path.textContent = result.dir === "" ? "/" : `/${result.dir}`;
+ path.title = path.textContent;
+ listing.replaceChildren();
+
+ if (result.parent !== undefined) {
+ const up = document.createElement("button");
+ up.type = "button";
+ up.className = "dir";
+ up.textContent = "../";
+ up.addEventListener("click", () => open(result.parent!));
+ listing.append(up);
+ }
+ for (const entry of result.entries) {
+ const item = document.createElement("button");
+ item.type = "button";
+ const child = result.dir === "" ? entry.name : `${result.dir}/${entry.name}`;
+ if (entry.kind === "dir") {
+ item.className = "dir";
+ item.textContent = `${entry.name}/`;
+ item.addEventListener("click", () => open(child));
+ } else if (entry.name.endsWith(".svs")) {
+ item.className = "sheet";
+ item.textContent = entry.name;
+ item.addEventListener("click", () => onSheet(child));
+ } else {
+ continue;
+ }
+ listing.append(item);
+ }
+ if (listing.childElementCount === 0) {
+ const empty = document.createElement("div");
+ empty.className = "browse-empty";
+ empty.textContent = "No folders or stylesheets here.";
+ listing.append(empty);
+ }
+ }).catch((error: unknown) => {
+ listing.replaceChildren();
+ const failed = document.createElement("div");
+ failed.className = "browse-empty";
+ failed.textContent = error instanceof Error ? error.message : String(error);
+ listing.append(failed);
+ });
+ }
+
+ open(current);
+ return { element, open };
+}
diff --git a/tools/playground/src/ui/gallery.ts b/tools/playground/src/ui/gallery.ts
new file mode 100644
index 00000000..5c304662
--- /dev/null
+++ b/tools/playground/src/ui/gallery.ts
@@ -0,0 +1,138 @@
+import { renderPreview } from "../preview/render.js";
+import type { PreviewSubject } from "../svs/discover.js";
+import { sealProgramSpace } from "../svml.js";
+
+export const GALLERY_CSS = `
+.gallery { flex: 1; min-width: 0; overflow-y: auto; background: #0d0d10; padding: 18px; }
+.gallery-grid { display: flex; flex-wrap: wrap; gap: 18px; align-content: flex-start; }
+.tile { display: flex; flex-direction: column; gap: 7px; cursor: pointer; }
+.tile-frame {
+ position: relative; overflow: hidden; background: #000;
+ box-shadow: 0 0 0 1px var(--line); border-radius: 3px;
+}
+.tile:hover .tile-frame { box-shadow: 0 0 0 1px var(--accent); }
+.tile-frame iframe { position: absolute; top: 0; left: 0; border: 0; transform-origin: top left; }
+.tile-name { font-size: 12px; font-family: ui-monospace, monospace; }
+.tile-kind { font-size: 11px; color: var(--muted); }
+.tile-error {
+ position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
+ padding: 10px; color: var(--danger); font-size: 11px; text-align: center;
+ font-family: ui-monospace, monospace; background: #2a1416;
+}
+.gallery-note { color: var(--muted); font-size: 12px; margin: 22px 0 7px; }
+.gallery-unmatched { display: flex; flex-direction: column; gap: 3px; }
+.gallery-unmatched code { font-size: 11px; color: var(--muted); font-family: ui-monospace, monospace; }
+.gallery-unmatched b { color: var(--text); font-weight: 500; }
+`;
+
+const TILE_WIDTH = 250;
+
+export type GalleryInput = {
+ readonly subjects: readonly PreviewSubject[];
+ readonly unmatched: readonly { readonly path: string; readonly keys: readonly string[] }[];
+ readonly canvas: { readonly width: number; readonly height: number; readonly clearColor: string };
+ readonly fps: number;
+ readonly durationSec: number;
+ readonly onFocus: (subject: PreviewSubject) => void;
+};
+
+/**
+ * Every Recipe in a sheet, previewed side by side.
+ *
+ * Each tile is an independent document at composition scale, shrunk by
+ * transform. Tiles hold one representative frame rather than a scrubber: the
+ * gallery answers "what is in this stylesheet", and a Recipe you want to work
+ * on gets focused into the single stage.
+ */
+export function renderGallery(input: GalleryInput): HTMLElement {
+ const element = document.createElement("div");
+ element.className = "gallery";
+ const grid = document.createElement("div");
+ grid.className = "gallery-grid";
+ element.append(grid);
+
+ const scale = TILE_WIDTH / input.canvas.width;
+ const height = Math.round(input.canvas.height * scale);
+
+ for (const subject of input.subjects) {
+ const tile = document.createElement("div");
+ tile.className = "tile";
+ const frame = document.createElement("div");
+ frame.className = "tile-frame";
+ frame.style.width = `${TILE_WIDTH}px`;
+ frame.style.height = `${height}px`;
+
+ try {
+ const programSpace = sealProgramSpace({
+ contract: "svml.program-space@1",
+ durationSec: input.durationSec,
+ frameRate: { numerator: input.fps, denominator: 1 },
+ });
+ const preview = renderPreview({
+ id: subject.component.id,
+ canvas: input.canvas,
+ programSpace,
+ tracks: subject.component.build({
+ parameters: subject.parameters,
+ content: subject.content,
+ programSpace,
+ canvas: input.canvas,
+ }),
+ });
+ const view = document.createElement("iframe");
+ view.title = subject.path;
+ view.style.width = `${input.canvas.width}px`;
+ view.style.height = `${input.canvas.height}px`;
+ view.style.transform = `scale(${scale})`;
+ view.srcdoc = preview.srcdoc;
+ // A third of the way in shows a Present that has settled rather than one
+ // still animating in from nothing.
+ const at = Math.floor(preview.frameCount / 3);
+ view.addEventListener("load", () => {
+ (view.contentWindow as { __svmlSeekFrame?: (frame: number) => void } | null)
+ ?.__svmlSeekFrame?.(at);
+ });
+ frame.append(view);
+ } catch (error) {
+ const failed = document.createElement("div");
+ failed.className = "tile-error";
+ failed.textContent = error instanceof Error ? error.message : String(error);
+ frame.append(failed);
+ }
+
+ const name = document.createElement("div");
+ name.className = "tile-name";
+ name.textContent = subject.path;
+ const kind = document.createElement("div");
+ kind.className = "tile-kind";
+ kind.textContent = subject.component.label;
+ tile.append(frame, name, kind);
+ tile.addEventListener("click", () => input.onFocus(subject));
+ grid.append(tile);
+ }
+
+ if (input.subjects.length === 0) {
+ const empty = document.createElement("div");
+ empty.className = "gallery-note";
+ empty.textContent = "This stylesheet declares nothing the playground can draw yet.";
+ element.append(empty);
+ }
+
+ if (input.unmatched.length > 0) {
+ const note = document.createElement("div");
+ note.className = "gallery-note";
+ note.textContent = `${input.unmatched.length} Recipe(s) have no preview — their property sets match no component:`;
+ const list = document.createElement("div");
+ list.className = "gallery-unmatched";
+ for (const entry of input.unmatched) {
+ const line = document.createElement("code");
+ const path = document.createElement("b");
+ path.textContent = entry.path;
+ line.append(path, document.createTextNode(` { ${entry.keys.join(", ")} }`));
+ list.append(line);
+ }
+ element.append(note, list);
+ }
+
+ return element;
+}
diff --git a/tools/playground/src/ui/shell.ts b/tools/playground/src/ui/shell.ts
index 7e110016..15997c79 100644
--- a/tools/playground/src/ui/shell.ts
+++ b/tools/playground/src/ui/shell.ts
@@ -1,9 +1,13 @@
import { REGISTRY, componentById } from "../registry/index.js";
import type { PreviewComponent } from "../registry/index.js";
import { renderPreview } from "../preview/render.js";
+import { discover } from "../svs/discover.js";
+import type { Discovery, PreviewSubject } from "../svs/discover.js";
import { sealProgramSpace } from "../svml.js";
import type { CanonicalValue } from "../svml.js";
+import { BROWSE_CSS, createBrowser, readSheet } from "./browse.js";
import { FORM_CSS, buildForm } from "./form.js";
+import { GALLERY_CSS, renderGallery } from "./gallery.js";
import { createStage } from "./stage.js";
const CSS = `
@@ -21,9 +25,18 @@ const CSS = `
.rail-canvas { display: grid; grid-template-columns: auto 1fr auto 1fr; gap: 6px; align-items: center; margin-top: 9px; }
.rail-canvas span { color: var(--muted); font-size: 11px; }
.section { color: var(--accent); font-size: 11px; letter-spacing: .05em;
- text-transform: uppercase; margin: 14px 0 4px; }
+ text-transform: uppercase; margin: 14px 0 4px; display: flex; justify-content: space-between; align-items: baseline; }
.section:first-child { margin-top: 0; }
+.section button {
+ border: 0; background: none; color: var(--muted); cursor: pointer;
+ font: inherit; font-size: 11px; text-transform: none; letter-spacing: 0; padding: 0;
+}
+.section button:hover { color: var(--text); }
+.sheet-note { color: var(--muted); font-size: 12px; margin-top: 6px; }
+.sheet-note b { color: var(--accent); font-weight: 500; }
+${BROWSE_CSS}
${FORM_CSS}
+${GALLERY_CSS}
`;
type Draft = { parameters: CanonicalValue; content: CanonicalValue };
@@ -64,7 +77,8 @@ export function mountShell(root: HTMLElement): void {
}
const stage = createStage();
- root.append(rail, stage.element);
+ let main: HTMLElement = stage.element;
+ root.append(rail, main);
const canvas = { width: 1080, height: 1920, clearColor: "#09090b" };
const space = { fps: 30, durationSec: 4 };
@@ -73,65 +87,156 @@ export function mountShell(root: HTMLElement): void {
fpsInput.value = String(space.fps);
durationInput.value = String(space.durationSec);
- // One draft per component, so switching away and back keeps your edits.
+ // Mode B keeps one draft per component; mode A keeps one per Recipe, so
+ // switching between two captions from a sheet does not merge their edits.
const drafts = new Map<string, Draft>();
let active: PreviewComponent = REGISTRY[0]!;
+ let activeKey = active.id;
+ let sheet: { name: string; discovery: Discovery } | undefined;
- function draft(component: PreviewComponent): Draft {
- const existing = drafts.get(component.id);
+ function draft(key: string, make: () => Draft): Draft {
+ const existing = drafts.get(key);
if (existing !== undefined) return existing;
- const created = component.defaults();
- drafts.set(component.id, created);
+ const created = make();
+ drafts.set(key, created);
return created;
}
+ function currentDraft(): Draft {
+ return draft(activeKey, () => active.defaults());
+ }
+
+ function swapMain(next: HTMLElement): void {
+ main.replaceWith(next);
+ main = next;
+ }
+
let queued = 0;
function schedule(): void {
if (queued !== 0) clearTimeout(queued);
queued = window.setTimeout(render, 120);
}
+ function programSpace() {
+ return sealProgramSpace({
+ contract: "svml.program-space@1",
+ durationSec: space.durationSec,
+ frameRate: { numerator: space.fps, denominator: 1 },
+ });
+ }
+
function render(): void {
- const current = draft(active);
+ if (main !== stage.element) swapMain(stage.element);
+ const current = currentDraft();
try {
- const programSpace = sealProgramSpace({
- contract: "svml.program-space@1",
- durationSec: space.durationSec,
- frameRate: { numerator: space.fps, denominator: 1 },
- });
- const tracks = active.build({
- parameters: current.parameters,
- content: current.content,
- programSpace,
+ const resolved = programSpace();
+ stage.show(renderPreview({
+ id: active.id,
canvas,
- });
- stage.show(renderPreview({ id: active.id, canvas, programSpace, tracks }));
+ programSpace: resolved,
+ tracks: active.build({
+ parameters: current.parameters,
+ content: current.content,
+ programSpace: resolved,
+ canvas,
+ }),
+ }));
} catch (error) {
// The compiler's own message, verbatim. The last good frame stays up.
stage.showError(error instanceof Error ? error.message : String(error));
}
}
- function renderForm(): void {
- const current = draft(active);
+ function showGallery(): void {
+ if (sheet === undefined) return;
+ swapMain(renderGallery({
+ subjects: sheet.discovery.subjects,
+ unmatched: sheet.discovery.unmatched,
+ canvas,
+ fps: space.fps,
+ durationSec: space.durationSec,
+ onFocus: focusSubject,
+ }));
+ }
+
+ function focusSubject(subject: PreviewSubject): void {
+ active = subject.component;
+ activeKey = subject.key;
+ picker.value = subject.component.id;
+ draft(subject.key, () => ({ parameters: subject.parameters, content: subject.content }));
+ renderRail();
+ render();
+ }
+
+ function loadSheet(path: string): void {
+ void readSheet(path).then((source) => {
+ const discovery = discover(path, source);
+ sheet = { name: path, discovery };
+ // A Film Recipe is not a preview subject; it says how big the frame is.
+ const offer = discovery.canvases[0];
+ if (offer !== undefined) {
+ canvas.width = offer.width;
+ canvas.height = offer.height;
+ canvas.clearColor = offer.clearColor;
+ space.fps = offer.fps;
+ widthInput.value = String(offer.width);
+ heightInput.value = String(offer.height);
+ fpsInput.value = String(offer.fps);
+ }
+ renderRail();
+ showGallery();
+ }).catch((error: unknown) => {
+ sheet = undefined;
+ renderRail();
+ stage.showError(error instanceof Error ? error.message : String(error));
+ });
+ }
+
+ const browser = createBrowser(loadSheet);
+
+ function section(title: string, action?: { label: string; run: () => void }): HTMLElement {
+ const element = document.createElement("div");
+ element.className = "section";
+ const caption = document.createElement("span");
+ caption.textContent = title;
+ element.append(caption);
+ if (action !== undefined) {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.textContent = action.label;
+ button.addEventListener("click", action.run);
+ element.append(button);
+ }
+ return element;
+ }
+
+ function renderRail(): void {
+ const current = currentDraft();
body.replaceChildren();
- const parameters = document.createElement("div");
- parameters.className = "section";
- parameters.textContent = "Parameters";
- const content = document.createElement("div");
- content.className = "section";
- content.textContent = "Content";
- body.append(
- parameters,
- buildForm(active.parameters, current.parameters, active.hints ?? {}, schedule),
- content,
- buildForm(active.content, current.content, active.hints ?? {}, schedule),
- );
+
+ body.append(section("Stylesheet"), browser.element);
+ if (sheet !== undefined) {
+ const note = document.createElement("div");
+ note.className = "sheet-note";
+ const count = sheet.discovery.subjects.length;
+ note.append(document.createTextNode(`${count} previewable Recipe(s) in `));
+ const id = document.createElement("b");
+ id.textContent = sheet.discovery.sheetId ?? sheet.name;
+ note.append(id);
+ body.append(note, section("", { label: "Show all", run: showGallery }));
+ }
+
+ body.append(section("Parameters"));
+ body.append(buildForm(active.parameters, current.parameters, active.hints ?? {}, schedule));
+ body.append(section("Content"));
+ body.append(buildForm(active.content, current.content, active.hints ?? {}, schedule));
}
picker.addEventListener("input", () => {
active = componentById(picker.value) ?? active;
- renderForm();
+ // Choosing from the list leaves any focused Recipe behind.
+ activeKey = active.id;
+ renderRail();
render();
});
@@ -147,6 +252,6 @@ export function mountShell(root: HTMLElement): void {
});
}
- renderForm();
+ renderRail();
render();
}
diff --git a/tools/playground/vite.config.ts b/tools/playground/vite.config.ts
index 47611345..5954dc34 100644
--- a/tools/playground/vite.config.ts
+++ b/tools/playground/vite.config.ts
@@ -4,6 +4,8 @@ import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";
+import { playgroundBrowsePlugin } from "./src/server/browse.js";
+
const here = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(here, "../..");
@@ -49,4 +51,5 @@ export default defineConfig({
// The playground reads sources and media from anywhere in the repository.
fs: { allow: [repoRoot] },
},
+ plugins: [playgroundBrowsePlugin(repoRoot)],
});