Add HyperFrames skills
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011h6NB8JQtfPc6eRCefEzBB
This commit is contained in:
964 files changed
+142321
No files matched your search
@@ -0,0 +1,56 @@
|
||||
// assets.mjs — stage frame-named capture assets into assets/.
|
||||
// Shared by stage-assets.mjs (Step 4 close, BEFORE the frame workers run) and
|
||||
// assemble-index.mjs (Step 5, idempotent backstop). Only assets a frame names
|
||||
// in `asset_candidates` are staged; unnamed assets never reach the project.
|
||||
// asset_candidates value form: "assets/<basename> — desc; assets/… — …".
|
||||
|
||||
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { basename, join } from "node:path";
|
||||
|
||||
export function basenamesFromCandidates(value) {
|
||||
if (typeof value !== "string") return [];
|
||||
return value
|
||||
.split(";")
|
||||
.map((seg) => seg.split(/\s+[—–-]\s+/)[0].trim()) // strip the " — description"
|
||||
.filter(Boolean)
|
||||
.map((p) => basename(p.replace(/^assets\//, "")));
|
||||
}
|
||||
|
||||
// Copy each frame's asset_candidates from capture/{assets,assets/videos,
|
||||
// assets/svgs, screenshots} into assets/. Already-staged files are left as is
|
||||
// (first-wins), so calling this twice is safe. Returns { staged, wanted, anomalies }.
|
||||
export function stageAssets({ hyperframesDir, frames }) {
|
||||
const wanted = new Set();
|
||||
for (const f of frames) {
|
||||
for (const b of basenamesFromCandidates(f.extra?.asset_candidates)) wanted.add(b);
|
||||
}
|
||||
const captureDirs = [
|
||||
join(hyperframesDir, "capture/assets"),
|
||||
join(hyperframesDir, "capture/assets/videos"), // videos download into a subdir
|
||||
join(hyperframesDir, "capture/assets/svgs"), // inline SVGs extract into a subdir
|
||||
join(hyperframesDir, "capture/screenshots"),
|
||||
];
|
||||
const assetsDir = join(hyperframesDir, "assets");
|
||||
const anomalies = [];
|
||||
let staged = 0;
|
||||
if (wanted.size > 0) {
|
||||
mkdirSync(assetsDir, { recursive: true });
|
||||
for (const b of wanted) {
|
||||
const dest = join(assetsDir, b);
|
||||
if (existsSync(dest)) {
|
||||
staged++;
|
||||
continue;
|
||||
} // first-wins / already staged
|
||||
const src = captureDirs.map((d) => join(d, b)).find((p) => existsSync(p));
|
||||
if (src) {
|
||||
copyFileSync(src, dest);
|
||||
staged++;
|
||||
} else {
|
||||
anomalies.push(
|
||||
`asset "${b}" named by a frame but not found under capture/ — frame will 404 it`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { staged, wanted, anomalies };
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Music sits under narration; a silent film brings music forward.
|
||||
export const BGM_BED_VOLUME = 0.12;
|
||||
export const BGM_SILENT_VOLUME = 0.9;
|
||||
export const bgmDefaultVolume = (hasVoice) => (hasVoice ? BGM_BED_VOLUME : BGM_SILENT_VOLUME);
|
||||
@@ -0,0 +1,58 @@
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
// Capture preserves subset and variable-axis descriptors in extracted/page.html.
|
||||
// Filenames alone cannot identify a face's character coverage.
|
||||
export function stageCapturedFonts(projectDir, families) {
|
||||
const page = join(projectDir, "capture/extracted/page.html");
|
||||
const result = { faces: [], families: new Set(), files: new Set() };
|
||||
if (!existsSync(page)) return result;
|
||||
const wanted = new Set(families.map((family) => family.toLowerCase()));
|
||||
const html = readFileSync(page, "utf8");
|
||||
const copied = new Set();
|
||||
for (const style of html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/gi)) {
|
||||
const css = style[1].replace(/\/\*[\s\S]*?\*\//g, "");
|
||||
for (const match of css.matchAll(/@font-face\s*\{([^}]+)\}/gi)) {
|
||||
const body = match[1];
|
||||
const familyValue = /(?:^|;)\s*font-family\s*:\s*([^;]+)/i.exec(body)?.[1]?.trim();
|
||||
if (!familyValue) continue;
|
||||
const family = familyValue.replace(/^(['"])(.*)\1$/, "$2");
|
||||
if (!wanted.has(family.toLowerCase())) continue;
|
||||
result.families.add(family.toLowerCase());
|
||||
const source = /(?:^|;)\s*src\s*:\s*([^;]+)/i.exec(body);
|
||||
if (!source) continue;
|
||||
const sources = localFontSources(source[1], projectDir);
|
||||
if (!sources.length) {
|
||||
console.warn("Captured font has no downloaded source: " + family);
|
||||
continue;
|
||||
}
|
||||
for (const file of sources) {
|
||||
if (copied.has(file.name)) continue;
|
||||
if (!copied.size) mkdirSync(join(projectDir, "assets/fonts"), { recursive: true });
|
||||
copyFileSync(file.source, join(projectDir, file.target));
|
||||
copied.add(file.name);
|
||||
result.files.add(file.target);
|
||||
}
|
||||
const src = sources.map((file) => file.css).join(", ");
|
||||
const rule = "@font-face{" + body.replace(source[1], src) + "}";
|
||||
if (!result.faces.includes(rule)) result.faces.push(rule);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function localFontSources(source, projectDir) {
|
||||
const files = [];
|
||||
for (const match of source.matchAll(
|
||||
/url\(\s*(?:"([^"]+)"|'([^']+)'|([^\s)]+))\s*\)(\s*format\([^)]*\))?/gi,
|
||||
)) {
|
||||
const url = match[1] ?? match[2] ?? match[3];
|
||||
const name = /^assets\/fonts\/([a-z0-9_.-]+\.(?:woff2?|ttf|otf))$/i.exec(url)?.[1];
|
||||
if (!name) continue;
|
||||
const path = join(projectDir, "capture/assets/fonts", name);
|
||||
if (!existsSync(path)) continue;
|
||||
const target = "assets/fonts/captured-" + name;
|
||||
files.push({ name, source: path, target, css: 'url("' + target + '")' + (match[4] ?? "") });
|
||||
}
|
||||
return files;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// dimensions.mjs — canvas size + caption-band geometry for the product-launch
|
||||
// pipeline. Single source of truth = the STORYBOARD frontmatter `format` global
|
||||
// ("1920x1080" / "1080x1920" / "1080x1080", or a named orientation). Every
|
||||
// script and the index assembler reads the size from here; none hardcodes it.
|
||||
|
||||
// Named orientation presets. Square/portrait are 1080-based so they share the
|
||||
// long-edge pixel budget with landscape (same render-cost ballpark).
|
||||
export const ORIENTATION_PRESETS = {
|
||||
landscape: { width: 1920, height: 1080 }, // 16:9 — default
|
||||
portrait: { width: 1080, height: 1920 }, // 9:16 — reels / shorts / TikTok
|
||||
square: { width: 1080, height: 1080 }, // 1:1 — feed
|
||||
};
|
||||
|
||||
export const DEFAULT_DIMENSIONS = ORIENTATION_PRESETS.landscape;
|
||||
|
||||
function sane(w, h) {
|
||||
return Number.isFinite(w) && Number.isFinite(h) && w >= 240 && h >= 240 && w <= 8192 && h <= 8192;
|
||||
}
|
||||
|
||||
// Parse a STORYBOARD `format` global into { width, height, source }. Accepts
|
||||
// "WxH" (e.g. "1920x1080"; `x` or `×`, any inner spacing) or a named orientation;
|
||||
// falls back to landscape so a storyboard with a missing/garbled format still
|
||||
// renders (no behavior change vs the old landscape lock).
|
||||
export function parseFormat(format) {
|
||||
const s = typeof format === "string" ? format.trim().toLowerCase() : "";
|
||||
if (ORIENTATION_PRESETS[s]) return { ...ORIENTATION_PRESETS[s], source: `orientation=${s}` };
|
||||
const m = s.match(/^(\d+)\s*[x×]\s*(\d+)$/);
|
||||
if (m) {
|
||||
const w = parseInt(m[1] ?? "", 10);
|
||||
const h = parseInt(m[2] ?? "", 10);
|
||||
if (sane(w, h)) return { width: w, height: h, source: "format" };
|
||||
}
|
||||
return { ...DEFAULT_DIMENSIONS, source: "default(landscape)" };
|
||||
}
|
||||
|
||||
// Caption band geometry, derived from canvas height: the bottom ~16.67% (180px
|
||||
// at h=1080). Frame content must end `safetyPx` above the band top. Holds even
|
||||
// when captions are disabled (bottom-edge consistency).
|
||||
export const CAPTION_BAND_FRACTION = 0.1667;
|
||||
export function captionBand(height, safetyPx = 20) {
|
||||
const h = Number.isFinite(height) ? height : DEFAULT_DIMENSIONS.height;
|
||||
const bandHeight = Math.round(h * CAPTION_BAND_FRACTION);
|
||||
const bandTopY = h - bandHeight; // foreground must end at/above this y
|
||||
return { bandHeight, bandTopY, foregroundMaxY: bandTopY - safetyPx };
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// Frame packets inline the storyboard frame, blueprint and cited recipes.
|
||||
// Workflow wrappers supply resource paths and workflow-specific sections.
|
||||
// The role combines the shared worker contract with the workflow delta.
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||
import { basename, join, resolve } from "node:path";
|
||||
|
||||
export function field(block, name) {
|
||||
const match = block.match(new RegExp(`^-\\s+${name}:\\s*(.+)$`, "im"));
|
||||
return match?.[1]?.trim() ?? null;
|
||||
}
|
||||
|
||||
export function splitFrames(storyboard) {
|
||||
const matches = [...storyboard.matchAll(/^## Frame\s+([^\n]+)$/gm)];
|
||||
return matches.map((match, index) => {
|
||||
const start = match.index;
|
||||
const end = matches[index + 1]?.index ?? storyboard.length;
|
||||
return {
|
||||
heading: match[1].trim(),
|
||||
block: storyboard.slice(start, end).trim(),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function frameId(frame) {
|
||||
const src = field(frame.block, "src");
|
||||
if (!src) throw new Error(`${frame.heading}: missing src`);
|
||||
return basename(src).replace(/\.html?$/i, "");
|
||||
}
|
||||
|
||||
export function selectedFile(path, heading) {
|
||||
if (!path || !existsSync(path)) return "";
|
||||
return `\n## ${heading}\n\n${readFileSync(path, "utf8").trim()}\n`;
|
||||
}
|
||||
|
||||
function escapeRegExp(id) {
|
||||
return id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
export function knownRuleIds(animationDir) {
|
||||
const rulesDir = join(animationDir, "rules");
|
||||
if (!existsSync(rulesDir)) {
|
||||
console.warn(
|
||||
`frame-packets: no rules dir at ${rulesDir} — packets will inline no motion recipes`,
|
||||
);
|
||||
return [];
|
||||
}
|
||||
return readdirSync(rulesDir)
|
||||
.filter((name) => name.endsWith(".md"))
|
||||
.map((name) => name.replace(/\.md$/, ""));
|
||||
}
|
||||
|
||||
export function citedRules(block, ruleIds) {
|
||||
const explicit = (field(block, "rules") ?? "")
|
||||
.split(/[,\s]+/)
|
||||
.map((rule) => rule.trim())
|
||||
.filter(Boolean);
|
||||
const mentioned = ruleIds.filter((id) =>
|
||||
new RegExp(`(?<![\\w-])${escapeRegExp(id)}(?![\\w-])`, "i").test(block),
|
||||
);
|
||||
return [...new Set([...explicit, ...mentioned])].filter((id) => ruleIds.includes(id));
|
||||
}
|
||||
|
||||
// visual-design.md tells the author to write the blueprint as `<id> (Reproduce)`
|
||||
// or `<id> (Adapt)` — the qualifier is direction for the frame worker, not part of
|
||||
// the filename. Parse the field into the id it names (or null for `compose`), so
|
||||
// no caller ever resolves a raw field value against the blueprints directory.
|
||||
export function blueprintId(block) {
|
||||
const raw = field(block, "blueprint");
|
||||
if (!raw) return null;
|
||||
const id = raw.replace(/\s*\([^)]*\)\s*$/, "").trim();
|
||||
return id && id.toLowerCase() !== "compose" ? id : null;
|
||||
}
|
||||
|
||||
export function resourceSections(block, { animationDir, ruleIds, frameId }) {
|
||||
let sections = "";
|
||||
const blueprint = blueprintId(block);
|
||||
if (blueprint) {
|
||||
const blueprintsDir = join(animationDir, "blueprints");
|
||||
const path = join(blueprintsDir, `${blueprint}.md`);
|
||||
// An installed library must contain the named blueprint.
|
||||
// An absent on-demand library warns, like missing motion rules.
|
||||
if (!existsSync(blueprintsDir)) {
|
||||
console.warn(
|
||||
`frame-packets: no blueprints dir at ${blueprintsDir} — packets will inline no blueprint`,
|
||||
);
|
||||
} else if (!existsSync(path)) {
|
||||
throw new Error(`${frameId ?? "frame"}: blueprint "${blueprint}" has no file at ${path}`);
|
||||
} else {
|
||||
sections += selectedFile(path, `Selected blueprint: ${blueprint}`);
|
||||
}
|
||||
}
|
||||
for (const rule of citedRules(block, ruleIds)) {
|
||||
sections += selectedFile(
|
||||
join(animationDir, "rules", `${rule}.md`),
|
||||
`Selected motion rule: ${rule}`,
|
||||
);
|
||||
}
|
||||
return sections;
|
||||
}
|
||||
|
||||
export function buildRolePayload({ corePath, deltaPath, outDir }) {
|
||||
const core = readFileSync(corePath, "utf8").trim();
|
||||
const delta = readFileSync(deltaPath, "utf8").trim();
|
||||
const role = `${core}\n\n---\n\n${delta}\n`;
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
const path = join(outDir, "_role.md");
|
||||
writeFileSync(path, role);
|
||||
return { path, bytes: Buffer.byteLength(role) };
|
||||
}
|
||||
|
||||
export function buildFramePackets({
|
||||
projectDir,
|
||||
storyboardPath = join(projectDir, "STORYBOARD.md"),
|
||||
outDir = join(projectDir, ".hyperframes", "frame-packets"),
|
||||
maxPacketBytes = 48_000,
|
||||
animationDir,
|
||||
corePath,
|
||||
deltaPath,
|
||||
// Per-workflow hooks (all optional):
|
||||
// designTruthLine(projectDir) -> the packet's design-truth input line
|
||||
// validateFrame(frame, id) -> throw to reject a frame before packing
|
||||
// extraSections(block) -> extra packet sections appended after the rule recipes
|
||||
designTruthLine = (dir) => `- Design tokens: ${join(resolve(dir), "frame.md")}`,
|
||||
validateFrame,
|
||||
extraSections,
|
||||
}) {
|
||||
const storyboard = readFileSync(storyboardPath, "utf8");
|
||||
const frames = splitFrames(storyboard);
|
||||
if (frames.length === 0) throw new Error("STORYBOARD.md has no frame blocks");
|
||||
const ruleIds = knownRuleIds(animationDir);
|
||||
|
||||
const packets = frames.map((frame) => {
|
||||
const id = frameId(frame);
|
||||
if (validateFrame) validateFrame(frame, id);
|
||||
const packet = `# Frame packet: ${id}\n\n## Project inputs\n\n- Project: ${resolve(projectDir)}\n${designTruthLine(projectDir)}\n- RULES_DIR: ${join(animationDir, "rules")}\n\n## Assigned storyboard block\n\n${frame.block}\n${resourceSections(frame.block, { animationDir, ruleIds, frameId: id })}${extraSections ? extraSections(frame.block) : ""}`;
|
||||
const bytes = Buffer.byteLength(packet);
|
||||
if (bytes > maxPacketBytes) {
|
||||
throw new Error(`${id}: frame packet is ${bytes} bytes (limit ${maxPacketBytes})`);
|
||||
}
|
||||
return { frameId: id, path: join(outDir, `${id}.md`), bytes, packet };
|
||||
});
|
||||
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
for (const { path, packet } of packets) writeFileSync(path, packet);
|
||||
buildRolePayload({ corePath, deltaPath, outDir });
|
||||
return packets.map(({ packet: _packet, ...result }) => result);
|
||||
}
|
||||
|
||||
export function flag(argv, name, fallback) {
|
||||
const index = argv.indexOf(`--${name}`);
|
||||
return index >= 0 && argv[index + 1] ? argv[index + 1] : fallback;
|
||||
}
|
||||
|
||||
export { isMainModule } from "./main-module.mjs";
|
||||
|
||||
export function runCli({ buildFramePackets: build, buildRolePayload: buildRole }) {
|
||||
const argv = process.argv.slice(2);
|
||||
const projectDir = resolve(flag(argv, "project", "."));
|
||||
const outDir = resolve(flag(argv, "out-dir", join(projectDir, ".hyperframes", "frame-packets")));
|
||||
try {
|
||||
const packets = build({
|
||||
projectDir,
|
||||
storyboardPath: resolve(flag(argv, "storyboard", join(projectDir, "STORYBOARD.md"))),
|
||||
outDir,
|
||||
});
|
||||
const role = buildRole({ outDir });
|
||||
console.log(`✓ frame packets: ${packets.length} bounded packet(s)`);
|
||||
for (const packet of packets)
|
||||
console.log(` ${packet.frameId}: ${packet.bytes} bytes → ${packet.path}`);
|
||||
console.log(` worker role: ${role.bytes} bytes → ${role.path}`);
|
||||
} catch (error) {
|
||||
console.error(`✗ frame packets: ${error.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Audio the host app supplied survives every pass that rebuilds audio_meta.json from the storyboard: an entry
|
||||
// marked "source": "host" whose file exists. A frame the host scored takes no looked-up cue sound.
|
||||
/** The host's own entries in an earlier audio_meta.json, and why any other host-marked entry was dropped; `exists`
|
||||
* resolves a path from the project root. A frame written as "1" is frame 1. */
|
||||
export function hostAudio(previous, exists) {
|
||||
const marked = [[previous?.bgm, "path"], ...(previous?.sfx ?? []).map((s) => [s, "file"])].filter(
|
||||
([entry]) => entry?.source === "host",
|
||||
);
|
||||
const kept = new Set();
|
||||
const dropped = [];
|
||||
for (const [entry, key] of marked) {
|
||||
const path = entry[key];
|
||||
if (typeof path !== "string") dropped.push(`a host entry has no "${key}"`);
|
||||
else if (!exists(path)) dropped.push(`${path} is not on disk`);
|
||||
else kept.add(entry);
|
||||
}
|
||||
const bgm = kept.has(previous?.bgm) ? previous.bgm : null;
|
||||
const sfx = (previous?.sfx ?? [])
|
||||
.filter((s) => kept.has(s))
|
||||
.map((s) => ({ ...s, frame: Number(s.frame) }));
|
||||
return { bgm, sfx, frames: new Set(sfx.map((s) => s.frame)), dropped };
|
||||
}
|
||||
|
||||
/** `rebuilt` with the host's bed and sounds put back; the host's bed wins over a looked-up one. */
|
||||
export function keepHostAudio(rebuilt, host) {
|
||||
const looked = (rebuilt.sfx ?? []).filter((s) => !host.frames.has(s.frame));
|
||||
return { ...rebuilt, bgm: host.bgm ?? rebuilt.bgm, sfx: [...host.sfx, ...looked] };
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { realpathSync } from "node:fs";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
// Node resolves symlinks in the main module's import.meta.url but argv[1] keeps the invoked
|
||||
// spelling (a symlinked skills dir, or /tmp vs /private/tmp on macOS), so compare real paths.
|
||||
export function isMainModule(importMetaUrl) {
|
||||
if (!process.argv[1]) return false;
|
||||
try {
|
||||
return pathToFileURL(realpathSync(process.argv[1])).href === importMetaUrl;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// pad-frame-duration.mjs — keeps a frame's own #root/clip data-duration in
|
||||
// sync with the padded index.html wrapper duration transitions.mjs computes.
|
||||
//
|
||||
// The frame's OWN internal file declares its #root/clip data-duration to the
|
||||
// STORYBOARD's content-only length (frame-worker.md: duration is "fixed
|
||||
// upstream"). When an outgoing transition pads the index.html WRAPPER's
|
||||
// data-duration to cover the transition tail, the frame's own internal
|
||||
// duration is left short — the render engine clip-gates the sub-composition's
|
||||
// visible content at that shorter value, so content vanishes abruptly at
|
||||
// content-end instead of fading gracefully through the wrapper's extended
|
||||
// fade-out tween. Pad the frame's own file to match so both durations agree.
|
||||
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
export function padFrameInternalDuration(hyperframesDir, frameSrc, frameId, newDuration) {
|
||||
const framePath = resolve(hyperframesDir, frameSrc);
|
||||
let html;
|
||||
try {
|
||||
html = readFileSync(framePath, "utf8");
|
||||
} catch (err) {
|
||||
if (err?.code === "ENOENT") return;
|
||||
throw err;
|
||||
}
|
||||
const tagRe = /<[a-z][\w:-]*\s[^<>]*?>/gi;
|
||||
let m;
|
||||
while ((m = tagRe.exec(html)) !== null) {
|
||||
const tag = m[0];
|
||||
if (!tag.includes(`data-composition-id="${frameId}"`)) continue;
|
||||
if (!/data-duration="[\d.]+"/.test(tag)) continue;
|
||||
const newTag = tag.replace(/data-duration="[\d.]+"/, `data-duration="${newDuration}"`);
|
||||
if (newTag === tag) return;
|
||||
writeFileSync(framePath, html.slice(0, m.index) + newTag + html.slice(m.index + tag.length));
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { padFrameInternalDuration } from "./pad-frame-duration.mjs";
|
||||
|
||||
// Regression: an outgoing transition pads the index.html WRAPPER's
|
||||
// data-duration to cover the transition tail, but the frame's own internal
|
||||
// file kept its shorter content-only duration, so the render engine
|
||||
// clip-gated the sub-composition's visible content at the shorter value —
|
||||
// content vanished abruptly instead of fading through the wrapper's
|
||||
// extended fade-out tween. A user diagnosed and verified this fix
|
||||
// themselves: pad the frame's own #root/clip data-duration to match.
|
||||
test("padFrameInternalDuration pads the matching frame's own data-duration", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "transitions-pad-"));
|
||||
const framesDir = join(dir, "compositions", "frames");
|
||||
mkdirSync(framesDir, { recursive: true });
|
||||
const frameSrc = "compositions/frames/scene-1.html";
|
||||
const framePath = join(dir, frameSrc);
|
||||
writeFileSync(
|
||||
framePath,
|
||||
`<template>
|
||||
<div
|
||||
id="root"
|
||||
data-composition-id="scene-1"
|
||||
data-width="1920"
|
||||
data-height="1080"
|
||||
data-duration="4.2"
|
||||
></div>
|
||||
</template>`,
|
||||
);
|
||||
|
||||
try {
|
||||
padFrameInternalDuration(dir, frameSrc, "scene-1", 4.7);
|
||||
const updated = readFileSync(framePath, "utf8");
|
||||
assert.match(updated, /data-duration="4\.7"/);
|
||||
assert.doesNotMatch(updated, /data-duration="4\.2"/);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("padFrameInternalDuration only touches the tag matching the given frame id", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "transitions-pad-scope-"));
|
||||
const framesDir = join(dir, "compositions", "frames");
|
||||
mkdirSync(framesDir, { recursive: true });
|
||||
const frameSrc = "compositions/frames/scene-2.html";
|
||||
const framePath = join(dir, frameSrc);
|
||||
const original = `<template>
|
||||
<div id="root" data-composition-id="scene-2" data-duration="3.0">
|
||||
<div data-composition-id="unrelated-child" data-duration="1.0"></div>
|
||||
</div>
|
||||
</template>`;
|
||||
writeFileSync(framePath, original);
|
||||
|
||||
try {
|
||||
padFrameInternalDuration(dir, frameSrc, "scene-2", 3.5);
|
||||
const updated = readFileSync(framePath, "utf8");
|
||||
assert.match(updated, /data-composition-id="scene-2" data-duration="3\.5"/);
|
||||
assert.match(updated, /data-composition-id="unrelated-child" data-duration="1\.0"/);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("padFrameInternalDuration is a no-op when the frame file does not exist", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "transitions-pad-missing-"));
|
||||
try {
|
||||
assert.doesNotThrow(() =>
|
||||
padFrameInternalDuration(dir, "compositions/frames/missing.html", "missing", 5),
|
||||
);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
// storyboard.mjs — vendored lenient parser for STORYBOARD.md.
|
||||
//
|
||||
// Faithful plain-JS port of @hyperframes/core/storyboard
|
||||
// (packages/core/src/storyboard/parseStoryboard.ts). Vendored because skills
|
||||
// ship standalone: installed via `npx skills add`, a skill's scripts can't reach
|
||||
// the monorepo's core package, and the core export points at .ts source that
|
||||
// `node` (which runs these scripts) can't load. CANONICAL contract = the core
|
||||
// parser + skills/hyperframes/references/storyboard-format.md; keep this in
|
||||
// lockstep. Behavior: never throws, accepts freeform narrative, recognizes
|
||||
// Frame/Beat/Scene headings at H2/H3, preserves unknown keys verbatim under
|
||||
// `extra` (keys lowercased). Pure node — no deps.
|
||||
|
||||
export const FRAME_STATUSES = ["outline", "built", "animated"];
|
||||
export const DEFAULT_FRAME_STATUS = "outline";
|
||||
|
||||
// Detection-only frame heading (ends at the keyword); ReDoS-hardened — keep as-is.
|
||||
const FRAME_HEADING_RE = /^(#{2,3})[ \t]+(?:frame|beat|scene)\b/i;
|
||||
const FRAME_TITLE_SEP_RE = /^[\s.:—-]+/;
|
||||
const HEADING_LEVEL_RE = /^(#{1,6})\s+/;
|
||||
const META_RE = /^\s*[-*]\s+([A-Za-z_][\w-]*)\s*:\s*(.+?)\s*$/;
|
||||
const LEADING_INT_RE = /^(\d+)/;
|
||||
const DURATION_NUM_RE = /(\d+(?:\.\d+)?)/;
|
||||
const TRANSITION_KEYS = new Set(["transition_in", "transitionin", "transition"]);
|
||||
const SCENE_KEYS = new Set(["scene", "description", "summary", "caption"]);
|
||||
export const VOICEOVER_ALIASES = ["voiceover", "vo", "voice_over", "narration"];
|
||||
const VOICEOVER_KEYS = new Set(VOICEOVER_ALIASES);
|
||||
|
||||
export function parseStoryboard(source) {
|
||||
const warnings = [];
|
||||
const { globals, bodyStartLine, body } = parseFrontmatter(source, warnings);
|
||||
const frames = parseFrames(body, bodyStartLine, warnings);
|
||||
return { globals, frames, warnings };
|
||||
}
|
||||
|
||||
function emptyGlobals() {
|
||||
return { extra: {} };
|
||||
}
|
||||
|
||||
function isFrameStatus(value) {
|
||||
return FRAME_STATUSES.includes(value);
|
||||
}
|
||||
|
||||
// ── Frontmatter ─────────────────────────────────────────────────────────────
|
||||
function findFrontmatterRange(lines, warnings) {
|
||||
let start = 0;
|
||||
while (start < lines.length && (lines[start] ?? "").trim() === "") start++;
|
||||
if ((lines[start] ?? "").trim() !== "---") return null;
|
||||
for (let i = start + 1; i < lines.length; i++) {
|
||||
if ((lines[i] ?? "").trim() === "---") return { start, end: i };
|
||||
}
|
||||
warnings.push({
|
||||
message: "Frontmatter opening '---' has no closing '---'; treating whole file as body.",
|
||||
line: start + 1,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseFrontmatterEntries(lines, start, end, warnings) {
|
||||
const globals = emptyGlobals();
|
||||
for (let i = start + 1; i < end; i++) {
|
||||
const raw = lines[i] ?? "";
|
||||
if (raw.trim() === "") continue;
|
||||
const colon = raw.indexOf(":");
|
||||
if (colon === -1) {
|
||||
warnings.push({
|
||||
message: `Ignored non key:value frontmatter line: "${raw.trim()}"`,
|
||||
line: i + 1,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const key = raw.slice(0, colon).trim().toLowerCase();
|
||||
assignGlobal(globals, key, stripQuotes(raw.slice(colon + 1).trim()));
|
||||
}
|
||||
return globals;
|
||||
}
|
||||
|
||||
function parseFrontmatter(source, warnings) {
|
||||
const lines = source.split(/\r?\n/);
|
||||
const range = findFrontmatterRange(lines, warnings);
|
||||
if (!range) return { globals: emptyGlobals(), bodyStartLine: 1, body: source };
|
||||
const globals = parseFrontmatterEntries(lines, range.start, range.end, warnings);
|
||||
const body = lines.slice(range.end + 1).join("\n");
|
||||
return { globals, bodyStartLine: range.end + 2, body };
|
||||
}
|
||||
|
||||
function assignGlobal(globals, key, value) {
|
||||
switch (key) {
|
||||
case "format":
|
||||
globals.format = value;
|
||||
break;
|
||||
case "message":
|
||||
globals.message = value;
|
||||
break;
|
||||
case "arc":
|
||||
globals.arc = value;
|
||||
break;
|
||||
case "audience":
|
||||
globals.audience = value;
|
||||
break;
|
||||
default:
|
||||
globals.extra[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Frames ──────────────────────────────────────────────────────────────────
|
||||
function openFrameSection(line, headingLine) {
|
||||
const match = FRAME_HEADING_RE.exec(line);
|
||||
if (!match) return null;
|
||||
const headingText = line.slice(match[0].length).replace(FRAME_TITLE_SEP_RE, "").trim();
|
||||
return { headingText, headingLine, level: (match[1] ?? "##").length, lines: [] };
|
||||
}
|
||||
|
||||
function endsFrameSection(line, current) {
|
||||
if (!current) return false;
|
||||
const heading = HEADING_LEVEL_RE.exec(line);
|
||||
return heading !== null && (heading[1] ?? "").length <= current.level;
|
||||
}
|
||||
|
||||
function parseFrames(body, bodyStartLine, warnings) {
|
||||
const lines = body.split(/\r?\n/);
|
||||
const sections = [];
|
||||
let current = null;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i] ?? "";
|
||||
const opened = openFrameSection(line, bodyStartLine + i);
|
||||
if (opened) {
|
||||
sections.push(opened);
|
||||
current = opened;
|
||||
} else if (endsFrameSection(line, current)) {
|
||||
current = null;
|
||||
} else if (current) {
|
||||
current.lines.push(line);
|
||||
}
|
||||
}
|
||||
return sections.map((section, idx) => buildFrame(section, idx + 1, warnings));
|
||||
}
|
||||
|
||||
function buildFrame(section, index, warnings) {
|
||||
const frame = { index, status: DEFAULT_FRAME_STATUS, narrative: "", extra: {} };
|
||||
const { number, title } = parseHeading(section.headingText);
|
||||
if (number !== undefined) frame.number = number;
|
||||
if (title) frame.title = title;
|
||||
|
||||
const narrativeLines = [];
|
||||
for (const line of section.lines) {
|
||||
const meta = META_RE.exec(line);
|
||||
if (meta) {
|
||||
applyMeta(
|
||||
frame,
|
||||
(meta[1] ?? "").toLowerCase(),
|
||||
(meta[2] ?? "").trim(),
|
||||
section.headingLine,
|
||||
warnings,
|
||||
);
|
||||
} else {
|
||||
narrativeLines.push(line);
|
||||
}
|
||||
}
|
||||
frame.narrative = narrativeLines.join("\n").trim();
|
||||
return frame;
|
||||
}
|
||||
|
||||
function parseHeading(text) {
|
||||
if (!text) return {};
|
||||
const intMatch = LEADING_INT_RE.exec(text);
|
||||
if (!intMatch) return { title: text };
|
||||
const number = Number.parseInt(intMatch[1] ?? "", 10);
|
||||
const rest = text
|
||||
.slice((intMatch[0] ?? "").length)
|
||||
.replace(/^[\s.:—-]+/, "")
|
||||
.trim();
|
||||
return { number, title: rest || undefined };
|
||||
}
|
||||
|
||||
// Dispatch a recognized metadata key to its field, else stash under `extra`.
|
||||
// Mirrors core's META_SETTERS map exactly (direct keys + alias sets).
|
||||
function applyMeta(frame, key, value, headingLine, warnings) {
|
||||
switch (key) {
|
||||
case "duration":
|
||||
applyDuration(frame, value, headingLine, warnings);
|
||||
return;
|
||||
case "status":
|
||||
applyStatus(frame, value, headingLine, warnings);
|
||||
return;
|
||||
case "poster":
|
||||
applyPoster(frame, value);
|
||||
return;
|
||||
case "src":
|
||||
frame.src = value;
|
||||
return;
|
||||
}
|
||||
if (TRANSITION_KEYS.has(key)) {
|
||||
frame.transitionIn = value;
|
||||
return;
|
||||
}
|
||||
if (SCENE_KEYS.has(key)) {
|
||||
frame.scene = value;
|
||||
return;
|
||||
}
|
||||
if (VOICEOVER_KEYS.has(key)) {
|
||||
frame.voiceover = stripQuotes(value);
|
||||
return;
|
||||
}
|
||||
frame.extra[key] = value;
|
||||
}
|
||||
|
||||
function applyPoster(frame, value) {
|
||||
const num = DURATION_NUM_RE.exec(value);
|
||||
if (num) frame.poster = Number.parseFloat(num[1] ?? "");
|
||||
}
|
||||
|
||||
function applyDuration(frame, value, headingLine, warnings) {
|
||||
frame.duration = value;
|
||||
const num = DURATION_NUM_RE.exec(value);
|
||||
if (num) {
|
||||
frame.durationSeconds = Number.parseFloat(num[1] ?? "");
|
||||
return;
|
||||
}
|
||||
warnings.push({
|
||||
message: `Frame ${frame.index}: could not parse duration "${value}".`,
|
||||
line: headingLine,
|
||||
frameIndex: frame.index,
|
||||
});
|
||||
}
|
||||
|
||||
function applyStatus(frame, value, headingLine, warnings) {
|
||||
const normalized = value.toLowerCase();
|
||||
if (isFrameStatus(normalized)) {
|
||||
frame.status = normalized;
|
||||
return;
|
||||
}
|
||||
frame.extra.status = value;
|
||||
warnings.push({
|
||||
message: `Frame ${frame.index}: unknown status "${value}"; defaulting to "${DEFAULT_FRAME_STATUS}".`,
|
||||
line: headingLine,
|
||||
frameIndex: frame.index,
|
||||
});
|
||||
}
|
||||
|
||||
function stripQuotes(value) {
|
||||
if (value.length >= 2) {
|
||||
const first = value[0];
|
||||
const last = value[value.length - 1];
|
||||
if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
|
||||
return value.slice(1, -1);
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
// tokens.mjs — shared brand-token parsing + semantic role mapping for frame.md /
|
||||
// FRAME.md. Used by build-frame.mjs (remix a preset onto brand tokens) and
|
||||
// captions.mjs (derive caption colors from frame.md). One mapping → frames and
|
||||
// captions stay consistent. Pure node.
|
||||
|
||||
// Collect `key: value` pairs under the top-level `colors:` block (until dedent).
|
||||
export function parseColors(md) {
|
||||
const out = [];
|
||||
let inBlock = false;
|
||||
for (const line of md.split(/\r?\n/)) {
|
||||
if (/^colors:\s*$/.test(line)) {
|
||||
inBlock = true;
|
||||
continue;
|
||||
}
|
||||
if (!inBlock) continue;
|
||||
if (/^\S/.test(line)) break; // dedent to a top-level key → end of block
|
||||
const m = line.match(
|
||||
/^\s+([\w-]+):\s*(?:"([^"]+)"|'([^']+)'|(#[0-9a-fA-F]{3,8}|rgba?\([^)]*\)|[^#\s][^#\n]*?))\s*(?:#.*)?$/,
|
||||
);
|
||||
if (m) out.push([m[1], (m[2] ?? m[3] ?? m[4]).trim()]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// relative luminance of a #rrggbb (null for non-hex like rgba()).
|
||||
export function lum(v) {
|
||||
const m = /^#?([0-9a-fA-F]{6})$/.exec(String(v).trim());
|
||||
if (!m) return null;
|
||||
const n = parseInt(m[1], 16);
|
||||
return 0.2126 * ((n >> 16) & 255) + 0.7152 * ((n >> 8) & 255) + 0.0722 * (n & 255);
|
||||
}
|
||||
|
||||
// chroma (max−min channel) of a #rrggbb — a cheap "how colorful" proxy; −1 for non-hex.
|
||||
export function chroma(v) {
|
||||
const m = /^#?([0-9a-fA-F]{6})$/.exec(String(v).trim());
|
||||
if (!m) return -1;
|
||||
const n = parseInt(m[1], 16);
|
||||
const r = (n >> 16) & 255,
|
||||
g = (n >> 8) & 255,
|
||||
b = n & 255;
|
||||
return Math.max(r, g, b) - Math.min(r, g, b);
|
||||
}
|
||||
|
||||
// Browser user-agent default colors for links / visited links. These leak into a
|
||||
// capture from any UNSTYLED <a> and are NOT brand colors — but being pure & saturated
|
||||
// they beat a real accent on chroma alone. Never let one become the accent.
|
||||
export const UA_DEFAULT_COLORS = new Set(
|
||||
["#0000EE", "#0000FF", "#0000CC", "#1A0DAB", "#551A8B", "#EE0000"].map((c) => c.toUpperCase()),
|
||||
);
|
||||
|
||||
export const ICON_FONT_PATTERN =
|
||||
/(?:^|[\s_-])icons?(?:[\s_-]|$)|icomoon|font\s*-?awesome|glyphicons?|material\s*icons|feather\s*icons|(?:icon|glyph).*font|font.*(?:icon|glyph)|^vidaxlfont$/i;
|
||||
|
||||
export function isIconFont(name) {
|
||||
return ICON_FONT_PATTERN.test(String(name));
|
||||
}
|
||||
|
||||
// Semantic STATUS roles (green "positive", red "negative"/"error", amber "warning" …). Their HUE
|
||||
// carries the meaning, so they are never a brand ACCENT — a status red is frequently the most
|
||||
// chromatic color in a palette (e.g. #dc2626 chroma 182 beats a deep-blue accent #1E40AF chroma
|
||||
// 145) and would otherwise win a pure chroma ranking, painting captions/highlights the error red.
|
||||
// build-frame.mjs uses this same key set to protect status colors during the preset→brand remix.
|
||||
export const STATUS_ROLE_KEY =
|
||||
/(?:^|[-_])(?:positive|negative|success|error|warning|danger|good|bad|up|down|info|neutral|alert|caution|critical)(?:[-_]|$)/i;
|
||||
|
||||
// Pick the brand ACCENT — never by raw chroma alone, never a UA-default link color.
|
||||
// Priority:
|
||||
// 1) with capture colorStats → the colorful color that RECURS across the UI. The brand
|
||||
// accent shows up in MANY roles (link text + icon + button + badge), whereas a one-off
|
||||
// CTA fill appears in just one. So rank chromatic (chroma>40) candidates by role
|
||||
// diversity first, then total prevalence, then interactive use, then chroma. This keeps
|
||||
// a pervasive brand color (e.g. an indigo used everywhere) ahead of a single bright
|
||||
// button fill (e.g. a lime used once) — the old "top interactiveBg" rule picked the
|
||||
// latter. Requiring interactiveBg>0 is dropped so a text/icon-only accent can still win.
|
||||
// 2) no stats → most chromatic color AFTER removing UA defaults + `exclude`.
|
||||
// A stray default link color (e.g. #0000EE) can win under neither path.
|
||||
export function pickAccent(stats, colors, exclude = []) {
|
||||
const ban = new Set([...exclude, ...UA_DEFAULT_COLORS].map((c) => String(c).toUpperCase()));
|
||||
const ok = (h) => /^#[0-9a-fA-F]{6}$/.test(String(h)) && !ban.has(String(h).toUpperCase());
|
||||
// Prominence rank from the (frequency-ordered) `colors` palette: index 0 = most used.
|
||||
// A saturated color sitting at the TAIL is almost always a one-off (a single CTA fill),
|
||||
// not the brand accent — capture colorStats counts are too sparse to tell these apart
|
||||
// (e.g. Linear's indigo and a lime CTA both register count≈1), but palette ORDER does.
|
||||
const rank = new Map((colors ?? []).map((h, i) => [String(h).toUpperCase(), i]));
|
||||
const prom = (h) => (rank.has(String(h).toUpperCase()) ? rank.get(String(h).toUpperCase()) : 1e9);
|
||||
if (Array.isArray(stats) && stats.length) {
|
||||
const roles = (s) =>
|
||||
((s.interactiveBg || 0) > 0 ? 1 : 0) +
|
||||
((s.textCount || 0) > 0 ? 1 : 0) +
|
||||
((s.bgCount || 0) > 0 ? 1 : 0);
|
||||
const a = stats
|
||||
.filter((s) => ok(s?.hex) && chroma(s.hex) > 40)
|
||||
.sort(
|
||||
(x, y) =>
|
||||
roles(y) - roles(x) || // used in MORE roles (link+icon+button) = the brand accent
|
||||
prom(x.hex) - prom(y.hex) || // earlier in the palette = more prominent
|
||||
(y.count || 0) - (x.count || 0) ||
|
||||
(y.interactiveBg || 0) - (x.interactiveBg || 0) ||
|
||||
chroma(y.hex) - chroma(x.hex),
|
||||
);
|
||||
if (a.length) return a[0].hex;
|
||||
}
|
||||
const c = (colors ?? [])
|
||||
.map(String)
|
||||
.filter(ok)
|
||||
.sort((x, y) => chroma(y) - chroma(x));
|
||||
return c[0];
|
||||
}
|
||||
|
||||
// Derive brand roles from rich capture colorStats (areaBg / interactiveBg / textCount /
|
||||
// maxArea) — by semantic FUNCTION, not luminance/chroma proxies. Returns null when stats
|
||||
// are unusable, so the caller can fall back. canvas = the color painting the most real
|
||||
// background area (the page ground, dark or light); ink = the dominant text color that
|
||||
// actually contrasts with the canvas; accent via pickAccent.
|
||||
export function brandRolesFromStats(stats, colorsInOrder) {
|
||||
if (!Array.isArray(stats) || !stats.length) return null;
|
||||
const v = stats.filter((s) => /^#[0-9a-fA-F]{6}$/.test(s?.hex || ""));
|
||||
if (!v.length) return null;
|
||||
const canvas = [...v].sort(
|
||||
(a, b) =>
|
||||
(b.areaBg || 0) - (a.areaBg || 0) ||
|
||||
(b.maxArea || 0) - (a.maxArea || 0) ||
|
||||
(b.bgCount || 0) - (a.bgCount || 0),
|
||||
)[0]?.hex;
|
||||
// pass the frequency-ordered palette (tokens.colors) so pickAccent can use palette
|
||||
// PROMINENCE — colorStats counts alone are too sparse to rank rare accents.
|
||||
const accent = pickAccent(v, colorsInOrder ?? v.map((s) => s.hex), [canvas]);
|
||||
if (!canvas || !accent) return null;
|
||||
const cl = lum(canvas) ?? 0;
|
||||
const ink =
|
||||
[...v]
|
||||
.filter((s) => s.hex !== canvas && s.hex !== accent)
|
||||
.sort((a, b) => (b.textCount || 0) - (a.textCount || 0))
|
||||
.find((s) => Math.abs((lum(s.hex) ?? 0) - cl) > 64)?.hex ??
|
||||
(cl > 128 ? "#000000" : "#FFFFFF");
|
||||
const accent2 =
|
||||
pickAccent(v, colorsInOrder ?? v.map((s) => s.hex), [canvas, ink, accent]) ?? accent;
|
||||
return { ink, canvas, accent, accent2 };
|
||||
}
|
||||
|
||||
// Map a list of [key, value] colors to semantic roles. ink = a dark/ink-named
|
||||
// color (else darkest); canvas = a paper/cream/white-named color (else lightest);
|
||||
// accents = whatever's left, ranked by chroma (the loudest color is almost always
|
||||
// the brand accent) — UA-default link colors AND semantic status colors (positive/
|
||||
// negative/error…) excluded so neither a stray <a> color nor a status red ever wins.
|
||||
// For an unkeyed brand list, pass synthetic keys — name matching simply no-ops and it
|
||||
// falls back to luminance/chroma, which is what we want. NOTE: when capture colorStats
|
||||
// exist, prefer brandRolesFromStats() — it picks by function, not these proxies.
|
||||
export function semanticColors(colors) {
|
||||
if (!colors.length) return {};
|
||||
const named = (re) => colors.find(([k]) => re.test(k));
|
||||
const hexes = colors.filter(([, v]) => lum(v) != null);
|
||||
const byLum = [...hexes].sort((a, b) => (lum(a[1]) ?? 1e9) - (lum(b[1]) ?? 1e9));
|
||||
const pick = (m, fallback) => (m ? m[1] : fallback ? fallback[1] : undefined);
|
||||
// "ink" must be a whole word-segment so "soft-pink"/"pink" don't match it.
|
||||
const ink = pick(
|
||||
named(/(?:^|[-_])ink(?:[-_]|$)|black|charcoal|^text(?:-dark)?$|outline|noir/i),
|
||||
byLum[0] ?? colors[0],
|
||||
);
|
||||
const canvas = pick(
|
||||
named(/cream|paper|canvas|white|bg|ground|surface|base|sand|parchment|off-?white|bone/i),
|
||||
byLum[byLum.length - 1] ?? colors[colors.length - 1],
|
||||
);
|
||||
const accents = colors
|
||||
.filter(
|
||||
([k, v]) =>
|
||||
v !== ink &&
|
||||
v !== canvas &&
|
||||
!UA_DEFAULT_COLORS.has(String(v).toUpperCase()) &&
|
||||
!STATUS_ROLE_KEY.test(k), // a status red/green carries meaning by hue — never an accent
|
||||
)
|
||||
.sort((a, b) => chroma(b[1]) - chroma(a[1]))
|
||||
.map(([, v]) => v);
|
||||
return { ink, canvas, accent: accents[0] ?? ink, accent2: accents[1] ?? accents[0] ?? ink };
|
||||
}
|
||||
|
||||
// Collect role→fontFamily under the top-level `typography:` block; pick a display
|
||||
// + body family from the usual role names. Returns quoted families (or null).
|
||||
export function parseFonts(md) {
|
||||
const roles = {};
|
||||
let inBlock = false;
|
||||
for (const line of md.split(/\r?\n/)) {
|
||||
if (/^typography:\s*$/.test(line)) {
|
||||
inBlock = true;
|
||||
continue;
|
||||
}
|
||||
if (!inBlock) continue;
|
||||
if (/^\S/.test(line)) break;
|
||||
const m = line.match(/^\s+([\w-]+):\s*\{[^}]*fontFamily:\s*"([^"]+)"/);
|
||||
if (m) roles[m[1]] = m[2];
|
||||
}
|
||||
const q = (s) => (s ? `"${s}"` : null);
|
||||
const body = roles.body ?? roles.subtitle ?? Object.values(roles)[0];
|
||||
const display =
|
||||
roles.display ??
|
||||
roles.headline ??
|
||||
roles["card-headline"] ??
|
||||
roles["section-headline"] ??
|
||||
roles["quote-display"] ??
|
||||
roles.h1 ??
|
||||
roles.h2 ??
|
||||
roles.title ??
|
||||
roles.hero ??
|
||||
body;
|
||||
// the monospace / chrome family (code, tags, ticks, page numbers) — so the remix can
|
||||
// route a captured brand mono (Berkeley Mono, JetBrains Mono…) onto this role instead
|
||||
// of the reading body. null when the preset has no distinct mono role.
|
||||
const mono =
|
||||
roles.mono ??
|
||||
roles["mono-tag"] ??
|
||||
roles["mono-chrome"] ??
|
||||
roles["mono-tick"] ??
|
||||
roles.code ??
|
||||
roles.data ??
|
||||
roles.pagenum ??
|
||||
null;
|
||||
return { display: q(display), body: q(body), mono: q(mono) };
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { brandRolesFromStats, ICON_FONT_PATTERN, isIconFont } from "./tokens.mjs";
|
||||
import { brandRolesFromStats as facelessBrandRolesFromStats } from "../../../faceless-explainer/scripts/lib/tokens.mjs";
|
||||
import { brandRolesFromStats as prBrandRolesFromStats } from "../../../pr-to-video/scripts/lib/tokens.mjs";
|
||||
|
||||
const scriptsDir = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
|
||||
|
||||
test("recognizes brand-specific icon font names", () => {
|
||||
assert.equal(isIconFont("vidaXLfont"), true);
|
||||
assert.equal(isIconFont("BrandGlyphFont"), true);
|
||||
assert.equal(isIconFont("Poppins"), false);
|
||||
assert.equal(isIconFont("HelveticaFont"), false);
|
||||
assert.equal(isIconFont("Airbnb Cereal Font"), false);
|
||||
assert.equal(isIconFont("SF Pro Text Font"), false);
|
||||
assert.equal(isIconFont("Uber Move Font"), false);
|
||||
assert.equal(isIconFont("Circular Std font"), false);
|
||||
assert.equal(isIconFont("brand-font"), false);
|
||||
});
|
||||
|
||||
test("keeps sibling skill icon-font classifiers aligned", () => {
|
||||
for (const skill of ["faceless-explainer", "pr-to-video"]) {
|
||||
const source = readFileSync(join(scriptsDir, skill, "scripts", "build-frame.mjs"), "utf8");
|
||||
assert.match(
|
||||
source,
|
||||
new RegExp(String.raw`ICON_FONT_PATTERN\s*=\s*${escapeRegExp(ICON_FONT_PATTERN)}`),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
function escapeRegExp(value) {
|
||||
return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
test("preserves a prominent second accent used outside interactive backgrounds", () => {
|
||||
const colors = ["#FFFFFF", "#2D1238", "#F3E62B", "#111111"];
|
||||
const stats = [
|
||||
{ hex: "#FFFFFF", areaBg: 1000, maxArea: 1000 },
|
||||
{ hex: "#2D1238", textCount: 4, interactiveBg: 3 },
|
||||
{ hex: "#F3E62B", textCount: 3, interactiveBg: 0 },
|
||||
{ hex: "#111111", textCount: 20 },
|
||||
];
|
||||
|
||||
assert.deepEqual(brandRolesFromStats(stats, colors), {
|
||||
canvas: "#FFFFFF",
|
||||
ink: "#111111",
|
||||
accent: "#F3E62B",
|
||||
accent2: "#2D1238",
|
||||
});
|
||||
|
||||
for (const sibling of [facelessBrandRolesFromStats, prBrandRolesFromStats]) {
|
||||
assert.deepEqual(sibling(stats, colors), brandRolesFromStats(stats, colors));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
// transition-registry.mjs — loader for this skill's vendored transition registry
|
||||
// (./transitions.json). The registry is the curated Tier-B subset (transform /
|
||||
// opacity / filter on the two frame clip wrappers `#el-<id>`, no overlay DOM) +
|
||||
// each type's GSAP template. Vendored into the skill so it ships standalone; the
|
||||
// recipes originate from the shared catalog skills/hyperframes-animation/
|
||||
// transitions/ (css-*.md) — keep them in step if those shared recipes change.
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
export const DEFAULT_REGISTRY_PATH = resolve(here, "./transitions.json");
|
||||
|
||||
let _cache = null;
|
||||
|
||||
export function loadTransitionRegistry(registryPath = DEFAULT_REGISTRY_PATH) {
|
||||
if (_cache && _cache.path === registryPath) return _cache.data;
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(readFileSync(registryPath, "utf8"));
|
||||
} catch (e) {
|
||||
throw new Error(`transition registry not loadable at ${registryPath}: ${e.message}`);
|
||||
}
|
||||
if (!Array.isArray(data.transitions) || data.transitions.length === 0) {
|
||||
throw new Error(`transition registry ${registryPath} has no transitions[]`);
|
||||
}
|
||||
_cache = { path: registryPath, data };
|
||||
return data;
|
||||
}
|
||||
|
||||
// Convenience: a Map name -> transition record.
|
||||
export function transitionsByName(registryPath = DEFAULT_REGISTRY_PATH) {
|
||||
const data = loadTransitionRegistry(registryPath);
|
||||
const map = new Map();
|
||||
for (const t of data.transitions) map.set(t.name, t);
|
||||
return map;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
{
|
||||
"_comment": "Vendored transition registry for the product-launch workflow — the curated Tier-B subset (transform/opacity/filter on the two frame clip wrappers #el-<id>, no overlay DOM, no per-frame cooperation). Each type carries its GSAP template; the transitions.mjs injector stamps it onto window.__timelines[\"main\"]. Recipes originate from the shared catalog skills/hyperframes-animation/transitions/ (css-*.md) — keep in step if those change. Token placeholders the injector substitutes: __OLD__ (#el-<from>), __NEW__ (#el-<to>), __T__ (overlap-start s), __DUR__ (this boundary's duration), __DX__/__DXIN__ (horizontal travel + incoming offset), __DY__/__DYIN__ (vertical).",
|
||||
"transitions": [
|
||||
{
|
||||
"name": "crossfade",
|
||||
"energy": "any",
|
||||
"default_duration_s": 0.5,
|
||||
"directions": [],
|
||||
"source": "css-dissolve.md",
|
||||
"gsap_template": [
|
||||
"tl.to(__OLD__, { opacity: 0, duration: __DUR__, ease: \"power2.inOut\" }, __T__);",
|
||||
"tl.fromTo(__NEW__, { opacity: 0 }, { opacity: 1, duration: __DUR__, ease: \"power2.inOut\" }, __T__);"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "blur-crossfade",
|
||||
"energy": "calm",
|
||||
"default_duration_s": 0.6,
|
||||
"directions": [],
|
||||
"source": "css-dissolve.md",
|
||||
"note": "Default when the two frames' #root backgrounds differ a lot — the blur masks the background-color clash a plain crossfade would expose.",
|
||||
"gsap_template": [
|
||||
"tl.to(__OLD__, { filter: \"blur(10px)\", scale: 1.03, opacity: 0, duration: __DUR__, ease: \"power2.inOut\" }, __T__);",
|
||||
"tl.fromTo(__NEW__, { filter: \"blur(10px)\", scale: 0.97, opacity: 0 }, { filter: \"blur(0px)\", scale: 1, opacity: 1, duration: __DUR__, ease: \"power2.inOut\" }, __T__);"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "push-slide",
|
||||
"energy": "medium",
|
||||
"default_duration_s": 0.5,
|
||||
"directions": ["LEFT", "RIGHT", "UP", "DOWN"],
|
||||
"default_direction": "LEFT",
|
||||
"source": "css-push.md",
|
||||
"note": "Directional. The injector picks __DX__/__DY__ from the direction and emits the horizontal OR vertical pair (not both).",
|
||||
"gsap_template_horizontal": [
|
||||
"tl.to(__OLD__, { x: __DX__, duration: __DUR__, ease: \"power3.inOut\" }, __T__);",
|
||||
"tl.fromTo(__NEW__, { x: __DXIN__, opacity: 1 }, { x: 0, opacity: 1, duration: __DUR__, ease: \"power3.inOut\" }, __T__);"
|
||||
],
|
||||
"gsap_template_vertical": [
|
||||
"tl.to(__OLD__, { y: __DY__, duration: __DUR__, ease: \"power3.inOut\" }, __T__);",
|
||||
"tl.fromTo(__NEW__, { y: __DYIN__, opacity: 1 }, { y: 0, opacity: 1, duration: __DUR__, ease: \"power3.inOut\" }, __T__);"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "zoom-through",
|
||||
"energy": "high",
|
||||
"default_duration_s": 0.4,
|
||||
"directions": [],
|
||||
"source": "css-scale.md",
|
||||
"gsap_template": [
|
||||
"tl.to(__OLD__, { scale: 2.5, opacity: 0, filter: \"blur(8px)\", duration: __DUR__, ease: \"power3.in\" }, __T__);",
|
||||
"tl.fromTo(__NEW__, { scale: 0.5, opacity: 0, filter: \"blur(8px)\" }, { scale: 1, opacity: 1, filter: \"blur(0px)\", duration: __DUR__, ease: \"power3.out\" }, __T__);"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "squeeze",
|
||||
"energy": "medium",
|
||||
"default_duration_s": 0.4,
|
||||
"directions": [],
|
||||
"source": "css-push.md",
|
||||
"note": "Old compresses to a vertical line on the left edge; new expands from the right edge. Incoming starts off (scaleX 0) so its higher-track stacking is harmless.",
|
||||
"gsap_template": [
|
||||
"tl.to(__OLD__, { scaleX: 0, transformOrigin: \"left center\", duration: __DUR__, ease: \"power3.inOut\" }, __T__);",
|
||||
"tl.fromTo(__NEW__, { scaleX: 0, transformOrigin: \"right center\", opacity: 1 }, { scaleX: 1, transformOrigin: \"right center\", opacity: 1, duration: __DUR__, ease: \"power3.inOut\" }, __T__);"
|
||||
]
|
||||
}
|
||||
],
|
||||
"default_high_energy": "zoom-through",
|
||||
"default_calm": "blur-crossfade",
|
||||
"max_duration_s": 2.0
|
||||
}
|
||||
Reference in new issue
Block a user