mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-16 14:27:26 +00:00
feat(cli): add website capture with AI-powered DESIGN.md generation
Adds `hyperframes capture <url>` command that extracts a complete design system from any website, producing AI-agent-ready output: - Full-page screenshot (lazy-load aware, nav at top) - AI-generated DESIGN.md via Claude API (colors, typography, elevation, components, do's/don'ts) with programmatic asset catalog (136+ assets with HTML context annotations like img[src], css url(), link[rel=preload]) - CSS-purged compositions (87% size reduction via PurgeCSS) - HTML-prettified compositions (one-tag-per-line for AI readability) - CLAUDE.md + .cursorrules auto-generated for AI agent instructions - Asset deduplication (srcset variants) and tracking pixel filtering
This commit is contained in:
@@ -0,0 +1,252 @@
|
||||
# Research: Aura.build, DESIGN.md Systems, and HyperFrames Integration
|
||||
|
||||
> Compiled 2026-04-07. Source: 19 Aura.build pages, web-shader-extractor repo, HyperFrames codebase analysis.
|
||||
|
||||
---
|
||||
|
||||
## 1. Aura.build — What It Is and How It Works
|
||||
|
||||
**Category**: AI website/landing page builder (closed-source SaaS)
|
||||
**Founder**: Meng To (Design+Code creator)
|
||||
**Users**: 65,000+ | **Trustpilot**: 4.0/5
|
||||
**Output**: HTML + Tailwind CSS + vanilla JS, Figma files, React components
|
||||
**Models**: Gemini 3.1 Pro (best for animations), Claude 4 (precise instructions), GPT-5.1 (structured UI)
|
||||
|
||||
### Core Philosophy
|
||||
"A prompt alone is not enough. You also need examples, templates, and assets." — Meng To
|
||||
|
||||
### The Prompt Builder (Flagship Feature)
|
||||
Visual no-code prompt construction with 6 categories:
|
||||
1. **Layout Types** — Hero, Features, Onboarding, Docs, Pricing, Dashboard, etc.
|
||||
2. **Layout Patterns** — Card, List, Bento, Table, Sidebar, Carousel, etc.
|
||||
3. **Framing** — Full Screen, Card, Browser, Mac App, Clay Web, iPhone, iPad
|
||||
4. **Visual Styles** — Flat, Outline, Minimalist, Glass, iOS, Material
|
||||
5. **Typography** — Family (Sans/Serif/Mono/Condensed/Handwritten), heading/body fonts, sizes, weights, spacing
|
||||
6. **Animation** — Type (Fade/Slide/Scale/Rotate/Blur/3D/Pulse/Bounce/Morph/Skew/Color/Clip), Scene (all at once/sequence/word-by-word/letter-by-letter), Duration, Timing (Linear/Ease/Spring/Bounce), Iterations, Direction
|
||||
|
||||
Plus: Theme (Light/Dark), Accent Color (17 options), Background Color (17 options), Border Color, Shadow (None through XXL + Beautiful/Bevel/3D/Inner)
|
||||
|
||||
**Generated prompts** include pre-filled suggestions like:
|
||||
- "Create a landing page for {your-app}, a {app-type} app that {feature} in the style of @hero"
|
||||
- "Animate fade in, slide in, blur in, element by element"
|
||||
- "Create 'Masked Staggered Word Reveal' animation on scroll using GSAP ScrollTrigger"
|
||||
- "Add a subtle flashlight effect on hover/mouse position to background and border of cards"
|
||||
|
||||
### @ Context System
|
||||
The `@` symbol feeds up to 100,000 characters (~2,000 lines of code) as context. Users can reference templates, components, code snippets, and previous iterations. This is what makes AI output consistent — "constrained AI produces more consistent output than unconstrained AI."
|
||||
|
||||
### Image-to-HTML
|
||||
Upload any screenshot/mockup/wireframe → AI analyzes structure → generates responsive HTML + Tailwind → edit and refine → export. Works with Midjourney outputs, Figma mockups, and arbitrary screenshots.
|
||||
|
||||
### Key Insight: Screenshot + DESIGN.md = Best Results
|
||||
When Aura has both a full-page screenshot AND design system data, output quality is dramatically better than either alone. The user demonstrated this with Notion — the version with screenshot was "SO FAST, and so exactly damn right."
|
||||
|
||||
### Aura Skills System
|
||||
Hosts AI Agent Skills directory: Skill Creator, Web Interface Guidelines, GSAP Web Animation Skill, Anime.js v4 Skill. Follows SKILL.md format compatible with Claude Code, Cursor, Gemini CLI.
|
||||
|
||||
### Pricing
|
||||
| Plan | Cost | Prompts/Month |
|
||||
|------|------|---------------|
|
||||
| Free | $0 | 10 |
|
||||
| Pro | $20/mo | 120 |
|
||||
| Max | $40/mo | 240 |
|
||||
| Ultra | $100/mo | 560 |
|
||||
|
||||
---
|
||||
|
||||
## 2. DESIGN.md — The Format
|
||||
|
||||
### Origin
|
||||
Popularized by Google Stitch. VoltAgent/awesome-design-md curates 58+ brand examples (Apple, Stripe, Figma, Linear, Notion, SpaceX).
|
||||
|
||||
### Standard Structure (9 sections)
|
||||
1. **Overview** — Visual identity, tone, design philosophy
|
||||
2. **Colors** — Semantic roles (surface, text, accent), hex values with usage context
|
||||
3. **Typography** — Font families, hierarchy tables, weight/size/tracking rules
|
||||
4. **Elevation & Depth** — Shadow systems, glassmorphism, border patterns
|
||||
5. **Components** — Buttons, cards, navigation, inputs across states
|
||||
6. **Layout** — Grid, spacing scale, whitespace philosophy
|
||||
7. **Do's and Don'ts** — Design guardrails and anti-patterns
|
||||
8. **Assets** — Images, fonts, icons with URLs and descriptions
|
||||
9. **Responsive Behavior** — Breakpoints, touch targets, collapse strategies
|
||||
|
||||
### Why It Works
|
||||
"Markdown is the format LLMs read best." The DESIGN.md acts as constraints, not suggestions. AI treats design rules as hard requirements, producing consistent output across multiple generations.
|
||||
|
||||
### Examples from User's Session
|
||||
- **Notion DESIGN.md** (16.4 KB) — "Digital Paper" aesthetic, NotionInter/LyonText/iAWriterMonoS fonts, border-reliance elevation, bento card system, logo marquee, interactive calculator component
|
||||
- **Soulscape DESIGN.md** (7.7 KB) — "Void" #020204 background, Cormorant Garamond serif + Geist Mono, glassmorphism, cinematic accordion, grain overlays, HUD explorer navigation
|
||||
|
||||
---
|
||||
|
||||
## 3. Web Shader Extractor (lixiaolin94/skills)
|
||||
|
||||
**Repository**: github.com/lixiaolin94/skills (MIT, 161 stars)
|
||||
**What it does**: 7-phase pipeline that extracts WebGL/Canvas/Shader effects from websites, deobfuscates minified JS, and ports to standalone native JavaScript projects.
|
||||
|
||||
### Phases
|
||||
0. Auto-installs Node.js + Playwright + Chromium
|
||||
1. Parallel source fetching (rendered DOM, canvas metadata, network requests, screenshots)
|
||||
2. Tech stack identification (Three.js, Babylon.js, PixiJS, Raw WebGL, 2D Canvas)
|
||||
3. Configuration extraction (REST APIs, Nuxt payloads, `__NEXT_DATA__`, bundle defaults)
|
||||
4. Shader code extraction from 1MB+ minified bundles
|
||||
5. Porting to standalone project (raw WebGL2 or original framework via CDN)
|
||||
6. Simplification proposal
|
||||
7. Optional extraction report
|
||||
|
||||
### HyperFrames Integration Potential
|
||||
- **Standalone JS output (zero deps)** embeds directly into HTML compositions
|
||||
- Could add WebGL detection to `hyperframes capture`
|
||||
- Extracted shaders become reusable backgrounds/transitions
|
||||
- Challenge: adapting `requestAnimationFrame` loops to HyperFrames' deterministic frame adapter system
|
||||
|
||||
---
|
||||
|
||||
## 4. HyperFrames Current State — What We Have
|
||||
|
||||
### visual-style.md (minimal, auto-generated during capture)
|
||||
```yaml
|
||||
---
|
||||
name: "Page Title"
|
||||
source_url: "URL"
|
||||
colors:
|
||||
- hex: "#..."
|
||||
role: "color-0"
|
||||
typography:
|
||||
fonts: ["Font1"]
|
||||
mood:
|
||||
keywords: ["extracted", "website-captured"]
|
||||
---
|
||||
```
|
||||
|
||||
### house-style.md (rich, in skills directory)
|
||||
- 9 palette categories (Bold/Energetic, Warm/Editorial, Dark/Premium, Clean/Corporate, etc.)
|
||||
- Easing vocabulary (power1-4, back.out, elastic.out, circ.out, expo.out)
|
||||
- Timing rules (0.3-0.6s for most moves, exits 2x faster)
|
||||
- Entrance patterns (position, scale, rotation, clip-path, blur, 3D transforms)
|
||||
- 11 "anti-defaults" (no Inter/Roboto, no mid-gray, no blue accent, no uniform spacing)
|
||||
- Typography rules (weight contrast, tracking, case)
|
||||
- Scene pacing (Build 0-30%, Breathe 30-70%, Resolve 70-100%)
|
||||
|
||||
### data-in-motion.md
|
||||
- Visual continuity rules for sequential stats
|
||||
- "Numbers need visual weight" (pair every metric with visual element)
|
||||
- Avoid web patterns (no pie charts, no multi-axis, no 6-panel dashboards)
|
||||
|
||||
### patterns.md
|
||||
- Picture-in-Picture, Title Card, Slide Show templates with code
|
||||
|
||||
### Token Extraction (tokenExtractor.ts)
|
||||
- Colors (12), fonts, headings (h1-h4 with size/weight/color), CTAs, sections (type/heading/bg), CSS variables, logos, images
|
||||
|
||||
### Animation Cataloging (animationCataloger.ts)
|
||||
- Web Animations API keyframes, CSS transition/animation declarations, IntersectionObserver scroll targets, CDP animation events, Canvas elements
|
||||
|
||||
### Gap: What's Missing
|
||||
1. No color role inference (just raw hex values)
|
||||
2. No typography hierarchy table (just font family names)
|
||||
3. No component documentation (nav, cards, buttons not described)
|
||||
4. No motion language (animations cataloged but not summarized in human terms)
|
||||
5. No do's/don'ts (house-style has them but they're not in capture output)
|
||||
6. No full-page screenshot (only per-section viewport shots)
|
||||
7. No prompt templates (brief suggests one generic prompt)
|
||||
8. No HyperFrames-specific recommendations (transitions, composition templates)
|
||||
9. No shader/WebGL detection
|
||||
|
||||
---
|
||||
|
||||
## 5. Mapping Aura Concepts to HyperFrames
|
||||
|
||||
| Aura Concept | HyperFrames Equivalent | Status |
|
||||
|---|---|---|
|
||||
| DESIGN.md | visual-style.md | Exists but minimal — needs enrichment |
|
||||
| Prompt Builder UI | CLI + prompt-catalog.md | Doesn't exist — create prompt catalog |
|
||||
| @ Context (100K chars) | Purged compositions (32-276KB, readable) | Built today! CSS purge + prettify |
|
||||
| Template library | Captured section compositions | Built today! Website capture pipeline |
|
||||
| Screenshot input | Full-page screenshot | Missing — add to capture |
|
||||
| Image-to-HTML | website-to-hyperframes capture | Exists but different goal (video, not web) |
|
||||
| Animation snippets | house-style.md + GSAP skills | Rich but not in capture output |
|
||||
| Multi-model support | Claude Code (any model) | Inherited from agent |
|
||||
| Code Mode editing | Edit purged compositions | Built today! AI-readable files |
|
||||
| Component remix | Remix demo (scenes 1-4) | Demonstrated today |
|
||||
|
||||
---
|
||||
|
||||
## 6. Future Directions
|
||||
|
||||
### Chrome Extension
|
||||
Aura has a web app. HyperFrames could have a Chrome extension that:
|
||||
- One-click captures the current page
|
||||
- Generates DESIGN.md + full-page screenshot
|
||||
- Opens HyperFrames Studio with captured components
|
||||
- Similar to Aura's "Adapt from HTML" but for video
|
||||
|
||||
### Visual Prompt Builder (Web UI)
|
||||
A Prompt Builder for video compositions could live in HyperFrames Studio:
|
||||
- Pick scene types (Hero, Features, Stats, Testimonial, CTA)
|
||||
- Select transitions between scenes
|
||||
- Choose animation style (Energetic, Calm, Corporate, Cinematic)
|
||||
- Set duration and pacing
|
||||
- Generate a composition from the selections
|
||||
|
||||
### Shader Integration
|
||||
Combine web-shader-extractor with capture:
|
||||
- Detect WebGL canvases during capture
|
||||
- Extract shader code into standalone files
|
||||
- Embed as animated backgrounds in compositions
|
||||
- Challenge: deterministic rendering of shader time uniforms
|
||||
|
||||
### DESIGN.md Ecosystem Play
|
||||
"Take your DESIGN.md and now all your videos are on-brand with HyperFrames":
|
||||
- Accept any DESIGN.md (from Aura, Google Stitch, or hand-written)
|
||||
- Extend with HyperFrames-specific sections (transitions, GSAP presets, composition templates)
|
||||
- Use as context for AI-generated compositions
|
||||
- Portable: same file works in Aura (web), Cursor (code), HyperFrames (video)
|
||||
|
||||
---
|
||||
|
||||
## 7. Aura Prompt Builder — Complete Category Reference
|
||||
|
||||
### Layout Types (Web)
|
||||
Hero, Features, Onboarding, Docs, Updates, Portfolio, Pricing, Gallery, Dashboard, Login, Email, Testimonials, Payment, Footer, FAQ, Explore, Settings, About, Blog, Video, Landing Page
|
||||
|
||||
### Layout Types (Mobile)
|
||||
Hero, Features, Onboarding, Dashboard, Login, Settings, Profile, Gallery, Explore, FAQ
|
||||
|
||||
### Layout Configuration
|
||||
Card, List, 2-2 Square, Table, Sidebar Left, Sidebar Right, 1-1 Split, 1-1 Vertical, 1/3 2/3 Bento, 2/3 1/3 Bento, 1x4 Bento, Feature Bento, Featured Right, Featured Top, 1/4 2/4 1/4 Bento, 2/4 1/4 1/4 Bento, 2-1 Split, 1-2 Split, 1-1-1 Equal, Header Focus, 3-3 Grid, Carousel, Modal, Alert
|
||||
|
||||
### Framing
|
||||
Full Screen, Card, Browser, Mac App, Clay Web (desktop)
|
||||
iPhone, Android, iPad, Clay Mobile (mobile)
|
||||
|
||||
### Visual Styles
|
||||
Flat, Outline, Minimalist, Glass, iOS, Material
|
||||
|
||||
### Animation Types
|
||||
Fade, Slide, Scale, Rotate, Blur, 3D, Pulse, Shake, Bounce, Morph, Skew, Color, Hue, Perspective, Clip
|
||||
|
||||
### Animation Scene
|
||||
All at once, Sequence, Word by word, Letter by letter
|
||||
|
||||
### Animation Timing
|
||||
Linear, Ease, Ease In, Ease Out, Ease In Out, Spring, Bounce
|
||||
|
||||
### Shadow Options
|
||||
None, Small, Medium, Large, Extra Large, XXL, Beautiful sm/md/lg, Light Blue sm/md/lg, Bevel, 3D, Inner Shadow
|
||||
|
||||
### Typeface Families
|
||||
Sans, Serif, Monospace, Condensed, Expanded, Rounded, Handwritten
|
||||
|
||||
### Ready-Made Prompts (partial list)
|
||||
- "Create a landing page for {your-app}, a {app-type} app that {feature} in the style of @hero"
|
||||
- "Hero section @hero. Add sections @feature, @testimonial, @pricing and add @footer"
|
||||
- "Use @border-gradient for buttons and cards"
|
||||
- "Add a beam animation to the vertical lines"
|
||||
- "Add noodles that connect elements and beam animation"
|
||||
- "Add a subtle flashlight effect on hover/mouse position"
|
||||
- "Create 'Masked Staggered Word Reveal' animation on scroll using GSAP ScrollTrigger"
|
||||
- "Add parallax scrolling to the background"
|
||||
- "Apply alpha masking using mask-image: linear-gradient"
|
||||
- "Animate fade in, slide in, blur in, element by element"
|
||||
- "Animate when in view observed, fade in, slide in, blur in, element by element"
|
||||
@@ -0,0 +1,127 @@
|
||||
# Aura Prompt Comparison: With Screenshot vs Without
|
||||
|
||||
## Soulscape (NO screenshot — timed out)
|
||||
|
||||
```
|
||||
Recreate the imported webpage as faithfully as possible using the captured
|
||||
page structure from the imported site as the structural reference and the
|
||||
attached DESIGN.md as the design-system and asset reference.
|
||||
|
||||
Screenshot capture timed out during import, so no screenshot reference is
|
||||
attached. Use the captured page structure from the imported site to preserve
|
||||
exact structure, section order, and supporting source details. Use the
|
||||
DESIGN.md to preserve exact design-system choices and asset references.
|
||||
|
||||
Rebuild all major sections supported by the source, preserving the original
|
||||
page flow instead of collapsing it into a smaller subset. Match the
|
||||
composition, section order, spacing, imagery placement, and responsive
|
||||
structure as closely as practical from the imported source.
|
||||
|
||||
Detect and preserve any motion patterns evidenced by the captured import
|
||||
structure, including scroll reveals, marquee effects, hover states, masked
|
||||
text reveals, parallax, or ambient background movement.
|
||||
|
||||
Avoid long inline SVG markup unless there is no practical alternative. Let
|
||||
the captured page structure from the imported site drive supporting structure
|
||||
and let the DESIGN.md drive design-system and asset decisions instead of
|
||||
adding extra interpretation.
|
||||
|
||||
Rebuild it as clean, maintainable HTML, CSS, and JavaScript instead of
|
||||
converting it into React.
|
||||
|
||||
Attached Files: DESIGN.md (7.7 KB)
|
||||
|
||||
This import is in EXACTLY mode. Screenshot capture timed out, so treat the
|
||||
captured page structure from the imported site as the required structural
|
||||
reference and the attached DESIGN.md as the design-system and asset
|
||||
reference. Match the original texts, names, numbers, and brand references
|
||||
unless something is clearly broken or inaccessible.
|
||||
|
||||
Preserve motion cues from the captured import structure when present, use
|
||||
the attached DESIGN.md as the supporting design-system and asset reference,
|
||||
and do not replace the imported design with Aura defaults or a new house
|
||||
style.
|
||||
|
||||
Detected source implementation cues that must be preserved:
|
||||
- Preserve the source CSS custom properties and theme tokens
|
||||
- Typography is explicitly defined in the source. Match the original font
|
||||
families, weights, and headline/body hierarchy
|
||||
- Preserve the detected runtime motion stack (GSAP, ScrollTrigger) and
|
||||
reproduce comparable scroll reveals, text animations, hover states
|
||||
- Marquee-style motion is present in the source. Keep that behavior
|
||||
- Three.js evidence is present in the imported source. Preserve the 3D
|
||||
scene or the closest faithful equivalent
|
||||
```
|
||||
|
||||
## Notion (WITH screenshot)
|
||||
|
||||
```
|
||||
Recreate the attached webpage EXACTLY like the screenshot as an HTML +
|
||||
JavaScript implementation using Tailwind CSS. Treat the screenshot as the
|
||||
primary visual reference. Use the captured page structure from the imported
|
||||
site as the structural reference and the attached DESIGN.md as a secondary
|
||||
typography and asset inventory reference.
|
||||
|
||||
Use DESIGN.md only to preserve font families, font weights, typographic
|
||||
tone, and asset references. If DESIGN.md conflicts with the screenshot on
|
||||
colors, surfaces, layout, or composition, follow the screenshot.
|
||||
|
||||
Avoid long inline SVG markup unless there is no practical alternative. Let
|
||||
the screenshot drive styling decisions instead of adding extra interpretation.
|
||||
|
||||
Attached Files: DESIGN.md (16.4 KB)
|
||||
|
||||
This import is in EXACTLY mode. Treat the screenshot as the primary visual
|
||||
reference, the captured page structure from the imported site as the
|
||||
structural source of truth, and the attached DESIGN.md as a secondary
|
||||
typography and asset inventory reference.
|
||||
|
||||
If the screenshot and captured structure conflict, follow the screenshot
|
||||
for layout, surfaces, typography, and motion. Use DESIGN.md only to
|
||||
preserve font families, font weights, typographic tone, and asset
|
||||
references. If DESIGN.md conflicts with the screenshot on colors, surfaces,
|
||||
layout, or composition, follow the screenshot.
|
||||
|
||||
Match the original texts, names, numbers, and brand references unless
|
||||
something is clearly broken or inaccessible.
|
||||
|
||||
Preserve motion cues from the screenshot when present, use the captured
|
||||
import structure as supporting structure, use the attached DESIGN.md as a
|
||||
secondary typography and asset inventory reference.
|
||||
|
||||
Do not replace the imported design with Aura defaults or a new house style.
|
||||
|
||||
Detected source implementation cues that must be preserved:
|
||||
- Preserve the source CSS custom properties and theme tokens
|
||||
- Typography is explicitly defined in the source. Match the original font
|
||||
families, weights, and headline/body hierarchy
|
||||
- Marquee-style motion is present in the source. Keep that behavior
|
||||
```
|
||||
|
||||
## Key Differences
|
||||
|
||||
| Aspect | NO screenshot | WITH screenshot |
|
||||
|--------|--------------|-----------------|
|
||||
| **Primary reference** | "captured page structure" (HTML) | "screenshot" (image) |
|
||||
| **DESIGN.md role** | "design-system and asset reference" (PRIMARY) | "secondary typography and asset inventory reference" (SECONDARY) |
|
||||
| **Conflict resolution** | DESIGN.md drives design decisions | "If DESIGN.md conflicts with the screenshot, follow the screenshot" |
|
||||
| **Output format** | "clean, maintainable HTML, CSS, and JavaScript" | "HTML + JavaScript implementation using Tailwind CSS" |
|
||||
| **Motion detection** | Lists specific: GSAP, ScrollTrigger, Three.js | Only: marquee, CSS custom properties |
|
||||
| **Structure emphasis** | "Rebuild all major sections...preserving the original page flow" | Less emphasis on structure completeness |
|
||||
|
||||
## What's SAME in Both
|
||||
|
||||
1. "EXACTLY mode" — match original texts, names, numbers, brand references
|
||||
2. "Do not replace the imported design with Aura defaults or a new house style"
|
||||
3. "Avoid long inline SVG markup"
|
||||
4. "Detected source implementation cues" section (dynamic, varies per site)
|
||||
5. "Preserve motion cues"
|
||||
6. DESIGN.md always attached
|
||||
7. "Captured page structure" always referenced
|
||||
|
||||
## What's Dynamic (Varies Per Site)
|
||||
|
||||
The "Detected source implementation cues" section changes based on what Aura found in the HTML:
|
||||
- Soulscape: GSAP, ScrollTrigger, Three.js, marquee (JS-heavy site)
|
||||
- Notion: CSS custom properties, marquee only (CSS-heavy site)
|
||||
- This section is programmatically generated based on source code analysis
|
||||
@@ -28,6 +28,9 @@
|
||||
"generate:previews": "tsx scripts/generate-template-previews.ts",
|
||||
"prepare": "test -d .git && lefthook install || true"
|
||||
},
|
||||
"dependencies": {
|
||||
"purgecss": "^8.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@commitlint/cli": "^20.5.0",
|
||||
"@commitlint/config-conventional": "^20.5.0",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.82.0",
|
||||
"@hono/node-server": "^1.8.0",
|
||||
"@puppeteer/browsers": "^2.13.0",
|
||||
"adm-zip": "^0.5.16",
|
||||
@@ -36,7 +37,9 @@
|
||||
"mime-types": "^3.0.2",
|
||||
"open": "^10.0.0",
|
||||
"postcss": "^8.5.8",
|
||||
"puppeteer-core": "^24.39.1"
|
||||
"prettier": "^3.8.1",
|
||||
"puppeteer-core": "^24.39.1",
|
||||
"purgecss": "^8.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@clack/prompts": "^1.1.0",
|
||||
|
||||
Generated
+1244
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Compare real Notion page vs our capture — find what's missing.
|
||||
* Run: npx tsx packages/cli/src/capture/_test_notion_compare.ts
|
||||
*/
|
||||
|
||||
import puppeteer from "puppeteer-core";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
async function main() {
|
||||
const { ensureBrowser } = await import("../browser/manager.js");
|
||||
const browser = await ensureBrowser();
|
||||
const b = await puppeteer.launch({
|
||||
headless: true,
|
||||
executablePath: browser.executablePath,
|
||||
args: ["--no-sandbox"],
|
||||
});
|
||||
const page = await b.newPage();
|
||||
await page.setViewport({ width: 1920, height: 1080 });
|
||||
|
||||
console.log("Loading notion.com...");
|
||||
await page.goto("https://www.notion.com", {
|
||||
waitUntil: "networkidle0",
|
||||
timeout: 30000,
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 5000));
|
||||
|
||||
// Scroll through to trigger lazy loading
|
||||
await page.evaluate(`(async () => {
|
||||
var h = document.body.scrollHeight;
|
||||
for (var y = 0; y < h + 1000; y += 500) {
|
||||
window.scrollTo(0, y);
|
||||
await new Promise(function(r) { setTimeout(r, 300); });
|
||||
}
|
||||
window.scrollTo(0, 0);
|
||||
await new Promise(function(r) { setTimeout(r, 1000); });
|
||||
})()`);
|
||||
|
||||
// Get the REAL page structure
|
||||
const realPage = await page.evaluate(`(() => {
|
||||
var sections = [];
|
||||
|
||||
// Find all major sections
|
||||
document.querySelectorAll("section, main > div, [class*='section']").forEach(function(el) {
|
||||
var rect = el.getBoundingClientRect();
|
||||
if (rect.height < 100) return;
|
||||
var h = el.querySelector("h1, h2, h3");
|
||||
var heading = h ? h.textContent.trim().slice(0, 60) : "";
|
||||
if (!heading) return;
|
||||
|
||||
// Count images in this section
|
||||
var imgs = el.querySelectorAll("img");
|
||||
var visibleImgs = Array.from(imgs).filter(function(img) {
|
||||
return img.offsetWidth > 0 && img.naturalWidth > 0;
|
||||
});
|
||||
var brokenImgs = Array.from(imgs).filter(function(img) {
|
||||
return img.offsetWidth > 0 && img.naturalWidth === 0;
|
||||
});
|
||||
|
||||
// Count SVGs
|
||||
var svgs = el.querySelectorAll("svg");
|
||||
|
||||
// Count videos
|
||||
var videos = el.querySelectorAll("video");
|
||||
|
||||
// Count iframes
|
||||
var iframes = el.querySelectorAll("iframe");
|
||||
|
||||
// Check for background images
|
||||
var bgImgs = 0;
|
||||
el.querySelectorAll("*").forEach(function(child) {
|
||||
var bg = getComputedStyle(child).backgroundImage;
|
||||
if (bg && bg !== "none" && !bg.includes("gradient")) bgImgs++;
|
||||
});
|
||||
|
||||
sections.push({
|
||||
heading: heading,
|
||||
y: Math.round(rect.top + window.scrollY),
|
||||
height: Math.round(rect.height),
|
||||
totalImgs: imgs.length,
|
||||
visibleImgs: visibleImgs.length,
|
||||
brokenImgs: brokenImgs.length,
|
||||
svgCount: svgs.length,
|
||||
videoCount: videos.length,
|
||||
iframeCount: iframes.length,
|
||||
bgImgCount: bgImgs,
|
||||
// Sample image srcs
|
||||
imgSrcs: Array.from(visibleImgs).slice(0, 3).map(function(img) {
|
||||
return { src: img.src.slice(0, 80), w: img.naturalWidth, h: img.naturalHeight };
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
// Deduplicate by heading
|
||||
var seen = {};
|
||||
sections = sections.filter(function(s) {
|
||||
if (seen[s.heading]) return false;
|
||||
seen[s.heading] = true;
|
||||
return true;
|
||||
});
|
||||
|
||||
return {
|
||||
totalSections: sections.length,
|
||||
pageHeight: document.body.scrollHeight,
|
||||
totalImages: document.querySelectorAll("img").length,
|
||||
totalSvgs: document.querySelectorAll("svg").length,
|
||||
totalVideos: document.querySelectorAll("video").length,
|
||||
sections: sections,
|
||||
};
|
||||
})()`);
|
||||
|
||||
console.log("\n=== REAL NOTION PAGE ===");
|
||||
console.log(`Page height: ${realPage.pageHeight}px`);
|
||||
console.log(`Total images: ${realPage.totalImages}`);
|
||||
console.log(`Total SVGs: ${realPage.totalSvgs}`);
|
||||
console.log(`Total videos: ${realPage.totalVideos}`);
|
||||
console.log(`\nSections (${realPage.totalSections}):`);
|
||||
|
||||
for (const s of realPage.sections) {
|
||||
console.log(`\n "${s.heading}"`);
|
||||
console.log(` y=${s.y} h=${s.height}`);
|
||||
console.log(` imgs: ${s.visibleImgs} visible, ${s.brokenImgs} broken, ${s.totalImgs} total`);
|
||||
console.log(
|
||||
` svgs: ${s.svgCount}, videos: ${s.videoCount}, iframes: ${s.iframeCount}, bgImgs: ${s.bgImgCount}`,
|
||||
);
|
||||
if (s.imgSrcs.length > 0) {
|
||||
for (const img of s.imgSrcs) {
|
||||
console.log(` → ${img.src} (${img.w}x${img.h})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Now compare with our capture
|
||||
console.log("\n\n=== OUR CAPTURE ===");
|
||||
try {
|
||||
const tokens = JSON.parse(readFileSync("/tmp/notion-capture5/extracted/tokens.json", "utf-8"));
|
||||
console.log(`Captured sections: ${tokens.sections.length}`);
|
||||
for (const s of tokens.sections) {
|
||||
console.log(` ${s.type}: "${s.heading}" y=${s.y}`);
|
||||
}
|
||||
} catch {
|
||||
console.log("Could not read capture data");
|
||||
}
|
||||
|
||||
await b.close();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,28 @@
|
||||
import puppeteer from "puppeteer-core";
|
||||
async function main() {
|
||||
const { ensureBrowser } = await import("../browser/manager.js");
|
||||
const browser = await ensureBrowser();
|
||||
const b = await puppeteer.launch({
|
||||
headless: true,
|
||||
executablePath: browser.executablePath,
|
||||
args: ["--no-sandbox"],
|
||||
});
|
||||
const page = await b.newPage();
|
||||
await page.setViewport({ width: 1920, height: 1080 });
|
||||
await page.goto("https://notion.so", { waitUntil: "networkidle0", timeout: 30000 });
|
||||
await new Promise((r) => setTimeout(r, 5000));
|
||||
|
||||
const info = await page.evaluate(`(() => {
|
||||
var headLinks = Array.from(document.head.querySelectorAll('link[rel="stylesheet"][href]'));
|
||||
var allLinks = Array.from(document.querySelectorAll('link[rel="stylesheet"][href]'));
|
||||
return {
|
||||
headLinkCount: headLinks.length,
|
||||
headLinkHrefs: headLinks.map(function(l) { return l.href.slice(0, 80); }),
|
||||
allLinkCount: allLinks.length,
|
||||
};
|
||||
})()`);
|
||||
|
||||
console.log(JSON.stringify(info, null, 2));
|
||||
await b.close();
|
||||
}
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* Generate CLAUDE.md (and .cursorrules) for captured website projects.
|
||||
*
|
||||
* This is the equivalent of Aura.build's auto-generated prompt that tells
|
||||
* the AI agent how to use the DESIGN.md and screenshot to create output.
|
||||
*
|
||||
* The file is placed at the project root so AI agents read it automatically:
|
||||
* - Claude Code reads CLAUDE.md
|
||||
* - Cursor reads .cursorrules
|
||||
* - Other agents typically read README.md or project-root markdown
|
||||
*/
|
||||
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { DesignTokens } from "./types.js";
|
||||
import type { AnimationCatalog } from "./animationCataloger.js";
|
||||
|
||||
export function generateAgentPrompt(
|
||||
outputDir: string,
|
||||
url: string,
|
||||
tokens: DesignTokens,
|
||||
animations: AnimationCatalog | undefined,
|
||||
hasScreenshot: boolean,
|
||||
hasDesignMd: boolean,
|
||||
): void {
|
||||
const prompt = buildPrompt(url, tokens, animations, hasScreenshot, hasDesignMd);
|
||||
|
||||
// Write CLAUDE.md (Claude Code reads this automatically)
|
||||
writeFileSync(join(outputDir, "CLAUDE.md"), prompt, "utf-8");
|
||||
|
||||
// Write .cursorrules (Cursor reads this automatically)
|
||||
writeFileSync(join(outputDir, ".cursorrules"), prompt, "utf-8");
|
||||
}
|
||||
|
||||
function buildPrompt(
|
||||
url: string,
|
||||
tokens: DesignTokens,
|
||||
animations: AnimationCatalog | undefined,
|
||||
hasScreenshot: boolean,
|
||||
hasDesignMd: boolean,
|
||||
): string {
|
||||
const hostname = new URL(url).hostname.replace(/^www\./, "");
|
||||
|
||||
// Detect implementation cues from the source
|
||||
const cues = detectImplementationCues(tokens, animations);
|
||||
|
||||
const _screenshotRef = hasScreenshot ? "screenshots/full-page.png" : null;
|
||||
|
||||
// Build the main instruction block
|
||||
let md = `# ${tokens.title || hostname} — Captured Website
|
||||
|
||||
This project was captured from [${url}](${url}) using \`hyperframes capture\`.
|
||||
|
||||
## What's in this project
|
||||
|
||||
${hasDesignMd ? `- **DESIGN.md** — Complete design system (colors, typography, elevation, components, do's/don'ts, and every asset URL with its HTML context). **READ THIS FIRST.**` : ""}
|
||||
${hasScreenshot ? `- **screenshots/full-page.png** — Full-page screenshot of the live website. **READ THIS IMAGE** as your primary visual reference.` : ""}
|
||||
- **compositions/** — Extracted page sections as editable HyperFrames HTML compositions (CSS-purged, prettified, AI-readable).
|
||||
- **assets/** — Downloaded fonts, logos, images, and favicon.
|
||||
- **extracted/** — Raw HTML, CSS, and animation data from the source page.
|
||||
|
||||
## How to use this capture
|
||||
|
||||
`;
|
||||
|
||||
if (hasScreenshot && hasDesignMd) {
|
||||
// BOTH screenshot and DESIGN.md available (best case — like Aura's Notion capture)
|
||||
md += `Treat the **full-page screenshot** as the primary visual reference. Use the **DESIGN.md** as the design-system and asset inventory reference. Use the **compositions/** as ready-made building blocks that can be used as-is or remixed.
|
||||
|
||||
If DESIGN.md conflicts with the screenshot on colors, surfaces, layout, or composition, **follow the screenshot**. Use DESIGN.md to preserve exact font families, font weights, typographic tone, asset URLs, and design tokens.
|
||||
|
||||
`;
|
||||
} else if (hasDesignMd) {
|
||||
// Only DESIGN.md (screenshot failed — like Aura's Soulscape capture)
|
||||
md += `Screenshot capture was not available. Use the **DESIGN.md** as both the design-system reference and the structural guide. Use the **compositions/** as the primary structural reference for the page layout and content.
|
||||
|
||||
Use the DESIGN.md to preserve exact design-system choices, asset references, colors, typography, and component patterns. Do not invent new design patterns — follow what's documented.
|
||||
|
||||
`;
|
||||
} else {
|
||||
md += `Use the **compositions/** as the primary reference for design and structure. Reference **assets/** for fonts, logos, and images.
|
||||
|
||||
`;
|
||||
}
|
||||
|
||||
// Common instructions
|
||||
md += `Match the original texts, names, numbers, and brand references from the source site. Do not replace the captured design with generic defaults or a different house style.
|
||||
|
||||
`;
|
||||
|
||||
// Detected implementation cues
|
||||
if (cues.length > 0) {
|
||||
md += `## Detected source implementation cues
|
||||
|
||||
These patterns were detected in the source and should be preserved:
|
||||
|
||||
`;
|
||||
for (const cue of cues) {
|
||||
md += `- ${cue}\n`;
|
||||
}
|
||||
md += "\n";
|
||||
}
|
||||
|
||||
// HyperFrames-specific instructions
|
||||
md += `## Creating video compositions
|
||||
|
||||
This capture is designed for use with **HyperFrames** — an HTML-to-video framework. When creating video compositions:
|
||||
|
||||
1. Use \`/hyperframes-compose\` skill before writing any composition HTML
|
||||
2. Reference the DESIGN.md for exact colors, fonts, and component styling
|
||||
3. Use compositions from \`compositions/\` as background footage or extract individual components to remix
|
||||
4. Reference assets by their URLs from the DESIGN.md Assets section
|
||||
5. After creating or editing compositions, run \`npx hyperframes lint\` and \`npx hyperframes validate\`
|
||||
|
||||
### Quick start prompts
|
||||
|
||||
**15-second social ad:**
|
||||
> Create a 15s social ad video using this captured website's design system. Use the DESIGN.md for brand colors, typography, and component styling. Create 4 scenes: Hook (4s), Features (5s), Social Proof (3s), CTA (3s).
|
||||
|
||||
**30-second product tour:**
|
||||
> Create a 30s product tour video. Walk through the main sections of the captured website, highlighting key features. Use the exact screenshots and component patterns from the capture.
|
||||
|
||||
**Component remix video:**
|
||||
> Extract individual UI components from the captured compositions and remix them into a new narrative. Change the text, rearrange the layout, combine elements from different sections.
|
||||
`;
|
||||
|
||||
return md;
|
||||
}
|
||||
|
||||
function detectImplementationCues(
|
||||
tokens: DesignTokens,
|
||||
animations: AnimationCatalog | undefined,
|
||||
): string[] {
|
||||
const cues: string[] = [];
|
||||
|
||||
// CSS custom properties
|
||||
if (Object.keys(tokens.cssVariables).length > 10) {
|
||||
cues.push(
|
||||
"The source uses CSS custom properties extensively. Preserve these design tokens for backgrounds, text, buttons, and spacing instead of using hardcoded values.",
|
||||
);
|
||||
}
|
||||
|
||||
// Typography
|
||||
if (tokens.fonts.length > 0) {
|
||||
cues.push(
|
||||
`Typography is explicitly defined in the source (${tokens.fonts.join(", ")}). Match the original font families, weights, and headline/body hierarchy instead of defaulting to a system stack.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Animations
|
||||
if (animations?.summary) {
|
||||
if (animations.summary.scrollTargets > 20) {
|
||||
cues.push(
|
||||
`Scroll-triggered animations are present in the source (${animations.summary.scrollTargets} IntersectionObserver targets). Preserve scroll reveal behavior.`,
|
||||
);
|
||||
}
|
||||
if (animations.summary.webAnimations > 5) {
|
||||
cues.push(
|
||||
`Web Animations API is used extensively (${animations.summary.webAnimations} active animations). Preserve entrance and interaction animations.`,
|
||||
);
|
||||
}
|
||||
if (animations.summary.canvases > 0) {
|
||||
cues.push(
|
||||
`Canvas/WebGL elements detected (${animations.summary.canvases}). The source may use shader effects or 3D rendering.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Marquee detection (from CSS or animation data)
|
||||
const hasMarquee = animations?.cssDeclarations?.some(
|
||||
(d) =>
|
||||
d.animation?.name?.toLowerCase().includes("marquee") ||
|
||||
d.animation?.name?.toLowerCase().includes("scroll"),
|
||||
);
|
||||
if (hasMarquee) {
|
||||
cues.push(
|
||||
"Marquee-style motion is present in the source. Preserve continuous horizontal scrolling behavior instead of replacing with a static section.",
|
||||
);
|
||||
}
|
||||
|
||||
return cues;
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
/**
|
||||
* Catalog all animations on a rendered page.
|
||||
*
|
||||
* Captures:
|
||||
* 1. Web Animations API — active animations with full keyframes + timing
|
||||
* 2. CSS animation/transition declarations via getComputedStyle
|
||||
* 3. IntersectionObserver targets (scroll-triggered elements)
|
||||
* 4. CDP Animation domain events
|
||||
*
|
||||
* The catalog is saved as animations.json and gives Claude Code
|
||||
* everything needed to recreate animations in GSAP.
|
||||
*
|
||||
* NOTE: Must be used on a page with ALL scripts running (not stripped).
|
||||
* Call setupAnimationCapture() BEFORE page.goto() for IO patching.
|
||||
* Call collectAnimationCatalog() AFTER page has loaded and settled.
|
||||
*/
|
||||
|
||||
import type { Page, CDPSession } from "puppeteer-core";
|
||||
|
||||
export interface AnimationCatalog {
|
||||
/** Active animations via document.getAnimations() — includes keyframes */
|
||||
webAnimations: WebAnimationEntry[];
|
||||
/** Elements with CSS animation/transition properties declared */
|
||||
cssDeclarations: CssAnimationEntry[];
|
||||
/** Elements being watched by IntersectionObserver (scroll triggers) */
|
||||
scrollTargets: ScrollTarget[];
|
||||
/** CDP Animation domain events captured during page lifecycle */
|
||||
cdpAnimations: CdpAnimationEntry[];
|
||||
/** Total counts summary */
|
||||
summary: {
|
||||
webAnimations: number;
|
||||
cssDeclarations: number;
|
||||
scrollTargets: number;
|
||||
cdpAnimations: number;
|
||||
canvases: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface WebAnimationEntry {
|
||||
type: string;
|
||||
playState: string;
|
||||
animationName?: string;
|
||||
targetSelector?: string;
|
||||
targetRect?: { x: number; y: number; width: number; height: number };
|
||||
keyframes?: Array<Record<string, string | number | null>>;
|
||||
timing?: {
|
||||
duration: number;
|
||||
delay: number;
|
||||
iterations: number;
|
||||
easing: string;
|
||||
direction: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CssAnimationEntry {
|
||||
selector: string;
|
||||
animation?: { name: string; duration: string; easing: string };
|
||||
transition?: { property: string; duration: string };
|
||||
}
|
||||
|
||||
export interface ScrollTarget {
|
||||
selector: string;
|
||||
rect: { top: number; height: number; width: number };
|
||||
}
|
||||
|
||||
export interface CdpAnimationEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
type: string;
|
||||
duration?: number;
|
||||
delay?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up animation capture hooks BEFORE navigating to the page.
|
||||
* This patches IntersectionObserver to track scroll-triggered elements.
|
||||
*/
|
||||
export async function setupAnimationCapture(page: Page): Promise<void> {
|
||||
await page.evaluateOnNewDocument(`
|
||||
window.__hf_io_targets = [];
|
||||
var OrigIO = window.IntersectionObserver;
|
||||
window.IntersectionObserver = function(callback, options) {
|
||||
var observer = new OrigIO(callback, options);
|
||||
var origObserve = observer.observe.bind(observer);
|
||||
observer.observe = function(target) {
|
||||
var sel = target.id ? '#' + target.id : target.tagName.toLowerCase();
|
||||
if (target.className && typeof target.className === 'string') {
|
||||
var cls = Array.from(target.classList).slice(0, 2).join('.');
|
||||
if (cls) sel += '.' + cls;
|
||||
}
|
||||
try {
|
||||
var rect = target.getBoundingClientRect();
|
||||
window.__hf_io_targets.push({
|
||||
selector: sel,
|
||||
rect: { top: Math.round(rect.top + window.scrollY), height: Math.round(rect.height), width: Math.round(rect.width) }
|
||||
});
|
||||
} catch(e) {}
|
||||
return origObserve(target);
|
||||
};
|
||||
return observer;
|
||||
};
|
||||
window.IntersectionObserver.prototype = OrigIO.prototype;
|
||||
`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start CDP Animation domain listener.
|
||||
* Returns the CDPSession and a reference to the captured array.
|
||||
*/
|
||||
export async function startCdpAnimationCapture(
|
||||
page: Page,
|
||||
): Promise<{ cdp: CDPSession; animations: CdpAnimationEntry[] }> {
|
||||
const cdp = await page.createCDPSession();
|
||||
await cdp.send("Animation.enable");
|
||||
const animations: CdpAnimationEntry[] = [];
|
||||
|
||||
cdp.on("Animation.animationStarted", (event: any) => {
|
||||
animations.push({
|
||||
id: event.animation.id,
|
||||
name: event.animation.name || "",
|
||||
type: event.animation.type,
|
||||
duration: event.animation.source?.duration,
|
||||
delay: event.animation.source?.delay,
|
||||
});
|
||||
});
|
||||
|
||||
return { cdp, animations };
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect the full animation catalog after page has loaded and settled.
|
||||
* Should be called after scrolling through the page to trigger all animations.
|
||||
*/
|
||||
export async function collectAnimationCatalog(
|
||||
page: Page,
|
||||
cdpAnimations: CdpAnimationEntry[],
|
||||
cdp: CDPSession,
|
||||
): Promise<AnimationCatalog> {
|
||||
// Scroll through page to trigger scroll-based animations
|
||||
await page.evaluate(`(async () => {
|
||||
var height = document.body.scrollHeight;
|
||||
for (var y = 0; y < height; y += window.innerHeight * 0.5) {
|
||||
window.scrollTo(0, y);
|
||||
await new Promise(function(r) { setTimeout(r, 400); });
|
||||
}
|
||||
window.scrollTo(0, 0);
|
||||
await new Promise(function(r) { setTimeout(r, 1000); });
|
||||
})()`);
|
||||
|
||||
// Collect from Web Animations API + computed styles + IO targets
|
||||
const result = (await page.evaluate(`(() => {
|
||||
var webAnimations = [];
|
||||
var cssDeclarations = [];
|
||||
|
||||
// 1. Web Animations API
|
||||
try {
|
||||
var anims = document.getAnimations();
|
||||
webAnimations = anims.map(function(anim) {
|
||||
var r = { type: anim.constructor.name, playState: anim.playState, animationName: anim.animationName || null };
|
||||
var effect = anim.effect;
|
||||
if (effect && effect.target) {
|
||||
var t = effect.target;
|
||||
r.targetSelector = t.id ? '#' + t.id : t.tagName.toLowerCase();
|
||||
if (t.className && typeof t.className === 'string') {
|
||||
var cls = Array.from(t.classList).slice(0, 3).join('.');
|
||||
if (cls) r.targetSelector += '.' + cls;
|
||||
}
|
||||
try { r.targetRect = t.getBoundingClientRect().toJSON(); } catch(e) {}
|
||||
}
|
||||
if (effect && typeof effect.getKeyframes === 'function') {
|
||||
try { r.keyframes = effect.getKeyframes(); } catch(e) {}
|
||||
}
|
||||
if (effect && typeof effect.getComputedTiming === 'function') {
|
||||
try {
|
||||
var timing = effect.getComputedTiming();
|
||||
r.timing = { duration: timing.duration, delay: timing.delay, iterations: timing.iterations, easing: timing.easing, direction: timing.direction };
|
||||
} catch(e) {}
|
||||
}
|
||||
return r;
|
||||
});
|
||||
} catch(e) {}
|
||||
|
||||
// 2. CSS animation/transition scan
|
||||
var allEls = document.querySelectorAll('*');
|
||||
for (var i = 0; i < allEls.length && i < 5000; i++) {
|
||||
var el = allEls[i];
|
||||
try {
|
||||
var cs = getComputedStyle(el);
|
||||
var hasAnim = cs.animationName && cs.animationName !== 'none';
|
||||
var hasTrans = cs.transitionProperty && cs.transitionProperty !== 'all' && cs.transitionProperty !== 'none' && cs.transitionDuration !== '0s';
|
||||
if (hasAnim || hasTrans) {
|
||||
var sel = el.id ? '#' + el.id : el.tagName.toLowerCase();
|
||||
if (el.className && typeof el.className === 'string') {
|
||||
var cls = Array.from(el.classList).slice(0, 2).join('.');
|
||||
if (cls) sel += '.' + cls;
|
||||
}
|
||||
var entry = { selector: sel };
|
||||
if (hasAnim) entry.animation = { name: cs.animationName, duration: cs.animationDuration, easing: cs.animationTimingFunction };
|
||||
if (hasTrans) entry.transition = { property: cs.transitionProperty, duration: cs.transitionDuration };
|
||||
cssDeclarations.push(entry);
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
|
||||
// 3. IO targets (collected by monkey-patch)
|
||||
var scrollTargets = (window.__hf_io_targets || []).map(function(t) {
|
||||
return { selector: t.selector, rect: t.rect };
|
||||
});
|
||||
|
||||
// 4. Canvas summary
|
||||
var canvasCount = document.querySelectorAll('canvas').length;
|
||||
|
||||
return { webAnimations: webAnimations, cssDeclarations: cssDeclarations, scrollTargets: scrollTargets, canvasCount: canvasCount };
|
||||
})()`)) as any;
|
||||
|
||||
// Stop CDP listener
|
||||
await cdp.send("Animation.disable");
|
||||
|
||||
return {
|
||||
webAnimations: result.webAnimations,
|
||||
cssDeclarations: result.cssDeclarations,
|
||||
scrollTargets: result.scrollTargets,
|
||||
cdpAnimations,
|
||||
summary: {
|
||||
webAnimations: result.webAnimations.length,
|
||||
cssDeclarations: result.cssDeclarations.length,
|
||||
scrollTargets: result.scrollTargets.length,
|
||||
cdpAnimations: cdpAnimations.length,
|
||||
canvases: result.canvasCount,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
/**
|
||||
* Comprehensive asset cataloger.
|
||||
*
|
||||
* Scans rendered HTML and CSS for every referenced asset (images, videos,
|
||||
* fonts, icons, stylesheets, backgrounds) and records the HTML context
|
||||
* where each was found (e.g., img[src], css url(), link[rel=preload]).
|
||||
*
|
||||
* This is the programmatic Part 1 of DESIGN.md generation — deterministic
|
||||
* extraction, no AI involved.
|
||||
*/
|
||||
|
||||
import type { Page } from "puppeteer-core";
|
||||
|
||||
export interface CatalogedAsset {
|
||||
url: string;
|
||||
type: "Image" | "Video" | "Font" | "Icon" | "Background" | "Other";
|
||||
contexts: string[];
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract all referenced assets from the rendered page with their HTML contexts.
|
||||
*/
|
||||
export async function catalogAssets(page: Page): Promise<CatalogedAsset[]> {
|
||||
const assets = await page.evaluate(`(() => {
|
||||
var assetMap = {};
|
||||
|
||||
function add(url, type, context, notes) {
|
||||
if (!url || url === '' || url.startsWith('data:') || url.startsWith('blob:') || url === 'about:blank') return;
|
||||
// Normalize URL
|
||||
try { url = new URL(url, document.baseURI).href; } catch(e) { return; }
|
||||
// Skip tiny inline data URIs but keep base64 SVGs
|
||||
if (url.length > 50000) return;
|
||||
// Filter tracking pixels and analytics
|
||||
var lurl = url.toLowerCase();
|
||||
if (lurl.indexOf('analytics.') > -1 || lurl.indexOf('adsct') > -1 || lurl.indexOf('pixel.') > -1 || lurl.indexOf('tracking.') > -1 || lurl.indexOf('pdscrb.') > -1 || lurl.indexOf('doubleclick') > -1 || lurl.indexOf('googlesyndication') > -1 || lurl.indexOf('facebook.com/tr') > -1 || lurl.indexOf('bat.bing') > -1 || lurl.indexOf('clarity.ms') > -1) return;
|
||||
if (lurl.indexOf('bci=') > -1 && lurl.indexOf('twpid=') > -1) return;
|
||||
if (lurl.indexOf('cachebust=') > -1 || lurl.indexOf('event_id=') > -1) return;
|
||||
// Filter CSS fragment references to SVG filter IDs (not real downloadable assets)
|
||||
// e.g., "page.css#hph-illustration-filter", "#linkedin-clip-1"
|
||||
if (url.indexOf('.css#') > -1) return;
|
||||
// Filter same-page fragment references like "https://site.com/#clip-1"
|
||||
try { var parsed = new URL(url); if (parsed.hash && parsed.pathname.length <= 1) return; } catch(e2) {}
|
||||
|
||||
if (!assetMap[url]) {
|
||||
assetMap[url] = { url: url, type: type, contexts: [], notes: null };
|
||||
}
|
||||
var entry = assetMap[url];
|
||||
if (entry.contexts.indexOf(context) === -1) {
|
||||
entry.contexts.push(context);
|
||||
}
|
||||
if (notes && !entry.notes) {
|
||||
entry.notes = notes;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Images: <img src="..."> and <img srcset="..."> ──
|
||||
document.querySelectorAll('img[src]').forEach(function(img) {
|
||||
var notes = img.alt || img.getAttribute('aria-label') || null;
|
||||
add(img.src, 'Image', 'img[src]', notes);
|
||||
if (img.srcset) {
|
||||
img.srcset.split(',').forEach(function(entry) {
|
||||
var u = entry.trim().split(/\\s+/)[0];
|
||||
if (u) add(u, 'Image', 'img[srcset]', notes);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ── Picture sources: <source srcset="..."> ──
|
||||
document.querySelectorAll('source[srcset]').forEach(function(src) {
|
||||
src.srcset.split(',').forEach(function(entry) {
|
||||
var u = entry.trim().split(/\\s+/)[0];
|
||||
if (u) add(u, 'Image', 'source[srcset]', null);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Videos: <video src="..."> and <video poster="..."> ──
|
||||
document.querySelectorAll('video[src]').forEach(function(v) {
|
||||
add(v.src, 'Video', 'video[src]', null);
|
||||
});
|
||||
document.querySelectorAll('video source[src]').forEach(function(s) {
|
||||
add(s.src, 'Video', 'video source[src]', null);
|
||||
});
|
||||
document.querySelectorAll('video[poster]').forEach(function(v) {
|
||||
add(v.poster, 'Image', 'video[poster]', null);
|
||||
});
|
||||
|
||||
// ── Links: preload, icon, apple-touch-icon, stylesheet ──
|
||||
document.querySelectorAll('link[rel]').forEach(function(link) {
|
||||
var rel = link.rel.toLowerCase();
|
||||
var href = link.href;
|
||||
if (!href) return;
|
||||
|
||||
if (rel.includes('preload')) {
|
||||
var asType = link.getAttribute('as') || '';
|
||||
if (asType === 'font') add(href, 'Font', 'link[rel="preload"]', null);
|
||||
else if (asType === 'image') add(href, 'Image', 'link[rel="preload"]', null);
|
||||
else if (asType === 'video') add(href, 'Video', 'link[rel="preload"]', null);
|
||||
else if (asType === 'style') add(href, 'Other', 'link[rel="preload"]', null);
|
||||
else add(href, 'Other', 'link[rel="preload"]', null);
|
||||
}
|
||||
if (rel.includes('icon')) add(href, 'Icon', 'link[rel="' + rel + '"]', null);
|
||||
if (rel === 'apple-touch-icon') add(href, 'Icon', 'link[rel="apple-touch-icon"]', null);
|
||||
});
|
||||
|
||||
// ── Meta: og:image, twitter:image ──
|
||||
document.querySelectorAll('meta[property="og:image"], meta[content][name="twitter:image"]').forEach(function(m) {
|
||||
var content = m.getAttribute('content');
|
||||
if (content) {
|
||||
var prop = m.getAttribute('property') || m.getAttribute('name') || '';
|
||||
add(content, 'Image', 'meta[' + prop + ']', null);
|
||||
}
|
||||
});
|
||||
|
||||
// ── CSS url() references from all stylesheets ──
|
||||
try {
|
||||
for (var i = 0; i < document.styleSheets.length; i++) {
|
||||
try {
|
||||
var sheet = document.styleSheets[i];
|
||||
var rules = sheet.cssRules || sheet.rules;
|
||||
if (!rules) continue;
|
||||
for (var j = 0; j < rules.length; j++) {
|
||||
var rule = rules[j];
|
||||
var cssText = rule.cssText || '';
|
||||
var urlMatches = cssText.match(/url\\(["']?([^"')]+)["']?\\)/g);
|
||||
if (urlMatches) {
|
||||
urlMatches.forEach(function(m) {
|
||||
var u = m.replace(/url\\(["']?/, '').replace(/["']?\\)/, '');
|
||||
if (u.startsWith('data:')) return;
|
||||
// Classify by file extension
|
||||
if (/\\.(woff2?|ttf|otf|eot)$/i.test(u)) {
|
||||
add(u, 'Font', 'css url()', null);
|
||||
} else if (/\\.(png|jpg|jpeg|gif|webp|avif|svg)$/i.test(u)) {
|
||||
add(u, 'Background', 'css url()', null);
|
||||
} else {
|
||||
add(u, 'Other', 'css url()', null);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch(e) { /* cross-origin stylesheet */ }
|
||||
}
|
||||
} catch(e) {}
|
||||
|
||||
// ── Inline style url() references ──
|
||||
document.querySelectorAll('[style]').forEach(function(el) {
|
||||
var style = el.getAttribute('style') || '';
|
||||
var urlMatches = style.match(/url\\(["']?([^"')]+)["']?\\)/g);
|
||||
if (urlMatches) {
|
||||
urlMatches.forEach(function(m) {
|
||||
var u = m.replace(/url\\(["']?/, '').replace(/["']?\\)/, '');
|
||||
if (u.startsWith('data:')) return;
|
||||
if (/\\.(woff2?|ttf|otf|eot)$/i.test(u)) {
|
||||
add(u, 'Font', 'html inline style url()', null);
|
||||
} else {
|
||||
add(u, 'Other', 'html inline style url()', null);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return Object.values(assetMap);
|
||||
})()`);
|
||||
|
||||
const raw = (assets as CatalogedAsset[]) || [];
|
||||
|
||||
// Deduplicate srcset resolution variants — keep highest resolution per base URL
|
||||
return deduplicateSrcsetVariants(raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deduplicate Next.js image variants (same image at different w= sizes).
|
||||
* Keeps the highest resolution version and merges contexts.
|
||||
*/
|
||||
function deduplicateSrcsetVariants(assets: CatalogedAsset[]): CatalogedAsset[] {
|
||||
const byBase = new Map<string, CatalogedAsset>();
|
||||
|
||||
for (const a of assets) {
|
||||
// Extract base URL by stripping w= and q= params from _next/image URLs
|
||||
let baseKey = a.url;
|
||||
try {
|
||||
const u = new URL(a.url);
|
||||
if (u.pathname.includes("_next/image") || u.searchParams.has("w")) {
|
||||
u.searchParams.delete("w");
|
||||
u.searchParams.delete("q");
|
||||
baseKey = u.toString();
|
||||
}
|
||||
} catch {
|
||||
/* not a valid URL, keep as-is */
|
||||
}
|
||||
|
||||
const existing = byBase.get(baseKey);
|
||||
if (existing) {
|
||||
// Merge contexts
|
||||
for (const ctx of a.contexts) {
|
||||
if (!existing.contexts.includes(ctx)) {
|
||||
existing.contexts.push(ctx);
|
||||
}
|
||||
}
|
||||
// Keep notes from whichever has them
|
||||
if (a.notes && !existing.notes) {
|
||||
existing.notes = a.notes;
|
||||
}
|
||||
// Keep the URL with highest w= value (largest image)
|
||||
const existingW = getWidthParam(existing.url);
|
||||
const newW = getWidthParam(a.url);
|
||||
if (newW > existingW) {
|
||||
existing.url = a.url;
|
||||
}
|
||||
} else {
|
||||
byBase.set(baseKey, { ...a, contexts: [...a.contexts] });
|
||||
}
|
||||
}
|
||||
|
||||
return [...byBase.values()];
|
||||
}
|
||||
|
||||
function getWidthParam(url: string): number {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
const w = u.searchParams.get("w");
|
||||
return w ? parseInt(w) : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format cataloged assets as markdown for the DESIGN.md Assets section.
|
||||
*/
|
||||
export function formatAssetCatalog(assets: CatalogedAsset[]): string {
|
||||
if (assets.length === 0) return "No assets detected.\n";
|
||||
|
||||
const lines: string[] = [];
|
||||
for (const a of assets) {
|
||||
const contexts = a.contexts.join(", ");
|
||||
const notes = a.notes ? ` | notes: ${a.notes}` : "";
|
||||
lines.push(`- **${a.type}**: ${a.url} — contexts: ${contexts}${notes}`);
|
||||
}
|
||||
return lines.join("\n") + "\n";
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Download assets (SVGs, images, favicon) from extracted tokens.
|
||||
*/
|
||||
|
||||
import { writeFileSync, mkdirSync } from "node:fs";
|
||||
import { join, extname } from "node:path";
|
||||
import type { DesignTokens, DownloadedAsset } from "./types.js";
|
||||
|
||||
export async function downloadAssets(
|
||||
tokens: DesignTokens,
|
||||
outputDir: string,
|
||||
): Promise<DownloadedAsset[]> {
|
||||
const assetsDir = join(outputDir, "assets");
|
||||
mkdirSync(assetsDir, { recursive: true });
|
||||
|
||||
const assets: DownloadedAsset[] = [];
|
||||
|
||||
// 1. SVG logos — save as files
|
||||
const logoSvgs = tokens.svgs.filter((s) => s.isLogo);
|
||||
for (let i = 0; i < logoSvgs.length && i < 5; i++) {
|
||||
const svg = logoSvgs[i];
|
||||
const name = svg.label ? slugify(svg.label) + ".svg" : `logo-${i}.svg`;
|
||||
const localPath = `assets/${name}`;
|
||||
try {
|
||||
writeFileSync(join(outputDir, localPath), svg.outerHTML, "utf-8");
|
||||
assets.push({ url: "", localPath, type: "svg" });
|
||||
} catch {
|
||||
/* skip */
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Favicon
|
||||
for (const icon of tokens.icons) {
|
||||
if (!icon.href) continue;
|
||||
try {
|
||||
const ext = extname(new URL(icon.href).pathname) || ".ico";
|
||||
const name = `favicon${ext}`;
|
||||
const localPath = `assets/${name}`;
|
||||
const buffer = await fetchBuffer(icon.href);
|
||||
if (buffer) {
|
||||
writeFileSync(join(outputDir, localPath), buffer);
|
||||
assets.push({ url: icon.href, localPath, type: "favicon" });
|
||||
break; // Only need one favicon
|
||||
}
|
||||
} catch {
|
||||
/* skip */
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Key images (hero, large product images) — download first 5
|
||||
const importantImages = tokens.images
|
||||
.filter((img) => img.width > 400 && img.src.startsWith("http"))
|
||||
.slice(0, 5);
|
||||
|
||||
for (let i = 0; i < importantImages.length; i++) {
|
||||
const img = importantImages[i];
|
||||
try {
|
||||
const url = new URL(img.src);
|
||||
const ext = extname(url.pathname) || ".jpg";
|
||||
const name = `image-${i}${ext}`;
|
||||
const localPath = `assets/${name}`;
|
||||
const buffer = await fetchBuffer(img.src);
|
||||
if (buffer) {
|
||||
writeFileSync(join(outputDir, localPath), buffer);
|
||||
assets.push({ url: img.src, localPath, type: "image" });
|
||||
}
|
||||
} catch {
|
||||
/* skip */
|
||||
}
|
||||
}
|
||||
|
||||
// 4. OG image
|
||||
if (tokens.ogImage) {
|
||||
try {
|
||||
const ext = extname(new URL(tokens.ogImage).pathname) || ".jpg";
|
||||
const localPath = `assets/og-image${ext}`;
|
||||
const buffer = await fetchBuffer(tokens.ogImage);
|
||||
if (buffer) {
|
||||
writeFileSync(join(outputDir, localPath), buffer);
|
||||
assets.push({ url: tokens.ogImage, localPath, type: "image" });
|
||||
}
|
||||
} catch {
|
||||
/* skip */
|
||||
}
|
||||
}
|
||||
|
||||
return assets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Download fonts referenced in CSS and rewrite URLs to local paths.
|
||||
* Returns the modified CSS string with local font paths.
|
||||
*/
|
||||
export async function downloadAndRewriteFonts(css: string, outputDir: string): Promise<string> {
|
||||
const assetsDir = join(outputDir, "assets", "fonts");
|
||||
mkdirSync(assetsDir, { recursive: true });
|
||||
|
||||
const fontUrlRegex = /url\(['"]?(https?:\/\/[^'")\s]+\.(?:woff2?|ttf|otf)[^'")\s]*?)['"]?\)/g;
|
||||
const fontUrls = new Set<string>();
|
||||
let match;
|
||||
while ((match = fontUrlRegex.exec(css)) !== null) {
|
||||
fontUrls.add(match[1]);
|
||||
}
|
||||
|
||||
if (fontUrls.size === 0) return css;
|
||||
|
||||
let rewritten = css;
|
||||
let count = 0;
|
||||
|
||||
for (const fontUrl of fontUrls) {
|
||||
try {
|
||||
const urlObj = new URL(fontUrl);
|
||||
const filename = urlObj.pathname.split("/").pop() || `font-${count}.woff2`;
|
||||
const localPath = join(assetsDir, filename);
|
||||
const relativePath = `assets/fonts/${filename}`;
|
||||
|
||||
const buffer = await fetchBuffer(fontUrl);
|
||||
if (buffer) {
|
||||
writeFileSync(localPath, buffer);
|
||||
rewritten = rewritten.split(fontUrl).join(relativePath);
|
||||
count++;
|
||||
}
|
||||
} catch {
|
||||
/* skip */
|
||||
}
|
||||
}
|
||||
|
||||
return rewritten;
|
||||
}
|
||||
|
||||
async function fetchBuffer(url: string): Promise<Buffer | null> {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
signal: AbortSignal.timeout(10000),
|
||||
headers: { "User-Agent": "HyperFrames/1.0" },
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const ab = await res.arrayBuffer();
|
||||
return Buffer.from(ab);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function slugify(text: string): string {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.slice(0, 40);
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
/**
|
||||
* Generate a prompt-ready design brief from captured website data.
|
||||
*
|
||||
* The brief is formatted like the 100 test prompts — specific hex colors,
|
||||
* exact text, font specs, animation timing — so Claude can build clean
|
||||
* HyperFrames compositions from scratch by reading the brief + screenshots.
|
||||
*/
|
||||
|
||||
import type { DesignTokens, DownloadedAsset } from "./types.js";
|
||||
import type { AnimationCatalog } from "./animationCataloger.js";
|
||||
|
||||
export function generateCaptureBrief(
|
||||
url: string,
|
||||
tokens: DesignTokens,
|
||||
animations: AnimationCatalog | undefined,
|
||||
screenshots: string[],
|
||||
assets: DownloadedAsset[],
|
||||
fontPaths: string[],
|
||||
): string {
|
||||
const sections = tokens.sections;
|
||||
const sectionCount = sections.filter(
|
||||
(s) => s.type !== "header" && s.type !== "footer" && s.heading,
|
||||
).length;
|
||||
const suggestedDuration = Math.max(15, sectionCount * 5);
|
||||
|
||||
let brief = `# Capture Brief: ${tokens.title}
|
||||
Source: ${url}
|
||||
|
||||
## How to Use This Brief
|
||||
|
||||
1. **Read each section below** — it describes what the original website looks like
|
||||
2. **Read each screenshot** — they show the exact visual layout
|
||||
3. **Build a new HyperFrames project** using \`/hyperframes\` skill
|
||||
4. **Use the exact values** from this brief: hex colors, font names, text content, timing
|
||||
5. **Reference \`assets/\`** for downloaded images and SVGs
|
||||
|
||||
## Project Overview
|
||||
|
||||
- **Title:** ${tokens.title}
|
||||
- **Description:** ${tokens.description}
|
||||
- **Suggested duration:** ${suggestedDuration}s (${sectionCount} content sections × 5s each)
|
||||
- **Canvas:** 1920×1080
|
||||
|
||||
## Brand System
|
||||
|
||||
### Colors
|
||||
${tokens.colors
|
||||
.slice(0, 10)
|
||||
.map((c) => `- \`${c}\``)
|
||||
.join("\n")}
|
||||
|
||||
### Typography
|
||||
- **Fonts:** ${tokens.fonts.join(", ") || "system-ui"}
|
||||
${fontPaths.length > 0 ? `- **Local files:** ${fontPaths.join(", ")}\n- Load with \`@font-face\` in compositions` : "- Use system fonts or Google Fonts CDN"}
|
||||
|
||||
### Headings (from site)
|
||||
${tokens.headings.map((h) => `- h${h.level}: "${h.text}" — ${h.fontSize} ${h.fontWeight} ${h.color}`).join("\n")}
|
||||
|
||||
### CTAs (from site)
|
||||
${tokens.ctas.map((c) => `- "${c.text}"${c.href ? ` → ${c.href}` : ""}`).join("\n")}
|
||||
|
||||
## Downloaded Assets
|
||||
|
||||
${assets.map((a) => `- \`${a.localPath}\` (${a.type})`).join("\n") || "None"}
|
||||
|
||||
## Screenshots (READ THESE)
|
||||
|
||||
${screenshots.map((s) => `- \`${s}\``).join("\n")}
|
||||
|
||||
---
|
||||
|
||||
## Sections
|
||||
|
||||
`;
|
||||
|
||||
// Sort sections by Y position
|
||||
const sorted = [...sections].sort((a, b) => a.y - b.y);
|
||||
let sectionIdx = 0;
|
||||
|
||||
for (const section of sorted) {
|
||||
// Skip empty headers/footers without headings
|
||||
if (!section.heading && (section.type === "header" || section.type === "footer")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
sectionIdx++;
|
||||
|
||||
// Find matching screenshot
|
||||
const screenshotMatch = screenshots.find(
|
||||
(s) =>
|
||||
s.includes(`section-${String(sectionIdx - 1).padStart(2, "0")}`) ||
|
||||
s.includes(`section-${String(sectionIdx).padStart(2, "0")}`),
|
||||
);
|
||||
|
||||
// Find headings that fall in this section's Y range
|
||||
const sectionHeadings = tokens.headings.filter((h) => {
|
||||
// Match by text overlap with section heading
|
||||
if (section.heading && h.text.includes(section.heading.slice(0, 20))) return true;
|
||||
return false;
|
||||
});
|
||||
|
||||
// Find CTAs in this section's Y range
|
||||
const sectionCtas = tokens.ctas.filter((_c) => {
|
||||
// Basic heuristic: include all CTAs for hero, specific ones for others
|
||||
if (section.type === "hero") return true;
|
||||
return false;
|
||||
});
|
||||
|
||||
// Find paragraphs that might belong to this section
|
||||
const sectionParagraphs = tokens.paragraphs.filter((p) => {
|
||||
if (section.heading && p.includes(section.heading.slice(0, 15))) return true;
|
||||
return false;
|
||||
});
|
||||
|
||||
// Find animations for this section's Y range
|
||||
const nextSection = sorted[sorted.indexOf(section) + 1];
|
||||
const yMax = nextSection ? nextSection.y : section.y + section.height;
|
||||
const sectionAnims = getAnimationsForRange(animations, section.y, yMax);
|
||||
|
||||
brief += `### Section ${sectionIdx}: ${section.heading || section.type} (${section.type})
|
||||
**Screenshot:** \`${screenshotMatch || `screenshots/section-${String(sectionIdx - 1).padStart(2, "0")}.png`}\` — **READ THIS IMAGE**
|
||||
**Background:** ${section.backgroundColor || "#ffffff"}
|
||||
**Y range:** ${section.y}–${yMax}px (${section.height}px tall)
|
||||
|
||||
#### Content
|
||||
`;
|
||||
|
||||
if (section.heading) {
|
||||
brief += `- **Heading:** "${section.heading}"\n`;
|
||||
}
|
||||
|
||||
if (sectionHeadings.length > 0) {
|
||||
for (const h of sectionHeadings) {
|
||||
brief += `- h${h.level}: "${h.text}" — ${h.fontSize} ${h.fontWeight} ${h.color}\n`;
|
||||
}
|
||||
}
|
||||
|
||||
if (sectionParagraphs.length > 0) {
|
||||
for (const p of sectionParagraphs.slice(0, 3)) {
|
||||
brief += `- Text: "${p.slice(0, 120)}${p.length > 120 ? "..." : ""}"\n`;
|
||||
}
|
||||
}
|
||||
|
||||
if (sectionCtas.length > 0) {
|
||||
for (const c of sectionCtas) {
|
||||
brief += `- CTA: "${c.text}"\n`;
|
||||
}
|
||||
}
|
||||
|
||||
brief += `
|
||||
#### Brand
|
||||
- Font: ${tokens.fonts[0] || "Inter"}
|
||||
- Background: \`${section.backgroundColor || "#ffffff"}\`
|
||||
`;
|
||||
|
||||
if (sectionAnims.length > 0) {
|
||||
brief += `
|
||||
#### Animations (from source site)
|
||||
${sectionAnims.map((a) => `- ${a}`).join("\n")}
|
||||
`;
|
||||
}
|
||||
|
||||
brief += `
|
||||
---
|
||||
|
||||
`;
|
||||
}
|
||||
|
||||
// Build a rich suggested prompt with specific animations, transitions, and effects
|
||||
const contentSections = sorted.filter(
|
||||
(s) => s.heading && s.type !== "header" && s.type !== "footer",
|
||||
);
|
||||
const numScenes = Math.min(contentSections.length, 7);
|
||||
const sceneSections = contentSections.slice(0, numScenes);
|
||||
const totalDur = sceneSections.reduce((sum, _, i) => sum + getSceneDuration(i, numScenes), 0);
|
||||
|
||||
// Transition types to cycle through (never repeat)
|
||||
const transitions = [
|
||||
"wipe left-to-right",
|
||||
"circle iris reveal from center",
|
||||
"diagonal wipe top-left to bottom-right",
|
||||
"crossfade over 0.8s",
|
||||
"slide-push from right",
|
||||
"glitch transition with brief RGB split",
|
||||
"zoom-through",
|
||||
];
|
||||
|
||||
// Entrance animations to cycle through (never repeat same one twice)
|
||||
const entrances = [
|
||||
"slides up from bottom with overshoot (back.out easing)",
|
||||
"fades in word-by-word with stagger 0.12s",
|
||||
"scales up from 80% with elastic easing",
|
||||
"types out character-by-character at 20 chars/sec",
|
||||
"drops in from above with bounce easing",
|
||||
"slides in from right with power4.out easing",
|
||||
"reveals via expanding clip-path circle from center",
|
||||
];
|
||||
|
||||
// Mid-scene activity to keep things alive
|
||||
const midActivities = [
|
||||
"Logo bar scrolls horizontally like a marquee",
|
||||
"Cards have subtle float animation (y: -4px, yoyo, repeat)",
|
||||
"Background has very subtle gradient shift",
|
||||
"Numbers counter-animate from 0 to their values",
|
||||
"Testimonial cards pulse with soft glow on hover highlight",
|
||||
"Icons rotate slowly (360deg over 8s)",
|
||||
"Decorative dots drift with parallax motion",
|
||||
];
|
||||
|
||||
brief += `## Suggested Prompt
|
||||
|
||||
Read \`${slugify(tokens.title)}/capture-brief.md\` from top to bottom. Read every screenshot listed in the brief. Then:
|
||||
|
||||
\`\`\`
|
||||
Create a new Hyperframes project called "${slugify(tokens.title)}-promo" in ~/Desktop/CLAUDE\\ TEST/.
|
||||
Use npx hyperframes init, then build a ${totalDur}-second composition.
|
||||
|
||||
`;
|
||||
|
||||
for (let i = 0; i < sceneSections.length; i++) {
|
||||
const s = sceneSections[i];
|
||||
const dur = getSceneDuration(i, numScenes);
|
||||
const bgColor = s.backgroundColor || "#0F172A";
|
||||
const transition = i > 0 ? transitions[(i - 1) % transitions.length] : "";
|
||||
const entrance = entrances[i % entrances.length];
|
||||
const midActivity = midActivities[i % midActivities.length];
|
||||
|
||||
// Find sub-elements to mention based on section type
|
||||
const elements = getSectionElements(s, tokens);
|
||||
|
||||
brief += `Scene ${i + 1} (${dur}s)${transition ? ` [${transition}]` : ""}: `;
|
||||
brief += `${bgColor} background. `;
|
||||
brief += `"${s.heading}" heading ${entrance}. `;
|
||||
|
||||
if (elements.length > 0) {
|
||||
brief += elements.join(". ") + ". ";
|
||||
}
|
||||
|
||||
brief += `${midActivity}. `;
|
||||
|
||||
// Exit for all but last scene
|
||||
if (i < sceneSections.length - 1) {
|
||||
brief += `All elements exit before transition.`;
|
||||
} else {
|
||||
brief += `Hold, then fade to black.`;
|
||||
}
|
||||
|
||||
brief += "\n\n";
|
||||
}
|
||||
|
||||
brief += `Colors: use exact hex values from the capture brief. Font: ${tokens.fonts[0] || "Inter"} (check capture brief for local font files). Reference notion/assets/ for images and SVGs. Then run npx hyperframes lint and npx hyperframes preview.
|
||||
\`\`\`
|
||||
|
||||
### Prompt Tips
|
||||
- **Always specify transition types** between scenes — don't let it default to simple fades
|
||||
- **Use specific animation verbs**: "slides up", "bounces in", "types out", "counter-animates from 0 to X" — not just "appears"
|
||||
- **Stagger everything**: cards, list items, logos — specify "stagger 0.15s" or "stagger 0.2s apart"
|
||||
- **Add mid-scene activity**: without it, scenes feel static. Floating, pulsing, subtle rotation, parallax
|
||||
- **Specify easing**: "elastic easing", "back.out with overshoot", "power4.out" — not just "ease-in"
|
||||
- **Exit animations are 2x faster than entrances**: elements should clear before the transition
|
||||
`;
|
||||
|
||||
return brief;
|
||||
}
|
||||
|
||||
/** Scene duration based on position: hook=5s, middle=6s, close=4s */
|
||||
function getSceneDuration(index: number, total: number): number {
|
||||
if (index === 0) return 5; // hook
|
||||
if (index === total - 1) return 4; // close
|
||||
return index < 3 ? 6 : 5; // features get more time
|
||||
}
|
||||
|
||||
/** Generate element descriptions based on section type and tokens */
|
||||
function getSectionElements(
|
||||
section: { heading: string; type: string; y: number; height: number },
|
||||
tokens: DesignTokens,
|
||||
): string[] {
|
||||
const elements: string[] = [];
|
||||
const type = section.type;
|
||||
const heading = section.heading.toLowerCase();
|
||||
|
||||
// CTAs for hero sections
|
||||
if (type === "hero" || heading.includes("try") || heading.includes("start")) {
|
||||
const ctas = tokens.ctas.slice(0, 2);
|
||||
if (ctas.length > 0) {
|
||||
elements.push(
|
||||
`CTA buttons "${ctas.map((c) => c.text).join('" and "')}" slide up staggered 0.2s, primary pulses with glow`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Logo bar for hero
|
||||
if (type === "hero") {
|
||||
const logoCount = tokens.svgs.filter((s) => s.isLogo).length;
|
||||
if (logoCount > 0) {
|
||||
elements.push(
|
||||
`Logo bar with ${logoCount} company logos fades in staggered at bottom, then scrolls as marquee`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Feature cards
|
||||
if (
|
||||
type === "features" ||
|
||||
heading.includes("feature") ||
|
||||
heading.includes("work") ||
|
||||
heading.includes("assistant")
|
||||
) {
|
||||
elements.push("Feature cards slide in staggered 0.15s from bottom with back.out easing");
|
||||
elements.push("Product screenshots scale in from 95% with subtle shadow animation");
|
||||
}
|
||||
|
||||
// Social proof / testimonials
|
||||
if (heading.includes("trust") || heading.includes("customer") || heading.includes("team")) {
|
||||
elements.push("Testimonial cards fade in staggered with subtle lift (translateY -8px)");
|
||||
elements.push("Company logos appear in a row, staggered 0.1s");
|
||||
}
|
||||
|
||||
// Pricing / productivity
|
||||
if (
|
||||
heading.includes("price") ||
|
||||
heading.includes("productiv") ||
|
||||
heading.includes("save") ||
|
||||
heading.includes("fewer")
|
||||
) {
|
||||
elements.push("Stats counter-animate from 0 to their values in DM Mono Bold");
|
||||
elements.push("Checkmark items slide in staggered with green (#22C55E) check icons");
|
||||
}
|
||||
|
||||
// CTA / try free
|
||||
if (heading.includes("try") || heading.includes("start") || heading.includes("free")) {
|
||||
elements.push("Main CTA button scales up with elastic easing, pulses with blue glow shadow");
|
||||
}
|
||||
|
||||
return elements;
|
||||
}
|
||||
|
||||
function getAnimationsForRange(
|
||||
animations: AnimationCatalog | undefined,
|
||||
yMin: number,
|
||||
yMax: number,
|
||||
): string[] {
|
||||
if (!animations) return [];
|
||||
const results: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
// Web animations with keyframes in this Y range
|
||||
for (const anim of animations.webAnimations) {
|
||||
const rect = anim.targetRect;
|
||||
if (!rect) continue;
|
||||
const top = rect.top ?? -1;
|
||||
if (top >= yMin && top <= yMax) {
|
||||
const kfs = anim.keyframes || [];
|
||||
const props = new Set<string>();
|
||||
for (const kf of kfs) {
|
||||
for (const k of Object.keys(kf)) {
|
||||
if (!["offset", "composite", "easing", "computedOffset"].includes(k)) {
|
||||
props.add(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (props.size === 0) continue;
|
||||
const timing = anim.timing || {};
|
||||
const dur = timing.duration;
|
||||
const ease = timing.easing || "linear";
|
||||
const durStr = typeof dur === "number" ? `${dur}ms` : "scroll-linked";
|
||||
const desc = `${anim.targetSelector?.slice(0, 60) || "element"}: ${[...props].join(", ")} (${durStr}, ${ease})`;
|
||||
if (!seen.has(desc)) {
|
||||
seen.add(desc);
|
||||
results.push(desc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Scroll targets in this range (summarize count)
|
||||
const scrollTargets = (animations.scrollTargets || []).filter(
|
||||
(st) => st.rect?.top >= yMin && st.rect?.top <= yMax,
|
||||
);
|
||||
if (scrollTargets.length > 0) {
|
||||
results.push(
|
||||
`${scrollTargets.length} scroll-triggered elements (IntersectionObserver targets)`,
|
||||
);
|
||||
}
|
||||
|
||||
return results.slice(0, 8); // Cap at 8 most relevant
|
||||
}
|
||||
|
||||
function slugify(text: string): string {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.slice(0, 30);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Purge unused CSS from captured HyperFrames compositions.
|
||||
*
|
||||
* Captured sections carry the source site's entire CSS framework,
|
||||
* but each section only uses a fraction. This strips unused rules
|
||||
* via PurgeCSS (two-pass: selectors first, then variables) to produce
|
||||
* files small enough for AI agents to read and edit.
|
||||
*/
|
||||
|
||||
import { readFileSync, writeFileSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export interface PurgeResult {
|
||||
file: string;
|
||||
originalBytes: number;
|
||||
purgedBytes: number;
|
||||
}
|
||||
|
||||
export async function purgeCompositionCss(
|
||||
compositionsDir: string,
|
||||
onProgress?: (detail: string) => void,
|
||||
): Promise<PurgeResult[]> {
|
||||
let PurgeCSS: typeof import("purgecss").PurgeCSS;
|
||||
try {
|
||||
const mod = await import("purgecss");
|
||||
PurgeCSS = mod.PurgeCSS;
|
||||
} catch {
|
||||
onProgress?.("purgecss not installed, skipping CSS purge");
|
||||
return [];
|
||||
}
|
||||
|
||||
const files = readdirSync(compositionsDir).filter(
|
||||
(f) => f.startsWith("section-") && f.endsWith(".html"),
|
||||
);
|
||||
|
||||
if (files.length === 0) return [];
|
||||
|
||||
const results: PurgeResult[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
const filePath = join(compositionsDir, file);
|
||||
const html = readFileSync(filePath, "utf-8");
|
||||
const originalBytes = Buffer.byteLength(html, "utf-8");
|
||||
|
||||
const styleRegex = /<style[^>]*>([\s\S]*?)<\/style>/gi;
|
||||
let allCss = "";
|
||||
let match;
|
||||
while ((match = styleRegex.exec(html)) !== null) {
|
||||
allCss += match[1] + "\n";
|
||||
}
|
||||
|
||||
if (!allCss.trim()) {
|
||||
results.push({ file, originalBytes, purgedBytes: originalBytes });
|
||||
continue;
|
||||
}
|
||||
|
||||
const htmlContent = html.replace(styleRegex, "");
|
||||
|
||||
// Pass 1: Remove unused selectors, keep all CSS variables
|
||||
const pass1 = await new PurgeCSS().purge({
|
||||
content: [{ raw: htmlContent, extension: "html" }],
|
||||
css: [{ raw: allCss }],
|
||||
variables: false,
|
||||
keyframes: true,
|
||||
fontFace: true,
|
||||
safelist: { greedy: [/^data-/] },
|
||||
});
|
||||
|
||||
const css1 = pass1[0]?.css || "";
|
||||
|
||||
// Pass 2: Purge CSS variables not referenced by surviving rules
|
||||
const pass2 = await new PurgeCSS().purge({
|
||||
content: [{ raw: htmlContent + "\n" + css1, extension: "html" }],
|
||||
css: [{ raw: css1 }],
|
||||
variables: true,
|
||||
keyframes: false,
|
||||
fontFace: false,
|
||||
});
|
||||
|
||||
let purgedCss = pass2[0]?.css || "";
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
purgedCss = purgedCss
|
||||
.replace(/@layer\s+[\w-]+\s*\{\s*\}/g, "")
|
||||
.replace(/@media[^{]*\{\s*\}/g, "")
|
||||
.replace(/@supports[^{]*\{\s*\}/g, "")
|
||||
.replace(/:root\s*\{\s*\}/g, "")
|
||||
.replace(/\n{3,}/g, "\n\n");
|
||||
}
|
||||
|
||||
const firstStyleStart = html.search(/<style[^>]*>/i);
|
||||
const lastStyleEnd = html.lastIndexOf("</style>") + "</style>".length;
|
||||
|
||||
const beforeStyles = html.substring(0, firstStyleStart);
|
||||
const afterStyles = html.substring(lastStyleEnd);
|
||||
|
||||
let purgedHtml = beforeStyles + "<style>\n" + purgedCss + "\n</style>" + afterStyles;
|
||||
|
||||
// Prettify HTML so AI agents can read/navigate individual elements
|
||||
try {
|
||||
const prettier = await import("prettier");
|
||||
purgedHtml = await prettier.format(purgedHtml, {
|
||||
parser: "html",
|
||||
printWidth: 120,
|
||||
tabWidth: 2,
|
||||
htmlWhitespaceSensitivity: "ignore",
|
||||
});
|
||||
} catch {
|
||||
// prettier not installed — still write the purged (unprettified) version
|
||||
}
|
||||
|
||||
const purgedBytes = Buffer.byteLength(purgedHtml, "utf-8");
|
||||
|
||||
writeFileSync(filePath, purgedHtml);
|
||||
|
||||
const reduction = (((originalBytes - purgedBytes) / originalBytes) * 100).toFixed(0);
|
||||
onProgress?.(
|
||||
`Purged ${file} (${(originalBytes / 1024).toFixed(0)} KB -> ${(purgedBytes / 1024).toFixed(0)} KB, -${reduction}%)`,
|
||||
);
|
||||
|
||||
results.push({ file, originalBytes, purgedBytes });
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
/**
|
||||
* AI-powered DESIGN.md generator.
|
||||
*
|
||||
* Feeds captured website data (tokens, animations, screenshots, structure)
|
||||
* to Claude and lets the LLM write a rich, opinionated design system document
|
||||
* — the same way Aura.build / Google Stitch produce DESIGN.md files.
|
||||
*/
|
||||
|
||||
import type { DesignTokens, DownloadedAsset } from "./types.js";
|
||||
import type { AnimationCatalog } from "./animationCataloger.js";
|
||||
import type { CatalogedAsset } from "./assetCataloger.js";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export async function generateDesignMd(
|
||||
url: string,
|
||||
tokens: DesignTokens,
|
||||
animations: AnimationCatalog | undefined,
|
||||
screenshots: string[],
|
||||
assets: DownloadedAsset[],
|
||||
fontPaths: string[],
|
||||
outputDir: string,
|
||||
fullPageScreenshot?: string,
|
||||
catalogedAssets?: CatalogedAsset[],
|
||||
): Promise<string> {
|
||||
const apiKey = process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_API_KEY;
|
||||
|
||||
if (!apiKey) {
|
||||
return generateFallbackDesignMd(
|
||||
url,
|
||||
tokens,
|
||||
animations,
|
||||
assets,
|
||||
fontPaths,
|
||||
screenshots,
|
||||
fullPageScreenshot,
|
||||
);
|
||||
}
|
||||
|
||||
const { default: Anthropic } = await import("@anthropic-ai/sdk");
|
||||
const { join } = await import("node:path");
|
||||
const client = new Anthropic({ apiKey });
|
||||
|
||||
const context = buildContext(
|
||||
url,
|
||||
tokens,
|
||||
animations,
|
||||
assets,
|
||||
fontPaths,
|
||||
screenshots,
|
||||
fullPageScreenshot,
|
||||
);
|
||||
|
||||
// Build message content with screenshots as vision input
|
||||
const contentParts: Array<
|
||||
| {
|
||||
type: "text";
|
||||
text: string;
|
||||
}
|
||||
| {
|
||||
type: "image";
|
||||
source: {
|
||||
type: "base64";
|
||||
media_type: "image/png";
|
||||
data: string;
|
||||
};
|
||||
}
|
||||
> = [];
|
||||
|
||||
// Send the full-page screenshot if available, otherwise first 4 section screenshots
|
||||
const screenshotsToSend = fullPageScreenshot ? [fullPageScreenshot] : screenshots.slice(0, 4);
|
||||
|
||||
for (const screenshotPath of screenshotsToSend) {
|
||||
try {
|
||||
const absPath = join(outputDir, screenshotPath);
|
||||
const imgData = readFileSync(absPath);
|
||||
if (imgData.length > 5 * 1024 * 1024) continue;
|
||||
const base64 = imgData.toString("base64");
|
||||
contentParts.push({
|
||||
type: "image" as const,
|
||||
source: {
|
||||
type: "base64" as const,
|
||||
media_type: "image/png" as const,
|
||||
data: base64,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// Screenshot not readable, skip
|
||||
}
|
||||
}
|
||||
|
||||
contentParts.push({
|
||||
type: "text" as const,
|
||||
text: context,
|
||||
});
|
||||
|
||||
const response = await client.messages.create({
|
||||
model: "claude-sonnet-4-20250514",
|
||||
max_tokens: 4096,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: contentParts,
|
||||
},
|
||||
],
|
||||
system: SYSTEM_PROMPT,
|
||||
});
|
||||
|
||||
// Extract text from response
|
||||
let aiText = "";
|
||||
for (const block of response.content) {
|
||||
if (block.type === "text") {
|
||||
aiText += block.text;
|
||||
}
|
||||
}
|
||||
|
||||
if (!aiText) {
|
||||
return generateFallbackDesignMd(
|
||||
url,
|
||||
tokens,
|
||||
animations,
|
||||
assets,
|
||||
fontPaths,
|
||||
screenshots,
|
||||
fullPageScreenshot,
|
||||
);
|
||||
}
|
||||
|
||||
// Append programmatic Assets section
|
||||
const { formatAssetCatalog } = await import("./assetCataloger.js");
|
||||
const assetsSection =
|
||||
catalogedAssets && catalogedAssets.length > 0
|
||||
? formatAssetCatalog(catalogedAssets)
|
||||
: assets.map((a) => `- **${a.type}**: ${a.localPath}`).join("\n") + "\n";
|
||||
|
||||
return aiText + "\n\n## Assets\n" + assetsSection;
|
||||
}
|
||||
|
||||
// ── System prompt ────────────────────────────────────────────────────────────
|
||||
|
||||
const SYSTEM_PROMPT = `You produce DESIGN.md files from website data. A DESIGN.md encodes a complete visual design system so AI agents can generate on-brand output.
|
||||
|
||||
You will receive:
|
||||
- Screenshots of the website (viewport sections or full-page)
|
||||
- Extracted data: colors, fonts, headings, CTAs, CSS variables, page sections, animations
|
||||
|
||||
You produce ONLY the following sections. The Assets section will be appended programmatically — do NOT generate it.
|
||||
|
||||
# Design System
|
||||
|
||||
## Overview
|
||||
3-4 sentences. Describe the visual identity factually. Look at the screenshots and identify:
|
||||
- Named layout patterns visible (e.g., "Bento grid" if cards are in modular grid, "Logo Wall" if company logos are scrolling)
|
||||
- Brand mascots or character illustrations visible in the screenshots (name them if recognizable)
|
||||
- Color strategy (e.g., "predominantly monochrome with functional color pops")
|
||||
- Typography tone (e.g., "sophisticated yet approachable")
|
||||
Be precise and factual, not poetic.
|
||||
|
||||
## Colors
|
||||
### Brand & Neutral
|
||||
Use standard color naming (Gray 200, Gray 600, Primary Black — not creative names like "Deep Space Navy"). List 5-7 key colors with hex values and their actual UI usage:
|
||||
- **Role Name**: \`#hex\` (Where it's used in the UI)
|
||||
|
||||
### Semantic Palette (Themed Sections)
|
||||
If the site uses color to differentiate product areas or features, list each theme color with what it maps to.
|
||||
|
||||
## Typography
|
||||
List each font family with its design role, available weights, and usage:
|
||||
- **Primary Sans-Serif**: \`FontName\`, \`fallback\`. Weights: 400, 500, 600, 700. Used for headings, body, and UI.
|
||||
- **Serif Accent**: \`FontName\`. Used for blockquotes and editorial headers.
|
||||
- **Monospace**: \`FontName\`. Used for technical callouts.
|
||||
- **Stylized Accent**: \`FontName\`. Used for annotations (if detected).
|
||||
|
||||
Include a Sizing Hierarchy subsection with the actual sizes found in the data.
|
||||
|
||||
## Elevation
|
||||
Describe the depth strategy factually: Does the site use borders, shadows, glassmorphism, or flat color shifts? Reference specific CSS tokens if provided (e.g., border-radius values, shadow values).
|
||||
|
||||
## Components
|
||||
Look at the screenshots and data to identify the actual UI components. Name them specifically (e.g., "Bento Grid" not "Cards", "Pricing Calculator" not "Form", "Logo Wall" not "Images", "Featured Testimonial" not "Quote"). For each component, describe its structure, border-radius, spacing, and any distinctive visual treatment. Reference CSS token names when available.
|
||||
|
||||
## Do's and Don'ts
|
||||
- **Do**: 3-5 rules derived from what the site actually does (reference specific design patterns)
|
||||
- **Don't**: 3-5 rules derived from what the site avoids (reference specific anti-patterns observed)
|
||||
|
||||
RULES:
|
||||
- Be FACTUAL, not creative. Describe what you see, don't invent narratives.
|
||||
- Use the EXACT hex values, font names, and pixel sizes from the data.
|
||||
- Name components by their actual names found in class names or content.
|
||||
- Reference real content (heading text, CTA text, company names in testimonials).
|
||||
- Do NOT include an Assets section — it will be appended programmatically.
|
||||
- Keep it under 2000 words.
|
||||
- Output ONLY the markdown — no preamble, no explanation.`;
|
||||
|
||||
// ── Context builder ──────────────────────────────────────────────────────────
|
||||
|
||||
function buildContext(
|
||||
url: string,
|
||||
tokens: DesignTokens,
|
||||
animations: AnimationCatalog | undefined,
|
||||
assets: DownloadedAsset[],
|
||||
fontPaths: string[],
|
||||
screenshots: string[],
|
||||
fullPageScreenshot?: string,
|
||||
): string {
|
||||
const sections = tokens.sections;
|
||||
|
||||
let ctx = `Generate a DESIGN.md for this website.
|
||||
|
||||
URL: ${url}
|
||||
Title: ${tokens.title}
|
||||
Description: ${tokens.description}
|
||||
|
||||
COLORS (extracted from page):
|
||||
${tokens.colors
|
||||
.slice(0, 15)
|
||||
.map((c) => ` ${c}`)
|
||||
.join("\n")}
|
||||
|
||||
SECTION BACKGROUNDS:
|
||||
${sections.map((s) => ` ${s.type}: ${s.heading || "(no heading)"} — bg: ${s.backgroundColor || "none"}`).join("\n")}
|
||||
|
||||
FONTS (from computed styles):
|
||||
${tokens.fonts.join(", ") || "system fonts"}
|
||||
|
||||
FONT FAMILIES (from @font-face CSS rules — you MUST mention ALL of these in Typography):
|
||||
${
|
||||
[
|
||||
...new Set(
|
||||
fontPaths
|
||||
.map((p) => {
|
||||
const name = p.split("/").pop() || "";
|
||||
return name
|
||||
.replace(
|
||||
/-(Regular|Bold|Medium|SemiBold|Italic|BoldItalic|MediumItalic|SemiBoldItalic|i18n|Light).*$/i,
|
||||
"",
|
||||
)
|
||||
.replace(/\./g, "");
|
||||
})
|
||||
.filter(Boolean),
|
||||
),
|
||||
].join(", ") || "none"
|
||||
}
|
||||
NOTE: "permanent-marker" = "Permanent Marker" (handwritten/annotation font). Include it as a Stylized Accent font.
|
||||
|
||||
FONT FILES (local):
|
||||
${fontPaths.length > 0 ? fontPaths.join("\n") : "none"}
|
||||
|
||||
HEADINGS:
|
||||
${tokens.headings.map((h) => ` h${h.level}: "${h.text}" — ${h.fontSize} ${h.fontWeight} ${h.color}`).join("\n")}
|
||||
|
||||
CTAs:
|
||||
${tokens.ctas.map((c) => ` "${c.text}"${c.href ? ` → ${c.href}` : ""}`).join("\n")}
|
||||
|
||||
PAGE SECTIONS (${sections.length} total):
|
||||
${sections.map((s, i) => ` ${i + 1}. [${s.type}] "${s.heading}" at y=${s.y} (${s.height}px) — bg: ${s.backgroundColor || "none"}`).join("\n")}
|
||||
|
||||
CSS CUSTOM PROPERTIES (${Object.keys(tokens.cssVariables).length} total — showing all color/font/spacing/radius/shadow tokens):
|
||||
${Object.entries(tokens.cssVariables)
|
||||
.filter(([k]) => /color|font|spacing|radius|shadow|border|gap|padding|margin|size/i.test(k))
|
||||
.slice(0, 100)
|
||||
.map(([k, v]) => ` ${k}: ${v}`)
|
||||
.join("\n")}
|
||||
`;
|
||||
|
||||
// Animation data
|
||||
if (animations?.summary) {
|
||||
ctx += `
|
||||
ANIMATIONS:
|
||||
Web Animations: ${animations.summary.webAnimations}
|
||||
CSS Declarations: ${animations.summary.cssDeclarations}
|
||||
Scroll Targets: ${animations.summary.scrollTargets}
|
||||
CDP Animations: ${animations.summary.cdpAnimations}
|
||||
Canvases: ${animations.summary.canvases}
|
||||
`;
|
||||
}
|
||||
|
||||
if (animations?.webAnimations && animations.webAnimations.length > 0) {
|
||||
const sample = animations.webAnimations.slice(0, 5);
|
||||
ctx += `\nSAMPLE WEB ANIMATIONS:\n`;
|
||||
sample.forEach((a) => {
|
||||
const easing = a.timing?.easing || "?";
|
||||
const duration = a.timing?.duration || "?";
|
||||
ctx += ` ${a.targetSelector || "element"}: easing=${easing}, duration=${duration}ms\n`;
|
||||
});
|
||||
}
|
||||
|
||||
// Assets
|
||||
ctx += `\nASSETS:\n`;
|
||||
assets.forEach((a) => {
|
||||
ctx += ` ${a.localPath} (${a.type})\n`;
|
||||
});
|
||||
|
||||
// Screenshots
|
||||
if (fullPageScreenshot) {
|
||||
ctx += `\nFULL-PAGE SCREENSHOT: ${fullPageScreenshot} (attached as image above — USE THIS as your primary visual reference)\n`;
|
||||
}
|
||||
if (screenshots.length > 0) {
|
||||
ctx += `\nSECTION SCREENSHOTS:\n`;
|
||||
screenshots.forEach((s) => (ctx += ` ${s}\n`));
|
||||
}
|
||||
|
||||
// Paragraphs (sample)
|
||||
if (tokens.paragraphs.length > 0) {
|
||||
ctx += `\nSAMPLE PARAGRAPHS:\n`;
|
||||
tokens.paragraphs.slice(0, 5).forEach((p) => {
|
||||
ctx += ` "${p.slice(0, 150)}"\n`;
|
||||
});
|
||||
}
|
||||
|
||||
// Distinctive CSS class name patterns (helps identify named components)
|
||||
// Extract from CSS variable names that hint at component architecture
|
||||
const allVarNames = Object.keys(tokens.cssVariables);
|
||||
const componentHints = allVarNames
|
||||
.filter((k) => /--([\w]+-[\w]+)/.test(k))
|
||||
.map((k) => k.replace(/^--/, "").split("-").slice(0, 2).join("-"))
|
||||
.filter((v, i, a) => a.indexOf(v) === i)
|
||||
.slice(0, 30);
|
||||
if (componentHints.length > 0) {
|
||||
ctx += `\nCSS DESIGN TOKEN PREFIXES (hint at component naming):\n ${componentHints.join(", ")}\n`;
|
||||
}
|
||||
|
||||
// SVG labels (often reveal brand characters and icons)
|
||||
if (tokens.svgs.length > 0) {
|
||||
const svgLabels = tokens.svgs
|
||||
.filter((s) => s.label)
|
||||
.map((s) => s.label)
|
||||
.slice(0, 10);
|
||||
if (svgLabels.length > 0) {
|
||||
ctx += `\nSVG LABELS (icons and brand elements):\n ${svgLabels.join(", ")}\n`;
|
||||
}
|
||||
}
|
||||
|
||||
return ctx;
|
||||
}
|
||||
|
||||
// ── Fallback (no API key) ────────────────────────────────────────────────────
|
||||
|
||||
function generateFallbackDesignMd(
|
||||
url: string,
|
||||
tokens: DesignTokens,
|
||||
_animations: AnimationCatalog | undefined,
|
||||
assets: DownloadedAsset[],
|
||||
fontPaths: string[],
|
||||
screenshots: string[],
|
||||
fullPageScreenshot?: string,
|
||||
): string {
|
||||
const hostname = new URL(url).hostname.replace(/^www\./, "");
|
||||
const sections = tokens.sections.filter((s) => s.heading);
|
||||
|
||||
return `# Design System
|
||||
|
||||
## Overview
|
||||
Design system extracted from ${tokens.title} (${hostname}). Set ANTHROPIC_API_KEY to generate a rich, AI-written design system analysis.
|
||||
|
||||
${tokens.description}
|
||||
|
||||
## Colors
|
||||
${tokens.colors
|
||||
.slice(0, 10)
|
||||
.map((c, i) => `- **Color ${i}**: \`${c}\``)
|
||||
.join("\n")}
|
||||
|
||||
## Typography
|
||||
${tokens.fonts.map((f, i) => `- **${f}** — ${i === 0 ? "Primary" : "Secondary"} font`).join("\n")}
|
||||
|
||||
### Hierarchy
|
||||
${tokens.headings
|
||||
.slice(0, 6)
|
||||
.map((h) => `- h${h.level}: ${h.fontSize}/${h.fontWeight} — "${h.text.slice(0, 50)}"`)
|
||||
.join("\n")}
|
||||
|
||||
${fontPaths.length > 0 ? `### Local Font Files\n${fontPaths.map((p) => `- \`${p}\``).join("\n")}` : ""}
|
||||
|
||||
## Assets
|
||||
${fullPageScreenshot ? `### Full-Page Screenshot\n- \`${fullPageScreenshot}\`\n` : ""}
|
||||
### Section Screenshots
|
||||
${screenshots.map((s) => `- \`${s}\``).join("\n")}
|
||||
|
||||
### Downloaded
|
||||
${assets.map((a) => `- \`${a.localPath}\` (${a.type})`).join("\n")}
|
||||
|
||||
## HyperFrames-Specific
|
||||
### Composition Templates
|
||||
- **15s Social Ad**: ${sections
|
||||
.slice(0, 4)
|
||||
.map((s) => s.heading.slice(0, 25) || s.type)
|
||||
.join(" → ")}
|
||||
- **Full Showcase (${sections.length * 5}s)**: All ${sections.length} sections × 5s each
|
||||
|
||||
---
|
||||
*Set ANTHROPIC_API_KEY environment variable to generate a full AI-written design system analysis.*
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Extract full-page HTML from a website using Puppeteer CDP.
|
||||
*
|
||||
* All page.evaluate() calls use string expressions to avoid
|
||||
* tsx/esbuild __name injection (see esbuild issue #1031).
|
||||
*/
|
||||
|
||||
import type { Page } from "puppeteer-core";
|
||||
import type { ExtractedHtml } from "./types.js";
|
||||
|
||||
const DEFAULT_SETTLE_TIME = 3000;
|
||||
|
||||
export async function extractHtml(
|
||||
page: Page,
|
||||
opts: { settleTime?: number } = {},
|
||||
): Promise<ExtractedHtml> {
|
||||
const settleTime = opts.settleTime ?? DEFAULT_SETTLE_TIME;
|
||||
|
||||
// Step 1: Trigger lazy loading by scrolling through the page
|
||||
// Also snapshot canvases AT EACH SCROLL POSITION (before they get GC'd)
|
||||
await page.evaluate(`(async () => {
|
||||
var snapshotted = new Set();
|
||||
var pageHeight = document.body.scrollHeight;
|
||||
var viewportH = window.innerHeight;
|
||||
var step = Math.floor(viewportH * 0.7);
|
||||
for (var y = 0; y < pageHeight + viewportH; y += step) {
|
||||
window.scrollTo(0, y);
|
||||
await new Promise(function(r) { setTimeout(r, 200); });
|
||||
// Snapshot any visible canvases at this scroll position
|
||||
document.querySelectorAll("canvas").forEach(function(canvas) {
|
||||
if (snapshotted.has(canvas)) return;
|
||||
try {
|
||||
if (canvas.width < 50 || canvas.height < 50) return;
|
||||
if (!canvas.offsetWidth || !canvas.offsetHeight) return;
|
||||
var dataUrl = canvas.toDataURL("image/jpeg", 0.85);
|
||||
if (dataUrl.length < 1000) return;
|
||||
var img = document.createElement("img");
|
||||
img.src = dataUrl;
|
||||
img.width = canvas.width;
|
||||
img.height = canvas.height;
|
||||
img.style.cssText = canvas.style.cssText;
|
||||
img.className = canvas.className;
|
||||
if (canvas.getAttribute("aria-hidden")) img.setAttribute("aria-hidden", "true");
|
||||
canvas.parentNode.replaceChild(img, canvas);
|
||||
snapshotted.add(canvas);
|
||||
} catch(e) {}
|
||||
});
|
||||
}
|
||||
window.scrollTo(0, pageHeight);
|
||||
await new Promise(function(r) { setTimeout(r, 300); });
|
||||
window.scrollTo(0, 0);
|
||||
await new Promise(function(r) { setTimeout(r, 300); });
|
||||
})()`);
|
||||
|
||||
// Re-measure after lazy load
|
||||
await new Promise((r) => setTimeout(r, settleTime));
|
||||
|
||||
// Step 2: Inline external stylesheets
|
||||
// Fetch CSS from Node.js (bypasses CORS) then inject into page
|
||||
const stylesheetUrls = (await page.evaluate(`(() => {
|
||||
return Array.from(document.querySelectorAll('link[rel="stylesheet"][href]')).map(function(l) { return l.href; });
|
||||
})()`)) as string[];
|
||||
|
||||
for (const href of stylesheetUrls) {
|
||||
try {
|
||||
const res = await fetch(href, {
|
||||
signal: AbortSignal.timeout(10000),
|
||||
headers: { "User-Agent": "Mozilla/5.0" },
|
||||
});
|
||||
if (!res.ok) continue;
|
||||
let css = await res.text();
|
||||
// Fix relative url() references
|
||||
css = css.replace(/url\(\s*['"]?([^'")\s]+)['"]?\s*\)/g, (match: string, url: string) => {
|
||||
if (url.startsWith("data:") || url.startsWith("http") || url.startsWith("//")) return match;
|
||||
try {
|
||||
return `url('${new URL(url, href).href}')`;
|
||||
} catch {
|
||||
return match;
|
||||
}
|
||||
});
|
||||
// Add the CSS as a <style> tag in <head> via Puppeteer's addStyleTag
|
||||
await page.addStyleTag({ content: css });
|
||||
// Remove the original <link> tag
|
||||
await page.evaluate(`(() => {
|
||||
var links = document.querySelectorAll('link[rel="stylesheet"]');
|
||||
for (var i = 0; i < links.length; i++) {
|
||||
if (links[i].href === "${href}") { links[i].remove(); break; }
|
||||
}
|
||||
})()`);
|
||||
} catch {
|
||||
/* network error — skip */
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3: Make URLs absolute and fix HTML entity encoding in src attributes
|
||||
await page.evaluate(`(() => {
|
||||
document.querySelectorAll("img[src]").forEach(function(el) {
|
||||
try {
|
||||
// getAttribute returns the raw HTML attribute (with &)
|
||||
// .src returns the resolved URL (with &) — use .src for the correct value
|
||||
var resolved = el.src;
|
||||
if (resolved) el.setAttribute("src", resolved);
|
||||
} catch(e) {}
|
||||
});
|
||||
// Fix srcset attributes too (Next.js image optimization)
|
||||
document.querySelectorAll("img[srcset]").forEach(function(el) {
|
||||
try {
|
||||
var srcset = el.getAttribute("srcset") || "";
|
||||
// Decode & entities in srcset
|
||||
srcset = srcset.replace(/&/g, "&");
|
||||
el.setAttribute("srcset", srcset);
|
||||
} catch(e) {}
|
||||
});
|
||||
document.querySelectorAll('[style*="url("]').forEach(function(el) {
|
||||
el.style.cssText = el.style.cssText.replace(/url\\(['"]?([^'"\\)\\s]+)['"]?\\)/g, function(_, url) {
|
||||
try { return "url('" + new URL(url, location.href).href + "')"; } catch(e) { return "url('" + url + "')"; }
|
||||
});
|
||||
});
|
||||
})()`);
|
||||
|
||||
// Step 3b: Convert cross-origin images to data URLs
|
||||
// Some CDNs (Contentful, etc.) block direct access but images are already
|
||||
// loaded in the browser. We convert loaded images to data URLs via canvas.
|
||||
await page.evaluate(`(async () => {
|
||||
var imgs = Array.from(document.querySelectorAll("img"));
|
||||
for (var i = 0; i < imgs.length; i++) {
|
||||
var img = imgs[i];
|
||||
try {
|
||||
if (!img.src || img.src.startsWith("data:")) continue;
|
||||
if (img.naturalWidth < 10 || img.naturalHeight < 10) continue;
|
||||
// Only convert cross-origin images (same-origin ones will load fine)
|
||||
var imgUrl = new URL(img.src);
|
||||
if (imgUrl.origin === location.origin) continue;
|
||||
// Try to draw to canvas — will fail if CORS blocks it
|
||||
var canvas = document.createElement("canvas");
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
var ctx = canvas.getContext("2d");
|
||||
ctx.drawImage(img, 0, 0);
|
||||
var dataUrl = canvas.toDataURL("image/png");
|
||||
if (dataUrl.length > 100) {
|
||||
img.setAttribute("src", dataUrl);
|
||||
img.removeAttribute("srcset");
|
||||
}
|
||||
} catch(e) {
|
||||
// Canvas CORS failed — try fetch + blob as fallback
|
||||
try {
|
||||
var resp = await fetch(img.src, { mode: "cors" });
|
||||
if (resp.ok) {
|
||||
var blob = await resp.blob();
|
||||
var reader = new FileReader();
|
||||
var dataUrl2 = await new Promise(function(resolve) {
|
||||
reader.onloadend = function() { resolve(reader.result); };
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
if (dataUrl2 && typeof dataUrl2 === "string" && dataUrl2.length > 100) {
|
||||
img.setAttribute("src", dataUrl2);
|
||||
img.removeAttribute("srcset");
|
||||
}
|
||||
}
|
||||
} catch(e2) {
|
||||
// Both methods failed — image stays as original URL
|
||||
}
|
||||
}
|
||||
}
|
||||
})()`);
|
||||
|
||||
// Step 4: Canvas elements are handled by the orchestrator using Puppeteer
|
||||
// element screenshots (page.$$('canvas') → handle.screenshot()) which is
|
||||
// more reliable than in-page toDataURL because React re-renders overwrite
|
||||
// DOM replacements.
|
||||
|
||||
// Note: Canvas snapshot via toDataURL is unreliable because React re-renders
|
||||
// overwrite in-page replacements. The Puppeteer element screenshots above
|
||||
// are saved as canvas-*.png files and referenced in capture-summary.md.
|
||||
|
||||
// Step 5: Extract everything
|
||||
const result = (await page.evaluate(`(() => {
|
||||
// Capture styles AND scripts from head separately then combine
|
||||
// Scripts include Three.js, animation libraries that we want to preserve
|
||||
var styles = Array.from(document.head.querySelectorAll("style")).map(function(s) { return s.outerHTML; }).join("\\n");
|
||||
var scripts = Array.from(document.head.querySelectorAll("script")).map(function(s) { return s.outerHTML; }).join("\\n");
|
||||
var headHtml = styles + "\\n" + scripts;
|
||||
var bodyHtml = document.body.innerHTML;
|
||||
|
||||
var cssomRules = [];
|
||||
for (var i = 0; i < document.styleSheets.length; i++) {
|
||||
var sheet = document.styleSheets[i];
|
||||
try {
|
||||
var ownerNode = sheet.ownerNode;
|
||||
if (ownerNode && ownerNode.textContent && ownerNode.textContent.trim()) continue;
|
||||
if (sheet.href) continue;
|
||||
for (var j = 0; j < sheet.cssRules.length; j++) {
|
||||
cssomRules.push(sheet.cssRules[j].cssText);
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
|
||||
var htmlEl = document.documentElement;
|
||||
var attrParts = [];
|
||||
for (var i = 0; i < htmlEl.attributes.length; i++) {
|
||||
var attr = htmlEl.attributes[i];
|
||||
if (attr.name === "lang" || attr.name === "class" || attr.name === "style" || attr.name === "dir" || attr.name.startsWith("data-")) {
|
||||
attrParts.push(attr.name + '="' + attr.value.replace(/"/g, """) + '"');
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
headHtml: headHtml,
|
||||
bodyHtml: bodyHtml,
|
||||
cssomRules: cssomRules.join("\\n"),
|
||||
htmlAttrs: attrParts.join(" "),
|
||||
viewportWidth: Math.max(window.innerWidth, document.documentElement.scrollWidth),
|
||||
viewportHeight: window.innerHeight,
|
||||
fullPageHeight: document.body.scrollHeight
|
||||
};
|
||||
})()`)) as ExtractedHtml;
|
||||
|
||||
// Post-process in Node.js (more reliable than browser-side fixing):
|
||||
// 1. Decode & in image src/srcset attributes
|
||||
// 2. Make relative image URLs absolute using the page's origin
|
||||
const pageOrigin = new URL(page.url()).origin;
|
||||
|
||||
result.bodyHtml = result.bodyHtml.replace(
|
||||
/(<img\b[^>]*\bsrc=")([^"]*?)(")/g,
|
||||
(_match: string, pre: string, url: string, post: string) => {
|
||||
let fixed = url.replace(/&/g, "&");
|
||||
// Make relative URLs absolute
|
||||
if (fixed.startsWith("/") && !fixed.startsWith("//")) {
|
||||
fixed = pageOrigin + fixed;
|
||||
}
|
||||
return pre + fixed + post;
|
||||
},
|
||||
);
|
||||
result.bodyHtml = result.bodyHtml.replace(
|
||||
/(<img\b[^>]*\bsrcset=")([^"]*?)(")/g,
|
||||
(_match: string, pre: string, urls: string, post: string) => {
|
||||
const fixed = urls
|
||||
.replace(/&/g, "&")
|
||||
.replace(
|
||||
/(^|,\s*)(\/[^\s,]+)/g,
|
||||
(_m: string, sep: string, path: string) => sep + pageOrigin + path,
|
||||
);
|
||||
return pre + fixed + post;
|
||||
},
|
||||
);
|
||||
|
||||
// Also fix video src/poster URLs
|
||||
result.bodyHtml = result.bodyHtml.replace(
|
||||
/(<video\b[^>]*\bsrc=")([^"]*?)(")/g,
|
||||
(_match: string, pre: string, url: string, post: string) => {
|
||||
let fixed = url.replace(/&/g, "&");
|
||||
if (fixed.startsWith("/") && !fixed.startsWith("//")) fixed = pageOrigin + fixed;
|
||||
return pre + fixed + post;
|
||||
},
|
||||
);
|
||||
result.bodyHtml = result.bodyHtml.replace(
|
||||
/(<video\b[^>]*\bposter=")([^"]*?)(")/g,
|
||||
(_match: string, pre: string, url: string, post: string) => {
|
||||
let fixed = url.replace(/&/g, "&");
|
||||
if (fixed.startsWith("/") && !fixed.startsWith("//")) fixed = pageOrigin + fixed;
|
||||
return pre + fixed + post;
|
||||
},
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
/**
|
||||
* Website capture orchestrator.
|
||||
*
|
||||
* Two-pass capture approach:
|
||||
* Pass 1: Full page load (all JS) → catalog animations + snapshot canvases
|
||||
* Pass 2: Framework scripts blocked → extract stable HTML/CSS
|
||||
*
|
||||
* This ensures we get both:
|
||||
* - Rich animation metadata for Claude Code to recreate
|
||||
* - Stable, renderable HTML that won't crash in Puppeteer
|
||||
*/
|
||||
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { extractHtml } from "./htmlExtractor.js";
|
||||
// captureScreenshots removed — full-page screenshot replaces per-section shots
|
||||
import { extractTokens } from "./tokenExtractor.js";
|
||||
import { downloadAssets, downloadAndRewriteFonts } from "./assetDownloader.js";
|
||||
import { generateCaptureBrief } from "./briefGenerator.js";
|
||||
import {
|
||||
setupAnimationCapture,
|
||||
startCdpAnimationCapture,
|
||||
collectAnimationCatalog,
|
||||
} from "./animationCataloger.js";
|
||||
import type { CaptureOptions, CaptureResult } from "./types.js";
|
||||
|
||||
export type { CaptureOptions, CaptureResult } from "./types.js";
|
||||
|
||||
export async function captureWebsite(
|
||||
opts: CaptureOptions,
|
||||
onProgress?: (stage: string, detail?: string) => void,
|
||||
): Promise<CaptureResult> {
|
||||
const {
|
||||
url,
|
||||
outputDir,
|
||||
viewportWidth = 1920,
|
||||
viewportHeight = 1080,
|
||||
timeout = 30000,
|
||||
settleTime = 3000,
|
||||
maxScreenshots: _maxScreenshots = 24,
|
||||
skipAssets = false,
|
||||
} = opts;
|
||||
|
||||
const warnings: string[] = [];
|
||||
const progress = (stage: string, detail?: string) => {
|
||||
onProgress?.(stage, detail);
|
||||
};
|
||||
|
||||
// Create output directories
|
||||
mkdirSync(join(outputDir, "extracted"), { recursive: true });
|
||||
mkdirSync(join(outputDir, "screenshots"), { recursive: true });
|
||||
mkdirSync(join(outputDir, "assets"), { recursive: true });
|
||||
mkdirSync(join(outputDir, "compositions"), { recursive: true });
|
||||
|
||||
// Launch browser
|
||||
progress("browser", "Launching headless Chrome...");
|
||||
const { ensureBrowser } = await import("../browser/manager.js");
|
||||
const browser = await ensureBrowser();
|
||||
const puppeteer = await import("puppeteer-core");
|
||||
const chromeBrowser = await puppeteer.default.launch({
|
||||
headless: true,
|
||||
executablePath: browser.executablePath,
|
||||
args: [
|
||||
"--no-sandbox",
|
||||
"--disable-dev-shm-usage",
|
||||
"--enable-webgl",
|
||||
"--ignore-gpu-blocklist",
|
||||
"--use-gl=angle",
|
||||
"--use-angle=swiftshader",
|
||||
"--disable-blink-features=AutomationControlled",
|
||||
"--disable-background-timer-throttling",
|
||||
"--disable-renderer-backgrounding",
|
||||
`--window-size=${viewportWidth},${viewportHeight}`,
|
||||
],
|
||||
});
|
||||
|
||||
let animationCatalog: CaptureResult["animationCatalog"];
|
||||
|
||||
try {
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// PASS 1: Full page load — all JS runs
|
||||
// Goal: Catalog animations + take screenshots (with JS rendering)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
progress("animations", "Cataloging animations (full JS)...");
|
||||
|
||||
const page1 = await chromeBrowser.newPage();
|
||||
await page1.setViewport({ width: viewportWidth, height: viewportHeight });
|
||||
await page1.setUserAgent(
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
||||
);
|
||||
|
||||
// Set up hooks BEFORE navigation
|
||||
await setupAnimationCapture(page1);
|
||||
const { cdp, animations: cdpAnims } = await startCdpAnimationCapture(page1);
|
||||
|
||||
// Patch WebGL to preserve drawing buffer — allows canvas.toDataURL() later
|
||||
await page1.evaluateOnNewDocument(`
|
||||
var origGetContext = HTMLCanvasElement.prototype.getContext;
|
||||
HTMLCanvasElement.prototype.getContext = function(type, attrs) {
|
||||
if (type === 'webgl' || type === 'webgl2' || type === 'experimental-webgl') {
|
||||
attrs = Object.assign({}, attrs || {}, { preserveDrawingBuffer: true });
|
||||
}
|
||||
return origGetContext.call(this, type, attrs);
|
||||
};
|
||||
`);
|
||||
|
||||
await page1.goto(url, { waitUntil: "networkidle0", timeout });
|
||||
await new Promise((r) => setTimeout(r, settleTime));
|
||||
|
||||
// Screenshot canvas elements using CDP captureScreenshot with clip
|
||||
// This captures from the compositor surface (includes WebGL content)
|
||||
// Must scroll each canvas into view, wait for Three.js render, then clip-capture
|
||||
let canvasCount = 0;
|
||||
const cdpCapture = await page1.createCDPSession();
|
||||
|
||||
// First, scroll through to trigger lazy-loaded canvases
|
||||
await page1.evaluate(`(async () => {
|
||||
var h = document.body.scrollHeight;
|
||||
for (var y = 0; y < h; y += window.innerHeight * 0.7) {
|
||||
window.scrollTo(0, y);
|
||||
await new Promise(function(r) { setTimeout(r, 300); });
|
||||
}
|
||||
window.scrollTo(0, 0);
|
||||
await new Promise(function(r) { setTimeout(r, 500); });
|
||||
})()`);
|
||||
|
||||
// Now capture each canvas
|
||||
const canvasEls = await page1.$$("canvas");
|
||||
for (const handle of canvasEls) {
|
||||
try {
|
||||
const box = await handle.boundingBox();
|
||||
if (!box || box.width < 50 || box.height < 50) continue;
|
||||
|
||||
// Scroll canvas into view and wait for render
|
||||
await handle.evaluate(`((el) => el.scrollIntoView({ block: "center" }))`);
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
|
||||
// Get updated bounding box after scroll
|
||||
const box2 = await handle.boundingBox();
|
||||
if (!box2) continue;
|
||||
|
||||
// CDP screenshot with clip — captures WebGL compositor surface
|
||||
const result = await cdpCapture.send("Page.captureScreenshot", {
|
||||
format: "png",
|
||||
fromSurface: true,
|
||||
clip: {
|
||||
x: box2.x,
|
||||
y: box2.y,
|
||||
width: box2.width,
|
||||
height: box2.height,
|
||||
scale: 1,
|
||||
},
|
||||
});
|
||||
const buffer = Buffer.from(result.data, "base64");
|
||||
if (buffer.length > 1000) {
|
||||
const filename = `canvas-${canvasCount}.png`;
|
||||
writeFileSync(join(outputDir, "assets", filename), buffer);
|
||||
canvasCount++;
|
||||
}
|
||||
} catch {
|
||||
/* not visible or capture failed */
|
||||
}
|
||||
}
|
||||
|
||||
await cdpCapture.detach();
|
||||
await page1.evaluate(`window.scrollTo(0, 0)`);
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
if (canvasCount > 0) {
|
||||
progress("canvas", `${canvasCount} canvas screenshots saved`);
|
||||
}
|
||||
|
||||
// Extract HTML + CSS (this scrolls the page for lazy loading)
|
||||
progress("extract", "Extracting HTML & CSS...");
|
||||
const extracted = await extractHtml(page1, { settleTime: 1000 });
|
||||
|
||||
// Extract design tokens
|
||||
progress("tokens", "Extracting design tokens...");
|
||||
const tokens = await extractTokens(page1);
|
||||
writeFileSync(
|
||||
join(outputDir, "extracted", "tokens.json"),
|
||||
JSON.stringify(tokens, null, 2),
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
// Collect animation catalog (scrolls through page — must be after HTML extraction)
|
||||
progress("animations", "Cataloging animations...");
|
||||
animationCatalog = await collectAnimationCatalog(page1, cdpAnims, cdp);
|
||||
|
||||
// Capture full-page screenshot (scrolls to trigger lazy loading, neutralizes sticky elements)
|
||||
progress("screenshots", "Capturing full-page screenshot...");
|
||||
const { captureFullPageScreenshot } = await import("./screenshotCapture.js");
|
||||
const fullPageScreenshot = await captureFullPageScreenshot(page1, outputDir);
|
||||
const screenshots: string[] = [];
|
||||
if (fullPageScreenshot) {
|
||||
screenshots.push(fullPageScreenshot);
|
||||
}
|
||||
|
||||
// Strip framework scripts from the extracted body — keep visual library scripts
|
||||
// IMPORTANT: Use non-greedy matching within individual script tags only
|
||||
extracted.bodyHtml = extracted.bodyHtml
|
||||
// Remove __NEXT_DATA__ (has its own ID so safe to target)
|
||||
.replace(/<script\s+id="__NEXT_DATA__"[^>]*>[\s\S]*?<\/script>/gi, "")
|
||||
// Remove React hydration markers
|
||||
.replace(/\s*data-reactroot="[^"]*"/g, "")
|
||||
.replace(/\s*data-reactroot/g, "");
|
||||
|
||||
// Remove Next.js bootstrap scripts individually (match each script tag separately)
|
||||
extracted.bodyHtml = extracted.bodyHtml.replace(
|
||||
/<script\b[^>]*>([\s\S]*?)<\/script>/gi,
|
||||
(match: string, content: string) => {
|
||||
// Only remove if this specific script contains Next.js bootstrap code
|
||||
if (
|
||||
content.includes("__next_f") ||
|
||||
content.includes("self.__next_f") ||
|
||||
content.includes("__NEXT_LOADED_PAGES__") ||
|
||||
content.includes("_N_E") ||
|
||||
content.includes("__NEXT_P")
|
||||
) {
|
||||
return "";
|
||||
}
|
||||
return match;
|
||||
},
|
||||
);
|
||||
|
||||
// Strip framework script tags from head (keep styles + visual library scripts)
|
||||
const FRAMEWORK_SRC_PATTERNS = [
|
||||
/_next\/static\/chunks\/(main|framework|webpack|pages\/)/,
|
||||
/_next\/static\/chunks\/app\//,
|
||||
/_buildManifest\.js/,
|
||||
/_ssgManifest\.js/,
|
||||
];
|
||||
extracted.headHtml = extracted.headHtml.replace(
|
||||
/<script[^>]*src="([^"]*)"[^>]*><\/script>/gi,
|
||||
(match: string, src: string) => {
|
||||
if (FRAMEWORK_SRC_PATTERNS.some((p) => p.test(src))) return "";
|
||||
return match;
|
||||
},
|
||||
);
|
||||
|
||||
// Catalog all assets with HTML contexts (before closing page)
|
||||
progress("design", "Cataloging assets...");
|
||||
let catalogedAssets: import("./assetCataloger.js").CatalogedAsset[] = [];
|
||||
try {
|
||||
const { catalogAssets } = await import("./assetCataloger.js");
|
||||
catalogedAssets = await catalogAssets(page1);
|
||||
progress("design", `${catalogedAssets.length} assets cataloged`);
|
||||
} catch (err) {
|
||||
warnings.push(`Asset cataloging failed: ${err}`);
|
||||
}
|
||||
|
||||
await page1.close();
|
||||
|
||||
// Download fonts and rewrite URLs to local paths
|
||||
extracted.headHtml = await downloadAndRewriteFonts(extracted.headHtml, outputDir);
|
||||
|
||||
// Save extracted data
|
||||
writeFileSync(join(outputDir, "extracted", "full-head.html"), extracted.headHtml, "utf-8");
|
||||
writeFileSync(join(outputDir, "extracted", "full-body.html"), extracted.bodyHtml, "utf-8");
|
||||
writeFileSync(join(outputDir, "extracted", "cssom.css"), extracted.cssomRules, "utf-8");
|
||||
|
||||
// Save animation catalog
|
||||
writeFileSync(
|
||||
join(outputDir, "extracted", "animations.json"),
|
||||
JSON.stringify(animationCatalog, null, 2),
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
// Download assets
|
||||
let assets: CaptureResult["assets"] = [];
|
||||
if (!skipAssets) {
|
||||
progress("assets", "Downloading assets...");
|
||||
assets = await downloadAssets(tokens, outputDir);
|
||||
}
|
||||
|
||||
// Generate visual-style.md
|
||||
progress("style", "Generating visual style...");
|
||||
const visualStyle = generateVisualStyle(tokens, url);
|
||||
writeFileSync(join(outputDir, "visual-style.md"), visualStyle, "utf-8");
|
||||
|
||||
// Generate capture-summary.md
|
||||
const summary = generateCaptureSummary(
|
||||
url,
|
||||
tokens,
|
||||
screenshots,
|
||||
assets,
|
||||
extracted,
|
||||
animationCatalog,
|
||||
);
|
||||
writeFileSync(join(outputDir, "capture-summary.md"), summary, "utf-8");
|
||||
|
||||
// Generate capture-brief.md (prompt-ready design brief for AI)
|
||||
progress("brief", "Generating design brief...");
|
||||
// Collect font file paths from assets/fonts/ (already downloaded by downloadAndRewriteFonts)
|
||||
const fontsDir = join(outputDir, "assets", "fonts");
|
||||
let fontPaths: string[] = [];
|
||||
try {
|
||||
const { readdirSync } = await import("node:fs");
|
||||
fontPaths = readdirSync(fontsDir)
|
||||
.filter((f: string) => /\.(woff2?|ttf|otf)$/i.test(f))
|
||||
.map((f: string) => `assets/fonts/${f}`);
|
||||
} catch {
|
||||
/* no fonts dir */
|
||||
}
|
||||
const brief = generateCaptureBrief(
|
||||
url,
|
||||
tokens,
|
||||
animationCatalog,
|
||||
screenshots,
|
||||
assets,
|
||||
fontPaths,
|
||||
);
|
||||
writeFileSync(join(outputDir, "capture-brief.md"), brief, "utf-8");
|
||||
|
||||
// Generate DESIGN.md (AI-powered if ANTHROPIC_API_KEY is set)
|
||||
progress("design", "Generating DESIGN.md...");
|
||||
try {
|
||||
const { generateDesignMd } = await import("./designMdGenerator.js");
|
||||
const designMd = await generateDesignMd(
|
||||
url,
|
||||
tokens,
|
||||
animationCatalog,
|
||||
screenshots,
|
||||
assets,
|
||||
fontPaths,
|
||||
outputDir,
|
||||
fullPageScreenshot,
|
||||
catalogedAssets,
|
||||
);
|
||||
writeFileSync(join(outputDir, "DESIGN.md"), designMd, "utf-8");
|
||||
progress("design", "DESIGN.md generated");
|
||||
} catch (err) {
|
||||
warnings.push(`DESIGN.md generation failed: ${err}`);
|
||||
}
|
||||
|
||||
// Split into sections (if not skipped)
|
||||
let sections: CaptureResult["sections"];
|
||||
if (!opts.skipSplit) {
|
||||
progress("split", "Splitting into sections...");
|
||||
const { splitCapture } = await import("./splitter/index.js");
|
||||
const captureForSplit: CaptureResult = {
|
||||
ok: true,
|
||||
projectDir: outputDir,
|
||||
url,
|
||||
title: tokens.title,
|
||||
extracted,
|
||||
screenshots,
|
||||
tokens,
|
||||
assets,
|
||||
animationCatalog,
|
||||
warnings,
|
||||
};
|
||||
sections = await splitCapture(captureForSplit, opts.maxSections);
|
||||
progress("split", `${sections.length} sections created`);
|
||||
|
||||
// Verify sections (if not skipped)
|
||||
if (!opts.skipVerify && sections.length > 0) {
|
||||
progress("verify", "Verifying sections...");
|
||||
const { verifyCapture } = await import("./verify/index.js");
|
||||
const verifyResult = await verifyCapture({ ...captureForSplit, sections }, (detail) =>
|
||||
progress("verify", detail),
|
||||
);
|
||||
progress(
|
||||
"verify",
|
||||
`${verifyResult.summary.passed} passed, ${verifyResult.summary.failed} failed`,
|
||||
);
|
||||
}
|
||||
|
||||
// Purge unused CSS from section compositions
|
||||
progress("purge", "Purging unused CSS...");
|
||||
const { purgeCompositionCss } = await import("./cssPurger.js");
|
||||
const purgeResults = await purgeCompositionCss(join(outputDir, "compositions"), (detail) =>
|
||||
progress("purge", detail),
|
||||
);
|
||||
if (purgeResults.length > 0) {
|
||||
const totalBefore = purgeResults.reduce((s, r) => s + r.originalBytes, 0);
|
||||
const totalAfter = purgeResults.reduce((s, r) => s + r.purgedBytes, 0);
|
||||
const pct = (((totalBefore - totalAfter) / totalBefore) * 100).toFixed(0);
|
||||
progress(
|
||||
"purge",
|
||||
`${purgeResults.length} files purged (${(totalBefore / 1024).toFixed(0)} KB -> ${(totalAfter / 1024).toFixed(0)} KB, -${pct}%)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Generate CLAUDE.md + .cursorrules (AI agent instructions)
|
||||
try {
|
||||
const { generateAgentPrompt } = await import("./agentPromptGenerator.js");
|
||||
generateAgentPrompt(
|
||||
outputDir,
|
||||
url,
|
||||
tokens,
|
||||
animationCatalog,
|
||||
!!fullPageScreenshot,
|
||||
true, // DESIGN.md is always generated
|
||||
);
|
||||
} catch {
|
||||
// Non-blocking
|
||||
}
|
||||
|
||||
progress("done", "Capture complete");
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
projectDir: outputDir,
|
||||
url,
|
||||
title: tokens.title,
|
||||
extracted,
|
||||
screenshots,
|
||||
tokens,
|
||||
assets,
|
||||
sections,
|
||||
animationCatalog,
|
||||
warnings,
|
||||
};
|
||||
} finally {
|
||||
await chromeBrowser.close();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Generators ──────────────────────────────────────────────────────────────
|
||||
|
||||
function generateVisualStyle(tokens: CaptureResult["tokens"], url: string): string {
|
||||
return `---
|
||||
name: "${tokens.title}"
|
||||
source_url: "${url}"
|
||||
|
||||
style_prompt_short: >
|
||||
Visual style extracted from ${tokens.title}.
|
||||
|
||||
colors:
|
||||
${tokens.colors
|
||||
.slice(0, 8)
|
||||
.map((c, i) => ` - hex: "${c}"\n role: "color-${i}"`)
|
||||
.join("\n")}
|
||||
|
||||
typography:
|
||||
fonts: [${tokens.fonts.map((f) => `"${f}"`).join(", ")}]
|
||||
|
||||
mood:
|
||||
keywords: ["extracted", "website-captured"]
|
||||
---
|
||||
`;
|
||||
}
|
||||
|
||||
function generateCaptureSummary(
|
||||
url: string,
|
||||
tokens: CaptureResult["tokens"],
|
||||
screenshots: string[],
|
||||
assets: CaptureResult["assets"],
|
||||
extracted: CaptureResult["extracted"],
|
||||
animations?: CaptureResult["animationCatalog"],
|
||||
): string {
|
||||
const svgLogos = tokens.svgs.filter((s) => s.isLogo);
|
||||
|
||||
return `# Capture Summary: ${tokens.title}
|
||||
Source: ${url}
|
||||
Captured: ${new Date().toISOString().split("T")[0]}
|
||||
|
||||
## Brand Identity
|
||||
- **Fonts:** ${tokens.fonts.join(", ") || "system-ui"}
|
||||
- **Colors:** ${tokens.colors.slice(0, 6).join(", ")}
|
||||
- **SVG Logos:** ${svgLogos.length} found
|
||||
- **Favicon:** ${tokens.icons.length > 0 ? "Yes" : "No"}
|
||||
|
||||
## Content
|
||||
- **Title:** ${tokens.title}
|
||||
- **Description:** ${tokens.description}
|
||||
- **Headings:** ${tokens.headings.length} extracted
|
||||
- **CTAs:** ${tokens.ctas.map((c) => `"${c.text}"`).join(", ")}
|
||||
|
||||
## Extracted HTML
|
||||
- **Head CSS + Scripts:** ${Math.round(extracted.headHtml.length / 1024)} KB
|
||||
- **Body HTML:** ${Math.round(extracted.bodyHtml.length / 1024)} KB
|
||||
- **CSSOM CSS:** ${Math.round(extracted.cssomRules.length / 1024)} KB
|
||||
- **Page height:** ${extracted.fullPageHeight}px
|
||||
- **Viewport:** ${extracted.viewportWidth}x${extracted.viewportHeight}
|
||||
|
||||
## Animations Catalog
|
||||
${
|
||||
animations
|
||||
? `- **Web Animations:** ${animations.summary.webAnimations} (with keyframes)
|
||||
- **CSS Declarations:** ${animations.summary.cssDeclarations} (animation/transition)
|
||||
- **Scroll Targets:** ${animations.summary.scrollTargets} (IntersectionObserver)
|
||||
- **CDP Events:** ${animations.summary.cdpAnimations}
|
||||
- **Canvases:** ${animations.summary.canvases}
|
||||
- **See:** extracted/animations.json for full keyframe data`
|
||||
: "Not captured"
|
||||
}
|
||||
|
||||
## Screenshots
|
||||
${screenshots.map((s) => `- ${s}`).join("\n")}
|
||||
|
||||
## Assets
|
||||
${assets.map((a) => `- ${a.localPath} (${a.type})`).join("\n") || "None downloaded"}
|
||||
|
||||
## Sections Detected
|
||||
${tokens.sections.map((s) => `- **${s.type}** at y=${s.y}: "${s.heading}" (${s.height}px)`).join("\n")}
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* Full-page screenshot capture.
|
||||
*
|
||||
* All page.evaluate() calls use string expressions to avoid
|
||||
* tsx/esbuild __name injection (see esbuild issue #1031).
|
||||
*/
|
||||
|
||||
import type { Page } from "puppeteer-core";
|
||||
import { writeFileSync, mkdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const SCROLL_PAD = 200;
|
||||
|
||||
export async function captureScreenshots(
|
||||
page: Page,
|
||||
outputDir: string,
|
||||
opts: { maxScreenshots?: number } = {},
|
||||
): Promise<string[]> {
|
||||
const maxScreenshots = opts.maxScreenshots ?? 24;
|
||||
const screenshotsDir = join(outputDir, "screenshots");
|
||||
mkdirSync(screenshotsDir, { recursive: true });
|
||||
|
||||
// Step 1: Calculate capture positions
|
||||
const positions = (await page.evaluate(`(() => {
|
||||
var de = document.documentElement;
|
||||
var body = document.body;
|
||||
var fullHeight = Math.max(de.clientHeight, body.scrollHeight, de.scrollHeight, body.offsetHeight, de.offsetHeight);
|
||||
var viewportH = window.innerHeight;
|
||||
var yDelta = viewportH - (viewportH > ${SCROLL_PAD} ? ${SCROLL_PAD} : 0);
|
||||
var positions = [];
|
||||
for (var y = 0; y < fullHeight; y += yDelta) positions.push(y);
|
||||
var lastPos = fullHeight - viewportH;
|
||||
if (lastPos > 0 && (positions.length === 0 || positions[positions.length - 1] < lastPos - 10)) positions.push(lastPos);
|
||||
if (positions.length > ${maxScreenshots}) {
|
||||
var sampled = [positions[0]];
|
||||
var stride = (positions.length - 1) / (${maxScreenshots} - 1);
|
||||
for (var i = 1; i < ${maxScreenshots} - 1; i++) sampled.push(positions[Math.round(i * stride)]);
|
||||
sampled.push(positions[positions.length - 1]);
|
||||
return sampled;
|
||||
}
|
||||
return positions;
|
||||
})()`)) as number[];
|
||||
|
||||
// Step 2: Disable fixed/sticky elements
|
||||
await page.evaluate(`(() => {
|
||||
var style = document.createElement("style");
|
||||
style.id = "__hf_capture_style";
|
||||
style.textContent = "*, *::before, *::after { transition-duration: 0s !important; animation-duration: 0s !important; }";
|
||||
document.head.appendChild(style);
|
||||
document.querySelectorAll("*").forEach(function(el) {
|
||||
var cs = getComputedStyle(el);
|
||||
if (cs.position === "fixed" || cs.position === "sticky") {
|
||||
el.dataset.hfOrigPos = cs.position;
|
||||
el.style.setProperty("position", "absolute", "important");
|
||||
}
|
||||
});
|
||||
})()`);
|
||||
|
||||
// Step 3: Capture each position
|
||||
await page.evaluate(`window.scrollTo(0, 0)`);
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
|
||||
const filePaths: string[] = [];
|
||||
|
||||
for (let i = 0; i < positions.length; i++) {
|
||||
await page.evaluate(`window.scrollTo(0, ${positions[i]})`);
|
||||
await new Promise((r) => setTimeout(r, 350));
|
||||
|
||||
const filename = `section-${String(i).padStart(2, "0")}.png`;
|
||||
const filePath = join(screenshotsDir, filename);
|
||||
|
||||
const buffer = await page.screenshot({ type: "png" });
|
||||
writeFileSync(filePath, buffer);
|
||||
filePaths.push(`screenshots/${filename}`);
|
||||
}
|
||||
|
||||
// Step 4: Restore
|
||||
await page.evaluate(`(() => {
|
||||
var style = document.getElementById("__hf_capture_style");
|
||||
if (style) style.remove();
|
||||
document.querySelectorAll("[data-hf-orig-pos]").forEach(function(el) {
|
||||
el.style.removeProperty("position");
|
||||
delete el.dataset.hfOrigPos;
|
||||
});
|
||||
window.scrollTo(0, 0);
|
||||
})()`);
|
||||
|
||||
return filePaths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture a full-page screenshot after scrolling to trigger lazy loading.
|
||||
* Uses Puppeteer's built-in fullPage stitching (same as Chrome DevTools
|
||||
* Cmd+Shift+P → "Capture full size screenshot").
|
||||
*
|
||||
* Note: Chrome has a ~16384px height limit. Content below that is clipped,
|
||||
* but the important above-the-fold design patterns are always captured.
|
||||
*/
|
||||
export async function captureFullPageScreenshot(
|
||||
page: Page,
|
||||
outputDir: string,
|
||||
): Promise<string | undefined> {
|
||||
const screenshotsDir = join(outputDir, "screenshots");
|
||||
mkdirSync(screenshotsDir, { recursive: true });
|
||||
|
||||
try {
|
||||
// Scroll through the page to trigger lazy loading first
|
||||
await page.evaluate(`(async () => {
|
||||
var step = Math.floor(window.innerHeight * 0.7);
|
||||
var limit = Math.min(document.body.scrollHeight, 50000);
|
||||
for (var y = 0; y < limit; y += step) {
|
||||
window.scrollTo(0, y);
|
||||
await new Promise(function(r) { setTimeout(r, 200); });
|
||||
}
|
||||
window.scrollTo(0, document.body.scrollHeight);
|
||||
await new Promise(function(r) { setTimeout(r, 500); });
|
||||
window.scrollTo(0, 0);
|
||||
await new Promise(function(r) { setTimeout(r, 300); });
|
||||
})()`);
|
||||
|
||||
// Wait for all images to finish loading
|
||||
await page
|
||||
.waitForFunction(
|
||||
`Array.from(document.querySelectorAll("img")).every(function(img) { return img.complete; })`,
|
||||
{ timeout: 10000 },
|
||||
)
|
||||
.catch(() => {});
|
||||
|
||||
// Kill animations and scroll to top before capture
|
||||
await page.evaluate(`(() => {
|
||||
var style = document.createElement("style");
|
||||
style.id = "__hf_fullpage_style";
|
||||
style.textContent = "*, *::before, *::after { transition-duration: 0s !important; animation-duration: 0s !important; }";
|
||||
document.head.appendChild(style);
|
||||
window.scrollTo(0, 0);
|
||||
})()`);
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
|
||||
const filename = "full-page.png";
|
||||
const filePath = join(screenshotsDir, filename);
|
||||
const buffer = await page.screenshot({ type: "png", fullPage: true });
|
||||
writeFileSync(filePath, buffer);
|
||||
|
||||
// Cleanup
|
||||
await page.evaluate(`(() => {
|
||||
var style = document.getElementById("__hf_fullpage_style");
|
||||
if (style) style.remove();
|
||||
})()`);
|
||||
|
||||
return `screenshots/${filename}`;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* Generate HyperFrames sub-composition HTML from a parsed section.
|
||||
*
|
||||
* Each section becomes a template-wrapped composition with:
|
||||
* - Shared CSS (full head styles + CSSOM)
|
||||
* - The section's HTML content
|
||||
* - Scale factor to fit 1920x1080
|
||||
* - Default GSAP entrance/exit animations
|
||||
*/
|
||||
|
||||
import type { ParsedSection } from "./sectionParser.js";
|
||||
|
||||
const DEFAULT_SECTION_DURATION = 5;
|
||||
|
||||
export function generateComposition(
|
||||
section: ParsedSection,
|
||||
headCss: string,
|
||||
cssomRules: string,
|
||||
htmlAttrs: string,
|
||||
viewportWidth: number,
|
||||
duration: number = DEFAULT_SECTION_DURATION,
|
||||
): string {
|
||||
const compositionId = section.id;
|
||||
const canvasW = 1920;
|
||||
const canvasH = 1080;
|
||||
// Scale to fit the section height into the canvas (if taller than canvas)
|
||||
const sectionH = section.height || canvasH;
|
||||
const scaleByWidth = canvasW / viewportWidth;
|
||||
const scaleByHeight = sectionH * scaleByWidth > canvasH ? canvasH / (sectionH * scaleByWidth) : 1;
|
||||
const scale = scaleByWidth * scaleByHeight;
|
||||
|
||||
// For sub-sections split from a larger parent, offset the content vertically
|
||||
// so the viewport shows the right part of the shared HTML.
|
||||
const contentOffsetY = section.parentY != null ? -(section.y - section.parentY) : 0;
|
||||
|
||||
// Strip <script> tags from head CSS — only keep <style> tags
|
||||
// This reduces size and avoids script conflicts in compositions
|
||||
const cssOnly = headCss.replace(/<script[\s\S]*?<\/script>/gi, "");
|
||||
|
||||
return `<template id="${compositionId}-template">
|
||||
<div data-composition-id="${compositionId}" data-width="${canvasW}" data-height="${canvasH}">
|
||||
<!-- Page styles (inlined for HyperFrames compatibility) -->
|
||||
${cssOnly}
|
||||
${cssomRules ? `<style data-cssom="true">${cssomRules}</style>` : ""}
|
||||
|
||||
<!-- Section content scaled to fit canvas -->
|
||||
<div id="${compositionId}-bg" style="
|
||||
position: absolute; top: 0; left: 0;
|
||||
width: ${canvasW}px; height: ${canvasH}px;
|
||||
background: ${section.backgroundColor || "#ffffff"};
|
||||
overflow: hidden; opacity: 0;
|
||||
">
|
||||
<div id="${compositionId}-content" ${htmlAttrs} style="
|
||||
transform-origin: top left;
|
||||
transform: scale(${scale.toFixed(4)});
|
||||
width: ${viewportWidth}px;
|
||||
position: absolute; top: ${contentOffsetY}px; left: 0;
|
||||
">
|
||||
${section.html}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
|
||||
<script>
|
||||
(function() {
|
||||
var dur = ${duration};
|
||||
var tl = gsap.timeline({ paused: true });
|
||||
|
||||
// Entrance
|
||||
tl.fromTo("#${compositionId}-bg",
|
||||
{ opacity: 0 }, { opacity: 1, duration: 0.4, ease: "power2.out" }, 0);
|
||||
|
||||
// Subtle zoom during hold (continuous motion)
|
||||
tl.fromTo("#${compositionId}-content",
|
||||
{ scale: ${scale.toFixed(4)} },
|
||||
{ scale: ${(scale * 1.02).toFixed(4)}, duration: dur - 0.6, ease: "sine.inOut" }, 0.3);
|
||||
|
||||
// Exit
|
||||
tl.to("#${compositionId}-bg",
|
||||
{ opacity: 0, duration: 0.3, ease: "power2.in" }, dur - 0.3);
|
||||
|
||||
window.__timelines = window.__timelines || {};
|
||||
window.__timelines["${compositionId}"] = tl;
|
||||
})();
|
||||
</script>
|
||||
</div>
|
||||
</template>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate root index.html that loads all sections sequentially.
|
||||
*/
|
||||
export function generateRootComposition(
|
||||
sectionIds: string[],
|
||||
title: string,
|
||||
sectionDuration: number = DEFAULT_SECTION_DURATION,
|
||||
): string {
|
||||
const totalDuration = sectionIds.length * sectionDuration;
|
||||
|
||||
const sectionDivs = sectionIds
|
||||
.map(
|
||||
(id, i) => ` <div
|
||||
data-composition-id="${id}"
|
||||
data-composition-src="compositions/${id}.html"
|
||||
data-start="${i * sectionDuration}"
|
||||
data-duration="${sectionDuration}"
|
||||
data-track-index="1"
|
||||
></div>`,
|
||||
)
|
||||
.join("\n\n");
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=1920" />
|
||||
<title>${title} — Captured Components</title>
|
||||
<style>
|
||||
body { margin: 0; padding: 0; background: #000; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div
|
||||
data-composition-id="${slugify(title)}-capture"
|
||||
data-width="1920"
|
||||
data-height="1080"
|
||||
data-start="0"
|
||||
data-duration="${totalDuration}"
|
||||
>
|
||||
${sectionDivs}
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
|
||||
<script>
|
||||
window.__timelines = window.__timelines || {};
|
||||
window.__timelines["${slugify(title)}-capture"] = gsap.timeline({ paused: true });
|
||||
</script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
function slugify(text: string): string {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.slice(0, 30);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Split captured website into per-section HyperFrames sub-compositions.
|
||||
*/
|
||||
|
||||
import { writeFileSync, mkdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { parseSections } from "./sectionParser.js";
|
||||
import { generateComposition, generateRootComposition } from "./compositionGen.js";
|
||||
import type { CaptureResult, SectionResult } from "../types.js";
|
||||
|
||||
export async function splitCapture(
|
||||
captureResult: CaptureResult,
|
||||
maxSections: number = 12,
|
||||
): Promise<SectionResult[]> {
|
||||
const { extracted, tokens, projectDir } = captureResult;
|
||||
|
||||
// Parse body HTML into sections
|
||||
const parsedSections = parseSections(extracted.bodyHtml, tokens.sections, maxSections);
|
||||
|
||||
if (parsedSections.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Create compositions directory
|
||||
const compositionsDir = join(projectDir, "compositions");
|
||||
mkdirSync(compositionsDir, { recursive: true });
|
||||
|
||||
// Generate sub-composition for each section
|
||||
const results: SectionResult[] = [];
|
||||
|
||||
for (const section of parsedSections) {
|
||||
const compositionHtml = generateComposition(
|
||||
section,
|
||||
extracted.headHtml,
|
||||
extracted.cssomRules,
|
||||
extracted.htmlAttrs,
|
||||
extracted.viewportWidth,
|
||||
);
|
||||
|
||||
const filename = `${section.id}.html`;
|
||||
const filePath = join(compositionsDir, filename);
|
||||
writeFileSync(filePath, compositionHtml, "utf-8");
|
||||
|
||||
results.push({
|
||||
id: section.id,
|
||||
type: section.type,
|
||||
heading: section.heading,
|
||||
compositionPath: `compositions/${filename}`,
|
||||
verified: false, // Will be set by verify step
|
||||
});
|
||||
}
|
||||
|
||||
// Generate root index.html
|
||||
const rootHtml = generateRootComposition(
|
||||
results.map((r) => r.id),
|
||||
tokens.title,
|
||||
);
|
||||
writeFileSync(join(projectDir, "index.html"), rootHtml, "utf-8");
|
||||
|
||||
return results;
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
/**
|
||||
* Parse body HTML into semantic sections.
|
||||
*
|
||||
* Identifies section boundaries using:
|
||||
* 1. <section> elements
|
||||
* 2. Direct children of <main>
|
||||
* 3. <header>, <footer>, <nav> elements
|
||||
* 4. Detected sections from the token extractor (with Y positions)
|
||||
*/
|
||||
|
||||
import { parseHTML } from "linkedom";
|
||||
import type { DesignTokens } from "../types.js";
|
||||
|
||||
export interface ParsedSection {
|
||||
/** Unique identifier (kebab-case) */
|
||||
id: string;
|
||||
/** Section type from token detection */
|
||||
type: string;
|
||||
/** Heading text (if any) */
|
||||
heading: string;
|
||||
/** The section's outerHTML */
|
||||
html: string;
|
||||
/** Approximate Y position on original page */
|
||||
y: number;
|
||||
/** Section height */
|
||||
height: number;
|
||||
/** Y offset of parent element (for sub-sections split from a larger parent) */
|
||||
parentY?: number;
|
||||
/** All class names used in this section (for CSS subsetting) */
|
||||
classNames: Set<string>;
|
||||
/** All IDs used in this section */
|
||||
elementIds: Set<string>;
|
||||
/** All tag names used */
|
||||
tagNames: Set<string>;
|
||||
/** Computed background color */
|
||||
backgroundColor: string;
|
||||
}
|
||||
|
||||
export function parseSections(
|
||||
bodyHtml: string,
|
||||
tokenSections: DesignTokens["sections"],
|
||||
maxSections: number = 12,
|
||||
): ParsedSection[] {
|
||||
const { document } = parseHTML(`<!DOCTYPE html><html><body>${bodyHtml}</body></html>`);
|
||||
const body = document.body;
|
||||
|
||||
// Strategy: find top-level semantic containers
|
||||
const candidates: Element[] = [];
|
||||
|
||||
// 1. <section> elements (direct or one level deep)
|
||||
body.querySelectorAll("section").forEach((el: Element) => {
|
||||
candidates.push(el);
|
||||
});
|
||||
|
||||
// 2. <header>, <nav>, <footer>
|
||||
body.querySelectorAll("header, nav, footer").forEach((el: Element) => {
|
||||
if (!candidates.includes(el)) candidates.push(el);
|
||||
});
|
||||
|
||||
// 3. Direct children of <main>
|
||||
const main = body.querySelector("main");
|
||||
if (main) {
|
||||
Array.from(main.children).forEach((child) => {
|
||||
if (child.tagName !== "SCRIPT" && child.tagName !== "STYLE" && !candidates.includes(child)) {
|
||||
candidates.push(child);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 4. If we found very few candidates, try direct body children
|
||||
if (candidates.length < 3) {
|
||||
Array.from(body.children).forEach((child) => {
|
||||
if (
|
||||
child.tagName !== "SCRIPT" &&
|
||||
child.tagName !== "STYLE" &&
|
||||
child.tagName !== "NOSCRIPT" &&
|
||||
child.innerHTML.length > 200 &&
|
||||
!candidates.includes(child)
|
||||
) {
|
||||
candidates.push(child);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Deduplicate: remove children of other candidates
|
||||
const filtered = candidates.filter((el) => {
|
||||
return !candidates.some((other) => other !== el && other.contains(el));
|
||||
});
|
||||
|
||||
// Expand oversized sections: returns {el, token?} pairs where token override
|
||||
// is set for sub-sections split from a large parent.
|
||||
const expanded = expandOversizedSections(filtered, tokenSections, document);
|
||||
|
||||
// Build sections from candidates
|
||||
const sections: ParsedSection[] = [];
|
||||
let sectionIndex = 0;
|
||||
|
||||
for (const entry of expanded) {
|
||||
if (sections.length >= maxSections) break;
|
||||
|
||||
const el = entry.el;
|
||||
const html = el.outerHTML;
|
||||
if (html.length < 100) continue;
|
||||
|
||||
// Use token override if provided (for split sub-sections), else detect from DOM
|
||||
let heading: string;
|
||||
let type: string;
|
||||
let y: number;
|
||||
let height: number;
|
||||
let backgroundColor: string;
|
||||
|
||||
// For sub-sections split from a parent, find the parent's Y by looking at the
|
||||
// first entry that shares this same element.
|
||||
let parentY: number | undefined;
|
||||
if (entry.token) {
|
||||
heading = entry.token.heading;
|
||||
type = entry.token.type;
|
||||
y = entry.token.y;
|
||||
height = entry.token.height;
|
||||
backgroundColor = entry.token.backgroundColor || "#ffffff";
|
||||
// Find the parent Y (first token for this element)
|
||||
const firstForEl = expanded.find((e) => e.el === el);
|
||||
if (firstForEl?.token && firstForEl.token.y !== y) {
|
||||
parentY = firstForEl.token.y;
|
||||
}
|
||||
} else {
|
||||
const headingEl = el.querySelector("h1, h2, h3, h4");
|
||||
heading = headingEl?.textContent?.trim().slice(0, 80) || "";
|
||||
|
||||
const tokenMatch = tokenSections.find((ts) => {
|
||||
if (heading && ts.heading) {
|
||||
return (
|
||||
heading.includes(ts.heading.slice(0, 30)) || ts.heading.includes(heading.slice(0, 30))
|
||||
);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
type = tokenMatch?.type || classifyElement(el);
|
||||
y = tokenMatch?.y || 0;
|
||||
height = tokenMatch?.height || 0;
|
||||
backgroundColor = tokenMatch?.backgroundColor || "#ffffff";
|
||||
}
|
||||
|
||||
const classNames = new Set<string>();
|
||||
const elementIds = new Set<string>();
|
||||
const tagNames = new Set<string>();
|
||||
collectSelectors(el, classNames, elementIds, tagNames);
|
||||
|
||||
const id = generateSectionId(type, heading, sectionIndex);
|
||||
sectionIndex++;
|
||||
|
||||
sections.push({
|
||||
id,
|
||||
type,
|
||||
heading,
|
||||
html,
|
||||
y,
|
||||
height,
|
||||
parentY,
|
||||
classNames,
|
||||
elementIds,
|
||||
tagNames,
|
||||
backgroundColor,
|
||||
});
|
||||
}
|
||||
|
||||
return sections;
|
||||
}
|
||||
|
||||
type ExpandedEntry = { el: Element; token?: DesignTokens["sections"][0] };
|
||||
|
||||
/**
|
||||
* If a DOM section is large and contains multiple token-identified sub-sections,
|
||||
* return the SAME parent element once per sub-section with different token overrides.
|
||||
* compositionGen uses the token's Y offset to "scroll" to the right part of the HTML.
|
||||
*/
|
||||
function expandOversizedSections(
|
||||
elements: Element[],
|
||||
tokenSections: DesignTokens["sections"],
|
||||
_document: Document,
|
||||
): ExpandedEntry[] {
|
||||
const result: ExpandedEntry[] = [];
|
||||
|
||||
for (const el of elements) {
|
||||
const headingEl = el.querySelector("h1, h2, h3, h4");
|
||||
const heading = headingEl?.textContent?.trim().slice(0, 80) || "";
|
||||
|
||||
const matchingTokens = tokenSections.filter((ts) => {
|
||||
if (!ts.heading) return false;
|
||||
return heading.includes(ts.heading.slice(0, 30)) || ts.heading.includes(heading.slice(0, 30));
|
||||
});
|
||||
|
||||
const myToken = matchingTokens[0];
|
||||
if (!myToken) {
|
||||
result.push({ el });
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find token sections that are INSIDE this element's Y range but don't match its heading
|
||||
const containedTokens = tokenSections.filter((ts) => {
|
||||
if (!ts.heading || ts.heading === myToken.heading) return false;
|
||||
return ts.y >= myToken.y && ts.y < myToken.y + myToken.height;
|
||||
});
|
||||
|
||||
if (containedTokens.length < 2) {
|
||||
result.push({ el });
|
||||
continue;
|
||||
}
|
||||
|
||||
// Build the full list sorted by Y, then fix heights so each sub-section
|
||||
// only covers its own portion (not the entire parent).
|
||||
const allTokens = [myToken, ...containedTokens].sort((a, b) => a.y - b.y);
|
||||
for (let i = 0; i < allTokens.length; i++) {
|
||||
const t = allTokens[i]!;
|
||||
const nextY = i + 1 < allTokens.length ? allTokens[i + 1]!.y : myToken.y + myToken.height;
|
||||
result.push({ el, token: { ...t, height: nextY - t.y } });
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function classifyElement(el: Element): string {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
const classes = (el.className || "").toString().toLowerCase();
|
||||
|
||||
if (tag === "header" || tag === "nav") return "header";
|
||||
if (tag === "footer") return "footer";
|
||||
if (classes.includes("hero")) return "hero";
|
||||
if (classes.includes("feature") || classes.includes("bento")) return "features";
|
||||
if (classes.includes("testimonial") || classes.includes("quote")) return "testimonials";
|
||||
if (classes.includes("logo") || classes.includes("customer")) return "logos";
|
||||
if (classes.includes("cta") || classes.includes("pricing")) return "cta";
|
||||
return "content";
|
||||
}
|
||||
|
||||
function generateSectionId(type: string, heading: string, index: number): string {
|
||||
if (heading) {
|
||||
const slug = heading
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.slice(0, 30);
|
||||
return `section-${slug}`;
|
||||
}
|
||||
return `section-${type}-${index}`;
|
||||
}
|
||||
|
||||
function collectSelectors(
|
||||
el: Element,
|
||||
classNames: Set<string>,
|
||||
elementIds: Set<string>,
|
||||
tagNames: Set<string>,
|
||||
): void {
|
||||
tagNames.add(el.tagName.toLowerCase());
|
||||
|
||||
if (el.id) elementIds.add(el.id);
|
||||
|
||||
if (el.className && typeof el.className === "string") {
|
||||
el.className.split(/\s+/).forEach((cls: string) => {
|
||||
if (cls) classNames.add(cls);
|
||||
});
|
||||
}
|
||||
|
||||
// Recurse into children (limit depth to avoid performance issues)
|
||||
const children = el.children;
|
||||
for (let i = 0; i < children.length && i < 500; i++) {
|
||||
const child = children[i];
|
||||
if (child) collectSelectors(child, classNames, elementIds, tagNames);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* Extract design tokens from a rendered page.
|
||||
*
|
||||
* All page.evaluate() calls use string expressions to avoid
|
||||
* tsx/esbuild __name injection (see esbuild issue #1031).
|
||||
*/
|
||||
|
||||
import type { Page } from "puppeteer-core";
|
||||
import type { DesignTokens } from "./types.js";
|
||||
|
||||
// The entire extraction runs as a single string-based evaluate
|
||||
// to avoid tsx __name injection into the browser context.
|
||||
const EXTRACT_SCRIPT = `(() => {
|
||||
var isVisible = (el) => {
|
||||
var s = getComputedStyle(el);
|
||||
return s.display !== "none" && s.visibility !== "hidden" && s.opacity !== "0" && el.getBoundingClientRect().height > 0;
|
||||
};
|
||||
|
||||
// 1. CSS custom properties from :root
|
||||
var cssVariables = {};
|
||||
for (var i = 0; i < document.styleSheets.length; i++) {
|
||||
try {
|
||||
var rules = document.styleSheets[i].cssRules;
|
||||
for (var j = 0; j < rules.length; j++) {
|
||||
if (rules[j].selectorText === ":root") {
|
||||
for (var k = 0; k < rules[j].style.length; k++) {
|
||||
var prop = rules[j].style[k];
|
||||
if (prop.startsWith("--")) {
|
||||
cssVariables[prop] = rules[j].style.getPropertyValue(prop).trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
|
||||
// 2. Meta
|
||||
var title = document.title || "";
|
||||
var descEl = document.querySelector('meta[name="description"]') || document.querySelector('meta[property="og:description"]');
|
||||
var description = descEl ? descEl.content : "";
|
||||
var ogImgEl = document.querySelector('meta[property="og:image"]');
|
||||
var ogImage = ogImgEl ? ogImgEl.content : undefined;
|
||||
|
||||
// 3. Fonts
|
||||
var fontSet = {};
|
||||
var fontSamples = [document.body, document.querySelector("h1"), document.querySelector("h2"), document.querySelector("p"), document.querySelector("button")].filter(Boolean);
|
||||
for (var fi = 0; fi < fontSamples.length; fi++) {
|
||||
var family = getComputedStyle(fontSamples[fi]).fontFamily.split(",")[0].replace(/['"]/g, "").trim();
|
||||
if (family && ["serif","sans-serif","monospace","cursive"].indexOf(family) === -1) fontSet[family] = true;
|
||||
}
|
||||
|
||||
// 4. Colors
|
||||
var colorSet = {};
|
||||
var colorSamples = [document.body, document.querySelector("header"), document.querySelector("nav"), document.querySelector("main"), document.querySelector("h1"), document.querySelector("a"), document.querySelector("button")].filter(Boolean);
|
||||
for (var ci = 0; ci < colorSamples.length; ci++) {
|
||||
var cs = getComputedStyle(colorSamples[ci]);
|
||||
if (cs.backgroundColor && cs.backgroundColor !== "rgba(0, 0, 0, 0)" && cs.backgroundColor !== "transparent") colorSet[cs.backgroundColor] = true;
|
||||
if (cs.color) colorSet[cs.color] = true;
|
||||
}
|
||||
|
||||
// 5. Headings
|
||||
var headingEls = Array.from(document.querySelectorAll("h1, h2, h3, h4")).slice(0, 20);
|
||||
var headings = headingEls.filter(isVisible).map(function(h) {
|
||||
var s = getComputedStyle(h);
|
||||
return { level: parseInt(h.tagName[1]), text: (h.textContent || "").trim().slice(0, 200), fontSize: s.fontSize, fontWeight: s.fontWeight, color: s.color };
|
||||
});
|
||||
|
||||
// 6. Paragraphs
|
||||
var paragraphs = Array.from(document.querySelectorAll("p")).slice(0, 10).map(function(p) { return (p.textContent || "").trim().slice(0, 300); }).filter(function(t) { return t.length > 20; });
|
||||
|
||||
// 7. CTAs
|
||||
var ctaEls = Array.from(document.querySelectorAll('a[class*="btn"], a[class*="button"], button[class*="primary"], [role="button"], a[class*="cta"]')).slice(0, 10);
|
||||
var ctas = ctaEls.filter(isVisible).map(function(c) { return { text: (c.textContent || "").trim().slice(0, 60), href: c.href || undefined }; }).filter(function(c) { return c.text.length > 1; });
|
||||
|
||||
// 8. SVGs
|
||||
var svgEls = Array.from(document.querySelectorAll("svg"));
|
||||
var svgs = svgEls.map(function(svg) {
|
||||
var label = svg.getAttribute("aria-label");
|
||||
var w = svg.getAttribute("width");
|
||||
if (!label && (!w || parseInt(w) < 30)) return null;
|
||||
return {
|
||||
label: label || undefined,
|
||||
viewBox: svg.getAttribute("viewBox") || undefined,
|
||||
outerHTML: svg.outerHTML.slice(0, 3000),
|
||||
isLogo: (label && label.toLowerCase().indexOf("logo") !== -1) || svg.closest('[class*="logo"], [class*="brand"], [class*="home"]') !== null
|
||||
};
|
||||
}).filter(Boolean).slice(0, 20);
|
||||
|
||||
// 9. Images
|
||||
var imgEls = Array.from(document.querySelectorAll("img[src]")).filter(function(img) { return img.naturalWidth > 200 && isVisible(img); }).slice(0, 15);
|
||||
var images = imgEls.map(function(img) { return { src: img.src, alt: img.alt || "", width: img.naturalWidth, height: img.naturalHeight }; });
|
||||
|
||||
// 10. Icons
|
||||
var iconEls = Array.from(document.querySelectorAll('link[rel*="icon"], link[rel="apple-touch-icon"]'));
|
||||
var icons = iconEls.map(function(l) { return { rel: l.rel, href: l.href }; });
|
||||
|
||||
// 11. Sections
|
||||
var sectionResults = [];
|
||||
var seen = {};
|
||||
var candidates = Array.from(document.querySelectorAll('section, main > div, main > section, [class*="hero"], [class*="Hero"], footer'));
|
||||
for (var si = 0; si < candidates.length; si++) {
|
||||
var el = candidates[si];
|
||||
if (seen[si]) continue;
|
||||
var rect = el.getBoundingClientRect();
|
||||
if (rect.height < 200 || rect.width < 400 || !isVisible(el)) continue;
|
||||
var y = rect.top + window.scrollY;
|
||||
var heading = el.querySelector("h1, h2, h3, h4");
|
||||
var headingText = heading ? (heading.textContent || "").trim().slice(0, 80) : "";
|
||||
var classes = (el.className || "").toString().toLowerCase();
|
||||
var type = "content";
|
||||
if (y < 200 || classes.indexOf("hero") !== -1) type = "hero";
|
||||
else if (el.tagName === "FOOTER" || classes.indexOf("footer") !== -1) type = "footer";
|
||||
else if (classes.indexOf("cta") !== -1) type = "cta";
|
||||
else if (classes.indexOf("logo") !== -1 || classes.indexOf("customer") !== -1) type = "logos";
|
||||
else if (classes.indexOf("testimonial") !== -1 || classes.indexOf("quote") !== -1) type = "testimonials";
|
||||
else if (classes.indexOf("feature") !== -1 || classes.indexOf("section") !== -1) type = "features";
|
||||
var selector = el.id ? "#" + el.id : el.tagName.toLowerCase();
|
||||
var sectionBg = getComputedStyle(el).backgroundColor;
|
||||
if (!sectionBg || sectionBg === "rgba(0, 0, 0, 0)" || sectionBg === "transparent") sectionBg = "#ffffff";
|
||||
seen[si] = true;
|
||||
sectionResults.push({ selector: selector, type: type, y: Math.round(y), height: Math.round(rect.height), heading: headingText, backgroundColor: sectionBg });
|
||||
}
|
||||
sectionResults.sort(function(a, b) { return a.y - b.y; });
|
||||
var filtered = sectionResults.filter(function(s, i) { return i === 0 || Math.abs(s.y - sectionResults[i-1].y) > 100; });
|
||||
|
||||
return {
|
||||
title: title, description: description, ogImage: ogImage,
|
||||
cssVariables: cssVariables, fonts: Object.keys(fontSet), colors: Object.keys(colorSet).slice(0, 12),
|
||||
headings: headings, paragraphs: paragraphs, ctas: ctas,
|
||||
svgs: svgs, images: images, icons: icons, sections: filtered
|
||||
};
|
||||
})()`;
|
||||
|
||||
export async function extractTokens(page: Page): Promise<DesignTokens> {
|
||||
return page.evaluate(EXTRACT_SCRIPT) as Promise<DesignTokens>;
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* Types for the website capture pipeline.
|
||||
*
|
||||
* Phase 1: Capture — Extract HTML, CSS, screenshots, tokens, assets from a URL
|
||||
* Phase 2: Split — Decompose into per-section sub-compositions
|
||||
* Phase 3: Verify — Validate each section renders correctly
|
||||
* Phase 4: Scaffold — Assemble standard HyperFrames project
|
||||
*/
|
||||
|
||||
// ── Phase 1: Capture ────────────────────────────────────────────────────────
|
||||
|
||||
export interface CaptureOptions {
|
||||
/** URL to capture */
|
||||
url: string;
|
||||
/** Output directory */
|
||||
outputDir: string;
|
||||
/** Viewport width (default: 1920) */
|
||||
viewportWidth?: number;
|
||||
/** Viewport height (default: 1080) */
|
||||
viewportHeight?: number;
|
||||
/** Page load timeout in ms (default: 30000) */
|
||||
timeout?: number;
|
||||
/** Extra wait after load for JS to settle (default: 3000) */
|
||||
settleTime?: number;
|
||||
/** Maximum screenshots to take (default: 24) */
|
||||
maxScreenshots?: number;
|
||||
/** Skip asset downloads */
|
||||
skipAssets?: boolean;
|
||||
/** Skip section splitting (Phase 2) */
|
||||
skipSplit?: boolean;
|
||||
/** Skip section verification (Phase 3) */
|
||||
skipVerify?: boolean;
|
||||
/** Maximum sections to extract (default: 12) */
|
||||
maxSections?: number;
|
||||
/** Output JSON for programmatic use */
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export interface CaptureResult {
|
||||
/** Whether capture completed successfully */
|
||||
ok: boolean;
|
||||
/** Project output directory */
|
||||
projectDir: string;
|
||||
/** Source URL */
|
||||
url: string;
|
||||
/** Page title */
|
||||
title: string;
|
||||
/** Extracted HTML data */
|
||||
extracted: ExtractedHtml;
|
||||
/** Screenshot file paths (relative to projectDir) */
|
||||
screenshots: string[];
|
||||
/** Design tokens extracted from the page */
|
||||
tokens: DesignTokens;
|
||||
/** Downloaded asset paths (relative to projectDir) */
|
||||
assets: DownloadedAsset[];
|
||||
/** Section split results (if splitting was performed) */
|
||||
sections?: SectionResult[];
|
||||
/** Animation catalog (captured during full-JS page load) */
|
||||
animationCatalog?: import("./animationCataloger.js").AnimationCatalog;
|
||||
/** Errors/warnings encountered during capture */
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export interface ExtractedHtml {
|
||||
/** All <style> tags from <head> (after stylesheet inlining) */
|
||||
headHtml: string;
|
||||
/** Full document.body.innerHTML */
|
||||
bodyHtml: string;
|
||||
/** CSS-in-JS rules from document.styleSheets (CSSOM) */
|
||||
cssomRules: string;
|
||||
/** <html> element attributes (class, data-theme, style, lang) */
|
||||
htmlAttrs: string;
|
||||
/** Original viewport width during capture */
|
||||
viewportWidth: number;
|
||||
/** Original viewport height during capture */
|
||||
viewportHeight: number;
|
||||
/** Full page scroll height */
|
||||
fullPageHeight: number;
|
||||
}
|
||||
|
||||
// ── Design Tokens ───────────────────────────────────────────────────────────
|
||||
|
||||
export interface DesignTokens {
|
||||
/** Page title */
|
||||
title: string;
|
||||
/** Meta description */
|
||||
description: string;
|
||||
/** OG image URL */
|
||||
ogImage?: string;
|
||||
/** CSS custom properties from :root */
|
||||
cssVariables: Record<string, string>;
|
||||
/** Font families in use */
|
||||
fonts: string[];
|
||||
/** Extracted colors (background, text, accent) */
|
||||
colors: string[];
|
||||
/** Headings with text and basic styles */
|
||||
headings: Array<{
|
||||
level: number;
|
||||
text: string;
|
||||
fontSize: string;
|
||||
fontWeight: string;
|
||||
color: string;
|
||||
}>;
|
||||
/** Paragraph text (first 10) */
|
||||
paragraphs: string[];
|
||||
/** CTA button/link text */
|
||||
ctas: Array<{ text: string; href?: string }>;
|
||||
/** SVG elements with labels */
|
||||
svgs: Array<{
|
||||
label?: string;
|
||||
viewBox?: string;
|
||||
outerHTML: string;
|
||||
isLogo: boolean;
|
||||
}>;
|
||||
/** Large images on the page */
|
||||
images: Array<{
|
||||
src: string;
|
||||
alt: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}>;
|
||||
/** Favicon/icon URLs */
|
||||
icons: Array<{ rel: string; href: string }>;
|
||||
/** Detected page sections with bounding rects */
|
||||
sections: Array<{
|
||||
selector: string;
|
||||
type: string;
|
||||
y: number;
|
||||
height: number;
|
||||
heading: string;
|
||||
backgroundColor?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
// ── Assets ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface DownloadedAsset {
|
||||
/** Original URL */
|
||||
url: string;
|
||||
/** Local file path (relative to projectDir) */
|
||||
localPath: string;
|
||||
/** Asset type */
|
||||
type: "svg" | "image" | "favicon";
|
||||
}
|
||||
|
||||
// ── Phase 2: Split ──────────────────────────────────────────────────────────
|
||||
|
||||
export interface SectionResult {
|
||||
/** Section identifier (kebab-case) */
|
||||
id: string;
|
||||
/** Detected section type */
|
||||
type: string;
|
||||
/** First heading in the section */
|
||||
heading: string;
|
||||
/** Composition file path (relative to projectDir) */
|
||||
compositionPath: string;
|
||||
/** Whether this section was verified to render correctly */
|
||||
verified: boolean;
|
||||
/** If not verified, the fallback applied */
|
||||
fallback?: "screenshot" | "css-fix" | "none";
|
||||
/** Matching screenshot path */
|
||||
screenshotPath?: string;
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* Verify each sub-composition renders correctly.
|
||||
*
|
||||
* For each composition:
|
||||
* 1. Load in headless Chrome
|
||||
* 2. Screenshot what renders
|
||||
* 3. Check for blank/broken output
|
||||
* 4. Write verification report
|
||||
*/
|
||||
|
||||
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { SectionResult, CaptureResult } from "../types.js";
|
||||
|
||||
interface VerifyResult {
|
||||
sections: SectionVerification[];
|
||||
summary: {
|
||||
total: number;
|
||||
passed: number;
|
||||
failed: number;
|
||||
fallback: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface SectionVerification {
|
||||
id: string;
|
||||
compositionPath: string;
|
||||
status: "passed" | "failed" | "fallback";
|
||||
errors: string[];
|
||||
/** Screenshot of the rendered section (relative path) */
|
||||
renderedScreenshot?: string;
|
||||
/** Matching viewport screenshot from capture */
|
||||
sourceScreenshot?: string;
|
||||
/** If fallback was applied, what type */
|
||||
fallbackType?: "screenshot-bg" | "none";
|
||||
}
|
||||
|
||||
export async function verifyCapture(
|
||||
captureResult: CaptureResult,
|
||||
onProgress?: (detail: string) => void,
|
||||
): Promise<VerifyResult> {
|
||||
const { projectDir, sections, screenshots } = captureResult;
|
||||
|
||||
if (!sections || sections.length === 0) {
|
||||
return {
|
||||
sections: [],
|
||||
summary: { total: 0, passed: 0, failed: 0, fallback: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
const progress = (msg: string) => onProgress?.(msg);
|
||||
|
||||
// Launch browser for verification
|
||||
const { ensureBrowser } = await import("../../browser/manager.js");
|
||||
const browser = await ensureBrowser();
|
||||
const puppeteer = await import("puppeteer-core");
|
||||
const chromeBrowser = await puppeteer.default.launch({
|
||||
headless: true,
|
||||
executablePath: browser.executablePath,
|
||||
args: [
|
||||
"--no-sandbox",
|
||||
"--disable-dev-shm-usage",
|
||||
"--enable-webgl",
|
||||
"--use-gl=angle",
|
||||
"--use-angle=swiftshader",
|
||||
],
|
||||
});
|
||||
|
||||
// Start a minimal file server for the project
|
||||
const { createServer } = await import("node:http");
|
||||
const { extname } = await import("node:path");
|
||||
|
||||
const mimeTypes: Record<string, string> = {
|
||||
".html": "text/html",
|
||||
".css": "text/css",
|
||||
".js": "application/javascript",
|
||||
".json": "application/json",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".svg": "image/svg+xml",
|
||||
".woff2": "font/woff2",
|
||||
".woff": "font/woff",
|
||||
".ttf": "font/ttf",
|
||||
".mp4": "video/mp4",
|
||||
".webm": "video/webm",
|
||||
".wav": "audio/wav",
|
||||
".mp3": "audio/mpeg",
|
||||
};
|
||||
const getMimeType = (p: string) =>
|
||||
mimeTypes[extname(p).toLowerCase()] || "application/octet-stream";
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
const url = decodeURIComponent(req.url ?? "/");
|
||||
const filePath = join(projectDir, url === "/" ? "index.html" : url);
|
||||
if (existsSync(filePath)) {
|
||||
let content = readFileSync(filePath);
|
||||
let contentType = getMimeType(filePath);
|
||||
|
||||
// For composition HTML files: unwrap <template> for standalone rendering
|
||||
if (filePath.endsWith(".html") && filePath.includes("compositions")) {
|
||||
let html = content.toString("utf-8");
|
||||
// Replace <template id="..."> with <div> and </template> with </div>
|
||||
// so the content actually renders in the browser
|
||||
html = html.replace(/<template\s+id="[^"]*">/gi, "<div>");
|
||||
html = html.replace(/<\/template>/gi, "</div>");
|
||||
// Wrap in a basic HTML document
|
||||
html = `<!DOCTYPE html><html><head><meta charset="utf-8"></head><body style="margin:0;padding:0;background:#000;width:1920px;height:1080px;overflow:hidden">${html}</body></html>`;
|
||||
content = Buffer.from(html, "utf-8");
|
||||
}
|
||||
|
||||
res.writeHead(200, { "Content-Type": contentType });
|
||||
res.end(content);
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
|
||||
const port = await new Promise<number>((resolvePort) => {
|
||||
server.listen(0, () => {
|
||||
const addr = server.address();
|
||||
resolvePort(typeof addr === "object" && addr ? addr.port : 0);
|
||||
});
|
||||
});
|
||||
|
||||
const results: SectionVerification[] = [];
|
||||
|
||||
try {
|
||||
for (let i = 0; i < sections.length; i++) {
|
||||
const section = sections[i];
|
||||
progress(`Verifying ${section.id} (${i + 1}/${sections.length})`);
|
||||
|
||||
const verification = await verifySection(
|
||||
chromeBrowser,
|
||||
port,
|
||||
section,
|
||||
projectDir,
|
||||
screenshots,
|
||||
i,
|
||||
);
|
||||
results.push(verification);
|
||||
}
|
||||
} finally {
|
||||
await chromeBrowser.close();
|
||||
server.close();
|
||||
}
|
||||
|
||||
const summary = {
|
||||
total: results.length,
|
||||
passed: results.filter((r) => r.status === "passed").length,
|
||||
failed: results.filter((r) => r.status === "failed").length,
|
||||
fallback: results.filter((r) => r.status === "fallback").length,
|
||||
};
|
||||
|
||||
// Write report
|
||||
const report: VerifyResult = { sections: results, summary };
|
||||
writeFileSync(join(projectDir, "capture-report.json"), JSON.stringify(report, null, 2), "utf-8");
|
||||
|
||||
// Update section results with verification status
|
||||
for (const r of results) {
|
||||
const section = sections.find((s) => s.id === r.id);
|
||||
if (section) {
|
||||
section.verified = r.status === "passed";
|
||||
section.fallback = r.status === "fallback" ? "screenshot" : "none";
|
||||
section.screenshotPath = r.sourceScreenshot;
|
||||
}
|
||||
}
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
async function verifySection(
|
||||
browser: any,
|
||||
port: number,
|
||||
section: SectionResult,
|
||||
projectDir: string,
|
||||
screenshots: string[],
|
||||
index: number,
|
||||
): Promise<SectionVerification> {
|
||||
const errors: string[] = [];
|
||||
const compositionUrl = `http://127.0.0.1:${port}/${section.compositionPath}`;
|
||||
|
||||
// Find the best matching source screenshot for this section
|
||||
const sourceScreenshot = screenshots[Math.min(index, screenshots.length - 1)];
|
||||
|
||||
const page = await browser.newPage();
|
||||
await page.setViewport({ width: 1920, height: 1080 });
|
||||
|
||||
// Collect console errors
|
||||
page.on("console", (msg: any) => {
|
||||
if (msg.type() === "error") {
|
||||
const text = msg.text();
|
||||
if (!text.includes("favicon") && !text.includes("Failed to load resource")) {
|
||||
errors.push(text.slice(0, 200));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
page.on("pageerror", (err: any) => {
|
||||
errors.push(String(err).slice(0, 200));
|
||||
});
|
||||
|
||||
try {
|
||||
await page.goto(compositionUrl, {
|
||||
waitUntil: "domcontentloaded",
|
||||
timeout: 10000,
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
|
||||
// Take screenshot of rendered section
|
||||
const renderedPath = `screenshots/verify-${section.id}.png`;
|
||||
await page.screenshot({
|
||||
path: join(projectDir, renderedPath),
|
||||
type: "png",
|
||||
});
|
||||
|
||||
// Force all elements visible (composition starts with opacity:0 for GSAP)
|
||||
await page.evaluate(`(() => {
|
||||
document.querySelectorAll('*').forEach(function(el) {
|
||||
var s = getComputedStyle(el);
|
||||
if (s.opacity === '0') el.style.opacity = '1';
|
||||
if (s.visibility === 'hidden') el.style.visibility = 'visible';
|
||||
});
|
||||
})()`);
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
|
||||
// Re-take screenshot with elements visible
|
||||
await page.screenshot({
|
||||
path: join(projectDir, renderedPath),
|
||||
type: "png",
|
||||
});
|
||||
|
||||
// Check if the screenshot has actual visual content (not just black/white)
|
||||
// Use a simple pixel sampling approach via CDP
|
||||
const cdpSession = await page.createCDPSession();
|
||||
const screenshotResult = await cdpSession.send("Page.captureScreenshot", {
|
||||
format: "jpeg",
|
||||
quality: 10, // Low quality for fast analysis
|
||||
fromSurface: true,
|
||||
});
|
||||
await cdpSession.detach();
|
||||
|
||||
const imgBuffer = Buffer.from(screenshotResult.data, "base64");
|
||||
// A mostly-black or mostly-white image will be very small at low quality
|
||||
const isVisuallyEmpty = imgBuffer.length < 2000;
|
||||
|
||||
// Also check DOM content as secondary signal
|
||||
const pageInfo = (await page.evaluate(`(() => {
|
||||
var body = document.body || document.documentElement;
|
||||
var text = (body.innerText || '').trim();
|
||||
var imgs = document.querySelectorAll('img[src]').length;
|
||||
var svgs = document.querySelectorAll('svg').length;
|
||||
return {
|
||||
textLength: text.length,
|
||||
imageCount: imgs,
|
||||
svgCount: svgs,
|
||||
hasContent: text.length > 20 || imgs > 0 || svgs > 0,
|
||||
};
|
||||
})()`)) as { textLength: number; imageCount: number; svgCount: number; hasContent: boolean };
|
||||
|
||||
await page.close();
|
||||
|
||||
// Determine status — must have BOTH DOM content AND visual pixels
|
||||
if (isVisuallyEmpty && !pageInfo.hasContent) {
|
||||
errors.push("Section appears visually empty");
|
||||
return {
|
||||
id: section.id,
|
||||
compositionPath: section.compositionPath,
|
||||
status: "failed",
|
||||
errors,
|
||||
renderedScreenshot: renderedPath,
|
||||
sourceScreenshot,
|
||||
};
|
||||
}
|
||||
|
||||
if (isVisuallyEmpty) {
|
||||
errors.push("Section has DOM content but renders as blank (CSS issue)");
|
||||
return {
|
||||
id: section.id,
|
||||
compositionPath: section.compositionPath,
|
||||
status: "failed",
|
||||
errors,
|
||||
renderedScreenshot: renderedPath,
|
||||
sourceScreenshot,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
id: section.id,
|
||||
compositionPath: section.compositionPath,
|
||||
status: errors.length > 3 ? "failed" : "passed",
|
||||
errors,
|
||||
renderedScreenshot: renderedPath,
|
||||
sourceScreenshot,
|
||||
};
|
||||
} catch (err) {
|
||||
errors.push(`Load failed: ${err}`);
|
||||
await page.close().catch(() => {});
|
||||
return {
|
||||
id: section.id,
|
||||
compositionPath: section.compositionPath,
|
||||
status: "failed",
|
||||
errors,
|
||||
sourceScreenshot,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@ const subCommands = {
|
||||
skills: () => import("./commands/skills.js").then((m) => m.default),
|
||||
telemetry: () => import("./commands/telemetry.js").then((m) => m.default),
|
||||
validate: () => import("./commands/validate.js").then((m) => m.default),
|
||||
capture: () => import("./commands/capture.js").then((m) => m.default),
|
||||
};
|
||||
|
||||
const main = defineCommand({
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import { defineCommand } from "citty";
|
||||
import { resolve } from "node:path";
|
||||
import type { Example } from "./_examples.js";
|
||||
|
||||
export const examples: Example[] = [
|
||||
["Capture a website", "hyperframes capture https://stripe.com"],
|
||||
[
|
||||
"Capture to a specific directory",
|
||||
"hyperframes capture https://linear.app -o linear-components",
|
||||
],
|
||||
["Capture without asset downloads", "hyperframes capture https://vercel.com --skip-assets"],
|
||||
["JSON output for AI agents", "hyperframes capture https://example.com --json"],
|
||||
];
|
||||
|
||||
export default defineCommand({
|
||||
meta: {
|
||||
name: "capture",
|
||||
description: "Capture a website as editable HyperFrames components",
|
||||
},
|
||||
args: {
|
||||
url: {
|
||||
type: "positional",
|
||||
description: "Website URL to capture",
|
||||
required: true,
|
||||
},
|
||||
output: {
|
||||
type: "string",
|
||||
description: "Output directory name",
|
||||
alias: "o",
|
||||
},
|
||||
"skip-assets": {
|
||||
type: "boolean",
|
||||
description: "Skip downloading assets (images, SVGs)",
|
||||
default: false,
|
||||
},
|
||||
"skip-split": {
|
||||
type: "boolean",
|
||||
description: "Skip section splitting (capture only)",
|
||||
default: false,
|
||||
},
|
||||
"skip-verify": {
|
||||
type: "boolean",
|
||||
description: "Skip section verification",
|
||||
default: false,
|
||||
},
|
||||
"max-screenshots": {
|
||||
type: "string",
|
||||
description: "Maximum screenshots to capture (default: 24)",
|
||||
},
|
||||
"max-sections": {
|
||||
type: "string",
|
||||
description: "Maximum sections to extract (default: 12)",
|
||||
},
|
||||
timeout: {
|
||||
type: "string",
|
||||
description: "Page load timeout in ms (default: 30000)",
|
||||
},
|
||||
json: {
|
||||
type: "boolean",
|
||||
description: "Output JSON (for AI agents / programmatic use)",
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
async run({ args }) {
|
||||
const url = args.url as string;
|
||||
|
||||
// Validate URL
|
||||
try {
|
||||
new URL(url);
|
||||
} catch {
|
||||
console.error(`Invalid URL: ${url}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Determine output directory
|
||||
let outputName = args.output as string | undefined;
|
||||
if (!outputName) {
|
||||
const hostname = new URL(url).hostname.replace(/^www\./, "");
|
||||
outputName = hostname.replace(/\./g, "-") + "-capture";
|
||||
}
|
||||
const outputDir = resolve(outputName);
|
||||
|
||||
const isJson = args.json as boolean;
|
||||
|
||||
if (!isJson) {
|
||||
const { c } = await import("../ui/colors.js");
|
||||
console.log();
|
||||
console.log(c.dim("◆") + " Capturing " + c.bold(url));
|
||||
console.log();
|
||||
}
|
||||
|
||||
const { captureWebsite } = await import("../capture/index.js");
|
||||
|
||||
try {
|
||||
const result = await captureWebsite(
|
||||
{
|
||||
url,
|
||||
outputDir,
|
||||
skipAssets: args["skip-assets"] as boolean,
|
||||
skipSplit: args["skip-split"] as boolean,
|
||||
skipVerify: args["skip-verify"] as boolean,
|
||||
maxScreenshots: args["max-screenshots"]
|
||||
? parseInt(args["max-screenshots"] as string)
|
||||
: undefined,
|
||||
maxSections: args["max-sections"] ? parseInt(args["max-sections"] as string) : undefined,
|
||||
timeout: args.timeout ? parseInt(args.timeout as string) : undefined,
|
||||
json: isJson,
|
||||
},
|
||||
isJson
|
||||
? undefined
|
||||
: (stage: string, detail?: string) => {
|
||||
const stages: Record<string, string> = {
|
||||
browser: " Launching browser...",
|
||||
navigate: " Loading page...",
|
||||
extract: " Extracting HTML & CSS...",
|
||||
tokens: " Extracting design tokens...",
|
||||
screenshots: " Capturing screenshots...",
|
||||
assets: " Downloading assets...",
|
||||
style: " Generating visual style...",
|
||||
done: " Done",
|
||||
};
|
||||
const label = stages[stage] || ` ${stage}`;
|
||||
console.log(detail ? `${label} ${detail}` : label);
|
||||
},
|
||||
);
|
||||
|
||||
if (isJson) {
|
||||
// Output structured JSON for Claude Code / programmatic use
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
ok: result.ok,
|
||||
projectDir: result.projectDir,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
screenshots: result.screenshots.length,
|
||||
assets: result.assets.length,
|
||||
detectedSections: result.tokens.sections.length,
|
||||
compositions: result.sections?.length ?? 0,
|
||||
fonts: result.tokens.fonts,
|
||||
animations: result.animationCatalog?.summary,
|
||||
warnings: result.warnings,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
const { c } = await import("../ui/colors.js");
|
||||
console.log();
|
||||
console.log(c.success("◇") + ` Captured ${c.bold(result.title)} → ${c.dim(outputDir)}`);
|
||||
console.log();
|
||||
console.log(` ${c.dim("Screenshots:")} ${result.screenshots.length}`);
|
||||
console.log(` ${c.dim("Assets:")} ${result.assets.length}`);
|
||||
console.log(` ${c.dim("Sections:")} ${result.tokens.sections.length}`);
|
||||
console.log(` ${c.dim("Fonts:")} ${result.tokens.fonts.join(", ")}`);
|
||||
if (result.warnings.length > 0) {
|
||||
console.log();
|
||||
for (const w of result.warnings) {
|
||||
console.log(` ${c.warn("⚠")} ${w}`);
|
||||
}
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
} catch (err) {
|
||||
if (isJson) {
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
ok: false,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
console.error(`\n ✗ Capture failed: ${err}\n`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
},
|
||||
});
|
||||
Generated
+2406
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,154 @@
|
||||
---
|
||||
name: website-to-hyperframes
|
||||
description: |
|
||||
Capture a website and build a HyperFrames video project from it. Use this skill whenever: (1) a user provides a URL and wants to create a video from it, (2) someone says "website to hyperframes", "capture this site", "turn this into a video", "make a promo from my site", (3) the user wants video components from an existing website, (4) the user shares a link and asks for any kind of video. Even if the user just pastes a URL — this is the skill to use.
|
||||
---
|
||||
|
||||
# Website to HyperFrames
|
||||
|
||||
Capture a website's design (screenshots, colors, fonts, text, animations, assets), then build a clean HyperFrames video project from scratch using that design data.
|
||||
|
||||
## How It Works
|
||||
|
||||
**Phase 1: Capture** — CLI extracts everything from the website into a data folder
|
||||
**Phase 2: Build** — You read the design brief + screenshots and build compositions from scratch using the `/hyperframes` compose skill
|
||||
|
||||
The capture produces a `capture-brief.md` file formatted exactly like a detailed video prompt — with hex colors, font names, exact text, animation timing. You read this brief, look at the screenshots, and build compositions the same way you'd build from a test prompt.
|
||||
|
||||
## Execution Rules
|
||||
|
||||
Every step has an **OUTPUT GATE**. Print the required output before proceeding.
|
||||
|
||||
## Step 1: Capture the website
|
||||
|
||||
```bash
|
||||
npx hyperframes capture --help 2>/dev/null && npx hyperframes capture <URL> -o <project-name> || npx tsx packages/cli/src/cli.ts capture <URL> -o <project-name>
|
||||
```
|
||||
|
||||
**OUTPUT GATE**: Print the capture output (sections, screenshots, assets, fonts).
|
||||
|
||||
✅ Step 1 complete
|
||||
|
||||
## Step 2: Read the design brief
|
||||
|
||||
Read these files:
|
||||
|
||||
1. `<project>/capture-brief.md` — **THE MAIN DESIGN SPEC.** This is your blueprint.
|
||||
2. `<project>/visual-style.md` — brand colors, fonts, mood
|
||||
|
||||
**OUTPUT GATE**: Print a summary:
|
||||
|
||||
```
|
||||
| Info | Value |
|
||||
|------|-------|
|
||||
| Sections | [N content sections from the brief] |
|
||||
| Colors | [primary hex colors] |
|
||||
| Fonts | [font names + local files if any] |
|
||||
| Assets | [N images, N SVGs] |
|
||||
| Suggested duration | [Ns] |
|
||||
```
|
||||
|
||||
✅ Step 2 complete
|
||||
|
||||
## Step 3: Study each section screenshot
|
||||
|
||||
For each section in the brief, **READ its screenshot image**. Describe:
|
||||
|
||||
- Layout (columns, grid, centered, sidebar)
|
||||
- Key visual elements (hero image, cards, logo bar, chart)
|
||||
- Color usage (dark bg with light text, gradient, etc.)
|
||||
- Overall feel (minimal, busy, corporate, playful)
|
||||
|
||||
**OUTPUT GATE**: Print a description table:
|
||||
|
||||
```
|
||||
| Section | Screenshot | Layout | Key Elements | Mood |
|
||||
|---------|-----------|--------|-------------|------|
|
||||
| Meet the night shift | section-00.png | Centered hero, dark navy bg | h1, 2 CTAs, agent icons, logo bar | Bold, techy |
|
||||
| Keep work moving | section-03.png | ... | ... | ... |
|
||||
| ... | ... | ... | ... | ... |
|
||||
```
|
||||
|
||||
Decide which sections to include/skip (navbar-only and footer-only sections → skip).
|
||||
|
||||
✅ Step 3 complete
|
||||
|
||||
## Step 4: Build the HyperFrames project
|
||||
|
||||
**Invoke `/hyperframes` BEFORE writing any composition code.**
|
||||
|
||||
1. Create a new project: `npx hyperframes init <new-project-name>`
|
||||
2. For each section you're keeping, build a scene in the composition
|
||||
3. Use **exact values from the brief**: hex colors, font names, heading text, CTA text
|
||||
4. Use **screenshots as visual reference**: match the layout, spacing, element arrangement
|
||||
5. Reference **`<capture-project>/assets/`** for downloaded images and SVGs
|
||||
6. Apply GSAP animations using timing from the brief's "Animations" data
|
||||
|
||||
**Key rules for building:**
|
||||
|
||||
- **Clean HTML/CSS from scratch** — do NOT copy the 800KB extracted HTML
|
||||
- **Match the screenshot** — your composition should look like the screenshot
|
||||
- **Use exact brand values** — hex colors from the brief, not approximations
|
||||
- **Reference local assets** — `<capture-project>/assets/image-0.jpg`, not remote URLs
|
||||
- **Font loading** — use `@font-face` with local font files if listed in the brief, or Google Fonts CDN
|
||||
- **Composition size** — each section should be ~5-20KB, not 800KB
|
||||
|
||||
**Animation guidance** — read [animation-recreation.md](./references/animation-recreation.md) for converting the source site's animation data to GSAP. The brief lists what animations the original site used per section.
|
||||
|
||||
**OUTPUT GATE**: Print what was built:
|
||||
|
||||
```
|
||||
| Scene | Duration | Elements | Animations |
|
||||
|-------|----------|----------|-----------|
|
||||
| Hero | 5s | h1, 2 CTAs, logo bar | heading slide-up, CTAs stagger, logos marquee |
|
||||
| Features | 5s | h2, 3 bento cards | cards stagger entrance, images scale-in |
|
||||
| ... | ... | ... | ... |
|
||||
```
|
||||
|
||||
✅ Step 4 complete
|
||||
|
||||
## Step 5: Lint, validate, preview
|
||||
|
||||
```bash
|
||||
npx hyperframes lint <new-project-name>
|
||||
npx hyperframes validate <new-project-name>
|
||||
```
|
||||
|
||||
Fix ALL errors before previewing.
|
||||
|
||||
```bash
|
||||
npx hyperframes preview <new-project-name>
|
||||
```
|
||||
|
||||
**Note:** Use `npx hyperframes preview` (built CLI), not `npx tsx ... preview`.
|
||||
|
||||
**OUTPUT GATE**: Print final summary:
|
||||
|
||||
```
|
||||
## Ready
|
||||
- Preview: http://localhost:XXXX
|
||||
- Scenes: N built from website capture
|
||||
- Duration: Ns total
|
||||
- Source: <URL>
|
||||
- Next steps: customize, add narration, render to MP4
|
||||
```
|
||||
|
||||
✅ Step 5 complete
|
||||
|
||||
## Key Rules
|
||||
|
||||
1. **Brief is your design spec, screenshots are your visual spec.** Read both.
|
||||
2. **Build from scratch, don't edit extracted HTML.** Clean 5-20KB compositions, not 800KB HTML files.
|
||||
3. **Use exact values.** Hex colors, font names, text content — all from the brief.
|
||||
4. **Reference local assets.** Use `assets/image-0.jpg`, not remote CDN URLs.
|
||||
5. **Invoke `/hyperframes`** before writing any composition code — it has the guardrails.
|
||||
6. **Match the screenshot layout.** Columns, spacing, element positions should feel like the original.
|
||||
|
||||
## Reference Files
|
||||
|
||||
| File | When to read |
|
||||
| --------------------------------------------------------------- | -------------------------------------------------- |
|
||||
| [animation-recreation.md](./references/animation-recreation.md) | Step 4 — converting source animations to GSAP |
|
||||
| [section-refinement.md](./references/section-refinement.md) | Step 4 — tips for building from brief + screenshot |
|
||||
| [video-recipes.md](./references/video-recipes.md) | Building videos — scene patterns |
|
||||
| [tts-integration.md](./references/tts-integration.md) | Adding narration |
|
||||
@@ -0,0 +1,145 @@
|
||||
# Animation Recreation
|
||||
|
||||
How to use `extracted/animations.json` to recreate website animations in GSAP.
|
||||
|
||||
## Reading the Animation Catalog
|
||||
|
||||
The catalog has four data sources. Use them together:
|
||||
|
||||
### 1. Web Animations (`webAnimations`)
|
||||
|
||||
Full keyframe data from `document.getAnimations()`. Each entry has:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "Animation",
|
||||
"targetSelector": "div.payments-graphic__terminal-pay-label-values",
|
||||
"keyframes": [
|
||||
{ "offset": 0, "transform": "translateY(0%)" },
|
||||
{ "offset": 0.7, "transform": "translateY(-100%)" },
|
||||
{ "offset": 1, "transform": "translateY(-100%)" }
|
||||
],
|
||||
"timing": {
|
||||
"duration": 1420,
|
||||
"delay": 4000,
|
||||
"iterations": 1,
|
||||
"easing": "linear",
|
||||
"direction": "normal"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Convert to GSAP:**
|
||||
|
||||
```javascript
|
||||
tl.fromTo(
|
||||
"#target",
|
||||
{ y: "0%" },
|
||||
{ y: "-100%", duration: 1.42, delay: 4, ease: "none" },
|
||||
startTime,
|
||||
);
|
||||
```
|
||||
|
||||
### 2. Scroll Targets (`scrollTargets`)
|
||||
|
||||
Elements that had `IntersectionObserver` watching them — these are scroll-triggered animations:
|
||||
|
||||
```json
|
||||
{
|
||||
"selector": "div.lazy-animation.lazy-bento-graphic",
|
||||
"rect": { "top": 1149, "height": 0, "width": 1392 }
|
||||
}
|
||||
```
|
||||
|
||||
**How to use:** These elements should have entrance animations that trigger when the scene plays. Use the `rect.top` value to determine which scene contains this element, then add a staggered entrance:
|
||||
|
||||
```javascript
|
||||
tl.fromTo(
|
||||
"#bento-graphic",
|
||||
{ opacity: 0, y: 30 },
|
||||
{ opacity: 1, y: 0, duration: 0.6, ease: "back.out(1.3)" },
|
||||
0.5,
|
||||
);
|
||||
```
|
||||
|
||||
### 3. CSS Declarations (`cssDeclarations`)
|
||||
|
||||
Elements with `animation` or `transition` CSS properties:
|
||||
|
||||
```json
|
||||
{
|
||||
"selector": "button.hds-button",
|
||||
"transition": { "property": "background-color, color, border", "duration": "0.3s" }
|
||||
}
|
||||
```
|
||||
|
||||
These are mostly hover effects — less useful for video. Focus on elements with `animation` (not just `transition`).
|
||||
|
||||
### 4. CDP Events (`cdpAnimations`)
|
||||
|
||||
Real-time animation events captured during page scroll. Useful for understanding the overall animation density and timing:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "WebAnimation",
|
||||
"name": "",
|
||||
"duration": 325,
|
||||
"delay": 50
|
||||
}
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Logo carousel (horizontal scroll)
|
||||
|
||||
If scroll targets include a `.logo-carousel` element, add a horizontal scroll animation:
|
||||
|
||||
```javascript
|
||||
tl.fromTo("#logo-row", { x: 0 }, { x: -200, duration: 8, ease: "none", repeat: -1 }, 0);
|
||||
```
|
||||
|
||||
### Staggered card entrance
|
||||
|
||||
For bento grids or feature cards:
|
||||
|
||||
```javascript
|
||||
tl.fromTo(
|
||||
".feature-card",
|
||||
{ opacity: 0, y: 40 },
|
||||
{ opacity: 1, y: 0, duration: 0.5, stagger: 0.15, ease: "power2.out" },
|
||||
0.3,
|
||||
);
|
||||
```
|
||||
|
||||
### Counter animation
|
||||
|
||||
For stat numbers:
|
||||
|
||||
```javascript
|
||||
var obj = { val: 0 };
|
||||
tl.to(
|
||||
obj,
|
||||
{
|
||||
val: 135,
|
||||
duration: 1.5,
|
||||
ease: "power2.out",
|
||||
onUpdate: function () {
|
||||
document.querySelector("#stat").textContent = Math.round(obj.val) + "+";
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
);
|
||||
```
|
||||
|
||||
### Typing effect
|
||||
|
||||
For code blocks or terminal mockups:
|
||||
|
||||
```javascript
|
||||
tl.fromTo(
|
||||
".code-line",
|
||||
{ opacity: 0, y: 8 },
|
||||
{ opacity: 1, y: 0, duration: 0.25, stagger: 0.3, ease: "power2.out" },
|
||||
0.5,
|
||||
);
|
||||
```
|
||||
@@ -0,0 +1,100 @@
|
||||
# Building from Brief + Screenshot
|
||||
|
||||
Tips for building HyperFrames compositions from the capture brief and screenshots.
|
||||
|
||||
## The Workflow
|
||||
|
||||
1. Read the section's entry in `capture-brief.md` for exact data
|
||||
2. Read the section's screenshot for visual layout
|
||||
3. Build clean HTML/CSS that recreates the design
|
||||
4. Add GSAP animations using timing from the brief
|
||||
|
||||
## Matching the Screenshot
|
||||
|
||||
### Layout
|
||||
|
||||
- Count columns in the screenshot. If you see 3 cards side by side → use CSS grid or flexbox with 3 columns
|
||||
- Check alignment: centered text, left-aligned content, split layouts
|
||||
- Note spacing: are elements tightly packed or breathing with margins?
|
||||
|
||||
### Colors
|
||||
|
||||
- Use exact hex values from the brief, not visual approximations
|
||||
- Check background: solid color, gradient, or image?
|
||||
- Note color contrast: light text on dark, dark text on light
|
||||
|
||||
### Typography
|
||||
|
||||
- Use the font from the brief (check `visual-style.md`)
|
||||
- Match heading sizes: hero headings are typically 48-72px, sub-headings 24-36px
|
||||
- Match weight: bold headings (700-900), regular body (400)
|
||||
|
||||
### Images & Assets
|
||||
|
||||
- Use downloaded assets from `assets/` (images, SVGs, favicon)
|
||||
- Reference by relative path: `../notion/assets/image-0.jpg`
|
||||
- If an image wasn't captured, use a CSS gradient or shape placeholder
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
### Building too literally
|
||||
|
||||
Don't try to recreate every pixel. Focus on the **essence**: headline, key visual, CTA, color scheme. A 5-second video scene only shows so much.
|
||||
|
||||
### Ignoring the brief's animation data
|
||||
|
||||
The brief lists what animations the original site used (entrance duration, easing). Use these values instead of inventing generic ones.
|
||||
|
||||
### Missing brand colors
|
||||
|
||||
Every section in the brief has a background color. Use it. Don't default to white or black unless the brief says so.
|
||||
|
||||
### Wrong font
|
||||
|
||||
Check if local font files exist in `assets/fonts/`. If yes, add `@font-face` declarations. If not, use Google Fonts or a system font that matches the style.
|
||||
|
||||
### Referencing remote URLs
|
||||
|
||||
Use local asset paths, not `https://notion.com/...`. The capture downloaded assets for offline use.
|
||||
|
||||
## When to Simplify
|
||||
|
||||
**Match exactly:**
|
||||
|
||||
- Heading text, font, color
|
||||
- Background color/gradient
|
||||
- CTA button text and colors
|
||||
- Overall layout (grid vs stacked vs centered)
|
||||
|
||||
**OK to simplify:**
|
||||
|
||||
- Complex nested card layouts → capture the visual essence
|
||||
- Decorative SVG illustrations → use a simpler CSS shape or skip
|
||||
- Hover states, interactive elements → not relevant for video
|
||||
- Cookie banners, popups, navigation → skip
|
||||
|
||||
## Screenshot Fallback
|
||||
|
||||
If a section is too complex to rebuild (e.g., 3D WebGL visualization), use the screenshot as a background:
|
||||
|
||||
```html
|
||||
<div style="position: absolute; inset: 0;">
|
||||
<img
|
||||
src="../capture-project/screenshots/section-03.png"
|
||||
style="width: 100%; height: 100%; object-fit: cover;"
|
||||
/>
|
||||
</div>
|
||||
```
|
||||
|
||||
Then animate on top of it (text overlays, motion graphics).
|
||||
|
||||
## Quality Checklist
|
||||
|
||||
Before considering a section done:
|
||||
|
||||
- [ ] Visually matches the screenshot (layout, colors, spacing)
|
||||
- [ ] Uses exact brand colors from the brief
|
||||
- [ ] Uses exact heading/CTA text from the brief
|
||||
- [ ] References local assets (not remote URLs)
|
||||
- [ ] Has meaningful GSAP animations (not just fade in/out)
|
||||
- [ ] Passes `npx hyperframes lint`
|
||||
@@ -0,0 +1,228 @@
|
||||
# TTS Integration
|
||||
|
||||
How to add narrated voiceover to a website-to-hyperframes composition.
|
||||
|
||||
## When to Use TTS
|
||||
|
||||
**Narration is the default for ALL video types.** Silent videos feel like slideshows. Generate voiceover unless the user explicitly says "no narration" or "no voiceover."
|
||||
|
||||
- **Explainer videos** — always narrated, longest script
|
||||
- **Product promos** — always narrated, punchy copy
|
||||
- **Social clips** — narrated with bold captions, short and energetic
|
||||
- **Launch announcements** — brief narration adds drama and polish
|
||||
|
||||
## Step 1: Write the Narration Script
|
||||
|
||||
**Write like a human product demo narrator, NOT marketing copy.** The script should feel like someone casually but enthusiastically showing you a product — not reading a press release.
|
||||
|
||||
### The #1 Rule: Conversational Tone
|
||||
|
||||
**BAD (corporate copy — sounds robotic when spoken):**
|
||||
|
||||
> "Stripe is the financial infrastructure that powers the internet. Accept payments, manage subscriptions, and build custom revenue models."
|
||||
|
||||
**GOOD (product demo — sounds natural when spoken):**
|
||||
|
||||
> "So this is Stripe — basically the backbone behind how the internet handles money. You can take payments, set up subscriptions, build out billing... all from one platform."
|
||||
|
||||
**BAD (bullet point narration):**
|
||||
|
||||
> "Trusted by millions of businesses worldwide, from startups to Fortune 500 companies."
|
||||
|
||||
**GOOD (conversational):**
|
||||
|
||||
> "And it's not just startups using this — Google's on here, Shopify, Coinbase, Amazon... pretty much everyone."
|
||||
|
||||
### Script Writing Rules
|
||||
|
||||
- **2.5 words per second** is natural speaking pace. 30s video = 75 words, 60s = 150 words.
|
||||
- **Start with energy** — first sentence should hook, not inform. "So this is..." or "Check this out..." or "Meet [product]..."
|
||||
- **Use contractions** — "it's" not "it is", "you'll" not "you will", "that's" not "that is"
|
||||
- **Use filler words sparingly but intentionally** — "basically", "pretty much", "honestly" make it human
|
||||
- **Vary sentence length** — mix short punchy phrases with longer ones
|
||||
- **Add pauses with punctuation** — "And the uptime? Ninety nine point nine percent." The question mark creates a natural pause.
|
||||
- **End with casual CTA** — "Check it out at stripe dot com" not "Get started at stripe dot com"
|
||||
- **Don't list features** — tell a story. "You set up payments, and then it just... handles everything" vs "Accept payments, manage subscriptions, build revenue models"
|
||||
|
||||
**Natural pronunciation — write numbers as people actually say them:**
|
||||
|
||||
| On the website | Write in script as | Why |
|
||||
| -------------- | --------------------------------- | --------------------------------------------------------- |
|
||||
| 135+ | more than one hundred thirty five | nobody says "one hundred thirty five plus" |
|
||||
| $1.9T | nearly two trillion dollars | round it, sound natural |
|
||||
| 99.999% | ninety nine point nine percent | simplify for speech — the extra nines are unpronounceable |
|
||||
| 200M+ | over two hundred million | "plus" sounds robotic |
|
||||
| 24/7 | twenty four seven | standard spoken form |
|
||||
| 10x | ten times | spell out multipliers |
|
||||
| API | A P I | spell out acronyms |
|
||||
| stripe.com | stripe dot com | spell out URLs |
|
||||
| Fortune 500 | Fortune five hundred | spell out numbers in names |
|
||||
|
||||
The TTS engine reads what you write literally. "99.999%" becomes "ninety nine point nine nine nine percent" which sounds ridiculous. Simplify numbers for natural speech — the visual on screen can show the exact figure while the voice rounds it.
|
||||
|
||||
Save the script as `narration-script.txt` in the project directory.
|
||||
|
||||
## Step 2: Generate TTS Audio
|
||||
|
||||
Three options, in order of recommendation:
|
||||
|
||||
### Voice Selection: Audition Before Committing
|
||||
|
||||
**Never use the first voice you find.** Always audition 2-3 voices with a short test phrase before generating the full narration.
|
||||
|
||||
#### Audition Process (Required)
|
||||
|
||||
1. **Search for voices** that match the brand tone:
|
||||
- Use `mcp__elevenlabs__search_voices` with descriptive terms: "warm conversational", "friendly narrator", "product demo"
|
||||
- Use `mcp__claude_ai_HeyGen__list_audio_voices` to browse HeyGen options
|
||||
2. **Generate a test clip** with a short excerpt (first sentence of the script) using 2-3 different voices
|
||||
3. **Pick the one that sounds most natural and conversational** — not the most "professional" or "polished"
|
||||
|
||||
#### What to listen for:
|
||||
|
||||
- **Natural breathing/pauses** — robotic voices have unnaturally even pacing
|
||||
- **Emphasis variation** — good voices stress important words naturally
|
||||
- **Warmth** — the voice should sound like someone talking TO you, not AT you
|
||||
- **Speed** — slightly faster than news-anchor pace, like a friend explaining something cool
|
||||
|
||||
### Option A: HeyGen TTS (Always Available)
|
||||
|
||||
HeyGen TTS is available via MCP and returns word-level timestamps automatically. **Use this as the primary option.**
|
||||
|
||||
```
|
||||
Tool: mcp__claude_ai_HeyGen__text_to_speech
|
||||
Input:
|
||||
text: "[narration script]"
|
||||
voiceId: "[pick based on audition]"
|
||||
speed: 1.0 (adjust 0.9-1.1 based on content)
|
||||
```
|
||||
|
||||
This returns an audio URL + word timestamps. Download the audio:
|
||||
|
||||
```bash
|
||||
curl -o narration.wav "[audio_url]"
|
||||
```
|
||||
|
||||
**Audition process:**
|
||||
|
||||
1. Use `mcp__claude_ai_HeyGen__list_audio_voices` with `language: "English"` to browse voices
|
||||
2. Look for voices described as "Chill", "Smooth", "Relaxed", "Charming" — avoid "Professional", "Dominant", "Firm"
|
||||
3. Generate test clips with 2-3 candidates using a short excerpt of the script
|
||||
4. Pick the most natural, conversational one
|
||||
|
||||
**Good HeyGen voices for product demos:** Chill Brian, Smooth Dev, Charming Charles, Relaxed Reece
|
||||
|
||||
### Option B: ElevenLabs TTS (If Available — Better Voice Quality)
|
||||
|
||||
If the ElevenLabs MCP server is installed (`mcp__elevenlabs__*` tools), use it for wider voice variety and more natural-sounding output:
|
||||
|
||||
```
|
||||
Tool: mcp__elevenlabs__search_voices
|
||||
Input: query "warm conversational narrator"
|
||||
|
||||
Then:
|
||||
Tool: mcp__elevenlabs__text_to_speech
|
||||
Input:
|
||||
text: "[narration script]"
|
||||
voice_id: "[from search results]"
|
||||
```
|
||||
|
||||
Note: ElevenLabs does NOT return word timestamps — you'll need to transcribe the audio separately (Step 3). ElevenLabs MCP may not be available in all environments.
|
||||
|
||||
### Option C: Local Kokoro TTS (Offline Fallback)
|
||||
|
||||
Only use Kokoro if MCP TTS tools are unavailable. Kokoro voices are functional but less expressive.
|
||||
|
||||
```bash
|
||||
npx hyperframes tts narration-script.txt --voice af_nova --output narration.wav --speed 0.95
|
||||
```
|
||||
|
||||
Best Kokoro voices:
|
||||
| Content | Voice | Why |
|
||||
|---------|-------|-----|
|
||||
| Product demo | `af_nova` | Warmest of the available options |
|
||||
| Tutorial | `bf_emma` | Clear, natural pacing |
|
||||
| Marketing | `af_sky` | Most energetic |
|
||||
|
||||
## Step 3: Get Word-Level Timestamps
|
||||
|
||||
Transcribe the generated audio back to get precise word timings:
|
||||
|
||||
```bash
|
||||
npx hyperframes transcribe narration.wav
|
||||
```
|
||||
|
||||
This produces `transcript.json`:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "text": "Stripe", "start": 0.0, "end": 0.4 },
|
||||
{ "text": "is", "start": 0.45, "end": 0.55 },
|
||||
{ "text": "financial", "start": 0.6, "end": 1.1 },
|
||||
{ "text": "infrastructure", "start": 1.15, "end": 1.8 }
|
||||
]
|
||||
```
|
||||
|
||||
## Step 4: Map Timestamps to Scenes
|
||||
|
||||
Divide the transcript into segments that correspond to scenes:
|
||||
|
||||
```
|
||||
Scene 1 intro narration: words 0-15 → starts at word[0].start, ends at word[15].end
|
||||
Scene 2 feature narration: words 16-35 → starts at word[16].start, ends at word[35].end
|
||||
...
|
||||
```
|
||||
|
||||
Set each scene's `data-start` and `data-duration` to match its narration segment. This creates natural transitions — the scene changes when the narration moves to the next topic.
|
||||
|
||||
## Step 5: Add Audio to Composition
|
||||
|
||||
In the root `index.html`, add the narration as an audio element:
|
||||
|
||||
```html
|
||||
<audio
|
||||
id="narration-audio"
|
||||
data-start="0"
|
||||
data-duration="[total narration duration]"
|
||||
data-track-index="10"
|
||||
src="narration.wav"
|
||||
data-volume="1"
|
||||
></audio>
|
||||
```
|
||||
|
||||
## Step 6: Add Captions (Optional but Recommended)
|
||||
|
||||
If adding captions synced to the narration, invoke `/hyperframes` and pass the `transcript.json`. The captions skill handles word-level timing, per-word styling, and animation automatically.
|
||||
|
||||
### Caption Emphasis with Marker-Highlight
|
||||
|
||||
For extra visual impact, use the `/hyperframes` skill to add hand-drawn emphasis on key words in captions:
|
||||
|
||||
- **Brand names** (e.g., "Stripe") → `highlight` mode with brand accent color
|
||||
- **Big numbers** (e.g., "two trillion") → `circle` or `burst` mode
|
||||
- **CTA words** (e.g., "Check it out") → `highlight` with thicker stroke
|
||||
|
||||
This is optional but makes captions feel alive. See the `/hyperframes` skill's marker-highlight reference for integration patterns.
|
||||
|
||||
Captions go in a separate sub-composition (`compositions/captions.html`) loaded as an overlay:
|
||||
|
||||
```html
|
||||
<div
|
||||
id="caption-overlay"
|
||||
data-composition-id="captions"
|
||||
data-composition-src="compositions/captions.html"
|
||||
data-start="0"
|
||||
data-duration="[narration duration]"
|
||||
data-track-index="2"
|
||||
data-width="1920"
|
||||
data-height="1080"
|
||||
></div>
|
||||
```
|
||||
|
||||
## Common Issues
|
||||
|
||||
**Audio too fast/slow:** Adjust TTS speed. HeyGen and ElevenLabs support speed parameters. For Kokoro, use `--speed 0.9` or `--speed 1.1`.
|
||||
|
||||
**Transcript timestamps are off:** Upgrade the whisper model: `npx hyperframes transcribe narration.wav --model medium.en` for better accuracy.
|
||||
|
||||
**Scene transitions feel abrupt:** Add 0.5-1s overlap between scenes — start the next scene's entrance animation slightly before the current scene fully exits.
|
||||
@@ -0,0 +1,415 @@
|
||||
# Video Recipes
|
||||
|
||||
Scene-by-scene composition patterns for each video type.
|
||||
|
||||
## Architecture Rules
|
||||
|
||||
**Every scene = a separate sub-composition file** in `compositions/`. Root `index.html` loads each scene on the same track with sequential `data-start` values.
|
||||
|
||||
```
|
||||
project/
|
||||
├── index.html ← root: loads scenes + captions + audio
|
||||
└── compositions/
|
||||
├── scene1-hook.html
|
||||
├── scene2-features.html
|
||||
├── scene3-trust.html
|
||||
├── scene4-cta.html
|
||||
└── captions.html ← word-level captions overlay
|
||||
```
|
||||
|
||||
## Transition Pattern (Every Scene Must Follow This)
|
||||
|
||||
Scenes on the same track hard-cut. To prevent jarring flashes, every scene's GSAP timeline MUST:
|
||||
|
||||
1. **Fade in from black** in the first 0.3s (background opacity 0→1, content slides in)
|
||||
2. **Fade out to black** in the last 0.3s (content fades, background opacity 1→0)
|
||||
3. Root `body { background: #000 }` ensures the gap between scenes is black, not white
|
||||
|
||||
```javascript
|
||||
// EVERY scene timeline must start and end like this:
|
||||
var dur = 5; // scene's data-duration
|
||||
var tl = gsap.timeline({ paused: true });
|
||||
|
||||
// === ENTRANCE (first 0.3s) ===
|
||||
tl.fromTo("#scene-bg", { opacity: 0 }, { opacity: 1, duration: 0.3, ease: "power2.out" }, 0);
|
||||
tl.fromTo(
|
||||
"#headline",
|
||||
{ opacity: 0, y: 30 },
|
||||
{ opacity: 1, y: 0, duration: 0.5, ease: "expo.out" },
|
||||
0.15,
|
||||
);
|
||||
|
||||
// === MAIN CONTENT (middle) ===
|
||||
// ... your animations here ...
|
||||
|
||||
// === EXIT (last 0.3s) ===
|
||||
tl.to("#headline", { opacity: 0, duration: 0.2, ease: "power1.in" }, dur - 0.35);
|
||||
tl.to("#scene-bg", { opacity: 0, duration: 0.3, ease: "power2.in" }, dur - 0.3);
|
||||
```
|
||||
|
||||
## Caption Safe Zone
|
||||
|
||||
**Bottom 120px is reserved for captions.** No scene content below y=960px. The captions sub-composition sits on track 2 as a full-duration overlay occupying this space.
|
||||
|
||||
If your scene has a CTA button or logo, place it at y=700-800, not at the bottom.
|
||||
|
||||
## Background Variety
|
||||
|
||||
When arranging captured sections into a video, ensure visual variety between adjacent scenes. Captured sections already have their real background colors — use these.
|
||||
|
||||
**Guidelines:**
|
||||
|
||||
- Don't put two dark scenes next to each other
|
||||
- Don't put two light scenes next to each other
|
||||
- Alternate light/dark or use gradient scenes as transitions
|
||||
- If the website has a consistent dark theme (like Linear), the variety comes from content differences, not background changes
|
||||
- When building custom scenes (not from capture), follow the site's color palette from `visual-style.md`
|
||||
|
||||
## Elements Must DO Something (Not Just Sit There)
|
||||
|
||||
**The #1 difference between a video and a slideshow is continuous motion.** Every visible element should have mid-scene activity — not just an entrance and exit.
|
||||
|
||||
### Mid-Scene Activity Table
|
||||
|
||||
Every CSS-built element MUST have at least one continuous animation during its hold phase:
|
||||
|
||||
| Element | Entrance | Mid-scene activity (REQUIRED) | Exit |
|
||||
| ----------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- |
|
||||
| Payment card | Slide in from left with 3D rotateY | **Amount counter animates from $0 to $2,499.00** (1.5s, power2.out). Checkmark circle draws in (stroke-dashoffset). Subtle float (y plus/minus 4px, sine.inOut, repeat:-1, yoyo) | Fade |
|
||||
| Code terminal | Slide in from right | **Lines appear one by one** (stagger: 0.4 per line, opacity 0 to 1, y: 8 to 0). Cursor blinks at end (repeat:-1, yoyo). | Fade |
|
||||
| Dashboard chart | Scale up | **Bars grow to their target heights** (stagger: 0.15, elastic.out). Values tick up as bars grow. | Fade |
|
||||
| Stats counter | Scale in with back.out | **Number counts from 0 to target** using gsap.to with onUpdate callback that sets textContent to Math.round(obj.val). Label fades in after count completes. | Fade |
|
||||
| Progress bar | Fade in empty | **Fill animates from 0% to target%** (1.2s, power2.out). Percentage text updates live. | Fade |
|
||||
| Logo grid | Stagger in | **Subtle shimmer sweep** (child div gradient slides across each logo, 2s) or **gentle pulse** (scale 1 to 1.02 to 1, sine.inOut, yoyo, repeat:-1) | Fade |
|
||||
| Subscription card | Scale in | **Icon rotates or pulses**. Progress indicator fills. Text highlights or underlines animate in. | Fade |
|
||||
|
||||
### Counter Animation Pattern (For Stats)
|
||||
|
||||
```javascript
|
||||
var obj = { val: 0 };
|
||||
var statEl = document.querySelector("#stat-num");
|
||||
tl.to(
|
||||
obj,
|
||||
{
|
||||
val: 135,
|
||||
duration: 1.5,
|
||||
ease: "power2.out",
|
||||
onUpdate: function () {
|
||||
statEl.textContent = Math.round(obj.val) + "+";
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
);
|
||||
```
|
||||
|
||||
### Floating/Breathing Pattern (For Persistent Elements)
|
||||
|
||||
```javascript
|
||||
// Subtle float — makes static elements feel alive
|
||||
tl.to("#card", { y: "-=6", duration: 2, ease: "sine.inOut", yoyo: true, repeat: -1 }, 0);
|
||||
// Pulse glow
|
||||
tl.to(
|
||||
"#glow",
|
||||
{ scale: 1.05, opacity: 0.8, duration: 1.5, ease: "sine.inOut", yoyo: true, repeat: -1 },
|
||||
0,
|
||||
);
|
||||
```
|
||||
|
||||
### Line-by-Line Reveal Pattern (For Code Terminals)
|
||||
|
||||
```javascript
|
||||
// Each line wrapped in a div with class 'code-line'
|
||||
tl.fromTo(
|
||||
".code-line",
|
||||
{ opacity: 0, y: 8 },
|
||||
{
|
||||
opacity: 1,
|
||||
y: 0,
|
||||
duration: 0.3,
|
||||
stagger: 0.4,
|
||||
ease: "power2.out",
|
||||
},
|
||||
0.5,
|
||||
);
|
||||
// Blinking cursor at end
|
||||
tl.fromTo(
|
||||
"#cursor",
|
||||
{ opacity: 1 },
|
||||
{
|
||||
opacity: 0,
|
||||
duration: 0.5,
|
||||
repeat: -1,
|
||||
yoyo: true,
|
||||
},
|
||||
2.5,
|
||||
);
|
||||
```
|
||||
|
||||
## Optional Visual Enhancements
|
||||
|
||||
These add personality that separates "AI-generated video" from "actually good video." Use 1-2 per composition — don't overload.
|
||||
|
||||
### Rough.js — Hand-Drawn Elements
|
||||
|
||||
Load rough.js for hand-drawn SVG shapes. Great for trust scenes (circles around logos), stats (underlines), and playful/educational tones.
|
||||
|
||||
```html
|
||||
<script src="https://cdn.jsdelivr.net/npm/roughjs@4.6.6/bundled/rough.min.js"></script>
|
||||
<svg
|
||||
id="rough-canvas"
|
||||
width="1920"
|
||||
height="1080"
|
||||
style="position:absolute;top:0;left:0;pointer-events:none"
|
||||
></svg>
|
||||
```
|
||||
|
||||
```javascript
|
||||
var rc = rough.svg(document.getElementById("rough-canvas"));
|
||||
|
||||
// Hand-drawn circle around a logo or word
|
||||
var node = rc.circle(960, 400, 200, {
|
||||
stroke: "#635BFF",
|
||||
strokeWidth: 3,
|
||||
roughness: 1.2,
|
||||
bowing: 2,
|
||||
fill: "none",
|
||||
});
|
||||
document.getElementById("rough-canvas").appendChild(node);
|
||||
|
||||
// Rough.js returns a <g> element — find the actual <path> children to animate
|
||||
var paths = node.querySelectorAll("path");
|
||||
paths.forEach(function (p) {
|
||||
var len = p.getTotalLength();
|
||||
p.style.strokeDasharray = len;
|
||||
p.style.strokeDashoffset = len;
|
||||
});
|
||||
|
||||
// Animate each path drawing in with GSAP
|
||||
tl.to(paths, { strokeDashoffset: 0, duration: 0.8, ease: "power2.out", stagger: 0.1 }, 2.0);
|
||||
```
|
||||
|
||||
**Best uses:**
|
||||
| Effect | When to use |
|
||||
|--------|------------|
|
||||
| Circle around a logo/word | Trust scene — circles drawn around each company name as narrator mentions them |
|
||||
| Underline under a stat | Stats scene — sketchy underline appears after number counts up |
|
||||
| Arrow pointing at CTA | CTA scene — hand-drawn arrow guides attention to the button |
|
||||
| Crossed-out text | Before/after comparisons — cross out the "old way" |
|
||||
| Box around a feature | Feature scene — rough rectangle highlights a key element |
|
||||
|
||||
**Roughness guide:** 0.8 = almost clean, 1.2 = noticeably hand-drawn, 2.0 = very sketchy. Match to brand mood — corporate brands get 0.8-1.0, playful brands get 1.5-2.0.
|
||||
|
||||
### Marker-Highlight — Hand-Drawn Text Emphasis
|
||||
|
||||
For highlighting key words in captions or scene text. See the `/hyperframes` skill's marker-highlight reference for full API details. Quick reference:
|
||||
|
||||
```javascript
|
||||
// After constructing MarkerHighlighter with animate: false
|
||||
// Trigger at specific timeline points:
|
||||
tl.call(
|
||||
function () {
|
||||
highlighter.clearMarks();
|
||||
highlighter.reanimateMark("stat-highlight");
|
||||
},
|
||||
null,
|
||||
3.0,
|
||||
);
|
||||
```
|
||||
|
||||
**Five modes:** `highlight` (marker sweep), `circle` (drawn around word), `burst` (radiating lines), `scribble` (chaotic cross-out), `sketchout` (rough rectangle)
|
||||
|
||||
**Energy mapping for captions:**
|
||||
|
||||
- Brand names, product names → `highlight` in brand accent color
|
||||
- Impressive numbers/stats → `circle` or `burst`
|
||||
- "Not just" / "never" / negation words → `scribble`
|
||||
- CTA phrases → `highlight` with thicker stroke
|
||||
|
||||
### SVG Stroke Animation — Path Drawing
|
||||
|
||||
For logos, icons, or decorative elements that "draw themselves in":
|
||||
|
||||
```javascript
|
||||
// Get the SVG path element
|
||||
var path = document.querySelector("#logo-path");
|
||||
var length = path.getTotalLength();
|
||||
path.style.strokeDasharray = length;
|
||||
path.style.strokeDashoffset = length;
|
||||
|
||||
// Animate: path draws in over 1.5 seconds
|
||||
tl.to(path.style, { strokeDashoffset: 0, duration: 1.5, ease: "power2.out" }, 0.5);
|
||||
```
|
||||
|
||||
Works with any SVG path — logos, icons, borders, decorative swirls. Combine with fill-opacity animation for a "draw then fill" effect.
|
||||
|
||||
## Use Captured Sections First
|
||||
|
||||
The capture command produces ready-made sub-compositions in `compositions/`. **Use these as your primary scene content** — they already have the real website HTML, correct styling, and proper background colors.
|
||||
|
||||
When building a video:
|
||||
|
||||
1. Pick the relevant captured sections for your video type
|
||||
2. Arrange them in the timeline with appropriate durations
|
||||
3. Add GSAP animations beyond the default entrance/exit (see animation patterns above)
|
||||
4. Only build CSS elements from scratch for things NOT on the website (custom stats counters, custom CTAs)
|
||||
|
||||
**CSS-built elements** are still useful for:
|
||||
|
||||
- Stats counters (need counting animation)
|
||||
- Progress bars (need filling animation)
|
||||
- Custom CTAs or overlays not from the original page
|
||||
- Code terminals (need typing effect)
|
||||
|
||||
## Using Captured Assets
|
||||
|
||||
The capture command downloads SVGs, images, fonts, and canvas screenshots to `assets/`. Use them:
|
||||
|
||||
- **SVG logos** → embed inline in scenes, animate with GSAP (fill, stroke, scale)
|
||||
- **Canvas screenshots** (`assets/canvas-*.png`) → use as `<img>` where the original canvas was (Three.js/WebGL content)
|
||||
- **Viewport screenshots** (`screenshots/section-*.png`) → faded backgrounds (10-20% opacity) or fallback for broken sections
|
||||
- **Fonts** (`assets/fonts/`) → already referenced in the captured CSS, load correctly from local files
|
||||
|
||||
---
|
||||
|
||||
## Product Promo (30-60s, Landscape 16:9)
|
||||
|
||||
### Scene Structure
|
||||
|
||||
```
|
||||
Scene 1 — Hook (0-5s)
|
||||
Background: WHITE or very light + DECORATIVE ASSET (use captured wave/pattern PNG
|
||||
as a background layer at opacity 0.2-0.3, drifting slowly with sine.inOut)
|
||||
Content: Brand logo (SVG or text) centered, tagline below
|
||||
Mid-scene activity: Wave/pattern drifts slowly. Logo has subtle pulse or glow.
|
||||
Tagline letters can have a shimmer sweep.
|
||||
Animation: logo scale-in with back.out, tagline slide-up
|
||||
Narration: "[Product] — [tagline]."
|
||||
|
||||
Scene 2 — Products (5-15s)
|
||||
Background: GRADIENT (brand primary to brand dark) + decorative elements if available
|
||||
Optional: use a bento grid / product UI screenshot as faded background (10-15% opacity, blur 2-4px) under the gradient
|
||||
Content: CSS-built UI mockups (payment card, terminal, dashboard)
|
||||
Build 2-3 elements and animate them in from different directions
|
||||
Mid-scene activity (CRITICAL): Each element MUST do something after entering:
|
||||
- Payment card: amount counter ticks up from $0, checkmark draws in
|
||||
- Code terminal: lines type in one by one with blinking cursor
|
||||
- Progress bar: fills from 0% to target
|
||||
- Chart: bars grow with elastic ease
|
||||
All elements should have subtle float (y +/-4px, sine.inOut, yoyo, repeat:-1)
|
||||
Animation: card from left with 3D rotateY, terminal from right, staggered 0.3s
|
||||
Narration: "[what the product does in 2-3 sentences]"
|
||||
|
||||
Scene 3 — Trust (15-25s)
|
||||
Background: LIGHT (#F6F9FC or brand light palette) + accent line or wave decoration
|
||||
Content: "Trusted by millions" headline + grid of company logos
|
||||
Use inline SVGs or styled text with correct brand colors
|
||||
6-8 logos in a 3x2 or 4x2 grid, staggered entries
|
||||
Mid-scene activity: Logos have subtle shimmer or gentle scale pulse after entering.
|
||||
Headline accent underline draws in after text settles.
|
||||
Accent line or decorative element continues slow movement throughout.
|
||||
Animation: headline drops in, logos stagger with varied entrances
|
||||
Narration: "[social proof — who uses it, stats]"
|
||||
|
||||
Scene 4 — CTA (25-30s)
|
||||
Background: GRADIENT (brand accent to brand primary, different angle from scene 2)
|
||||
Optional: pricing or stats screenshot as faded background (10% opacity)
|
||||
Content: Key stats (large numbers in accent colors), CTA button, URL
|
||||
Stats in upper half (above y=500)
|
||||
CTA in middle (y=600-700)
|
||||
Brand logo small at y=800 max (above caption zone)
|
||||
Mid-scene activity: Numbers count up from 0 to target (use gsap.to with onUpdate).
|
||||
CTA button has a pulse or glow effect after appearing.
|
||||
Animated mouse cursor glides in and clicks the CTA button.
|
||||
Background glows drift continuously.
|
||||
Animation: stats scale-in timed to narration words, CTA slides up
|
||||
Narration: "[impressive numbers]. Check it out at [url]."
|
||||
|
||||
Persistent elements across all scenes:
|
||||
- Brand favicon/icon badge in bottom-right corner (40x40px, 70% opacity, track 3)
|
||||
```
|
||||
|
||||
### Content Sourcing
|
||||
|
||||
| Scene | Source |
|
||||
| -------- | -------------------------------------------------------------------------------------------------- |
|
||||
| Hook | Use the captured hero section composition, or build from logo SVG + tagline from `visual-style.md` |
|
||||
| Products | Use captured feature/product section compositions — they already have the real UI |
|
||||
| Trust | Use captured logos/testimonials section composition, or build from SVGs in `assets/` |
|
||||
| CTA | Use captured CTA/footer section composition, or build from CTA text in `capture-summary.md` |
|
||||
|
||||
**Prefer captured sections over building from scratch.** The real website HTML looks better than recreations.
|
||||
|
||||
---
|
||||
|
||||
## Social Clip (15-30s, Vertical 9:16)
|
||||
|
||||
### Scene Structure
|
||||
|
||||
```
|
||||
Scene 1 — Hook (0-3s)
|
||||
Background: BRAND ACCENT COLOR (bold, attention-grabbing)
|
||||
Content: Bold hook question or statement (40-60px, 800 weight)
|
||||
Animation: text scale-pop entrance
|
||||
|
||||
Scene 2 — Feature Cards (3-12s)
|
||||
Background: GRADIENT
|
||||
Content: 2-3 CSS-built feature cards sliding up from bottom
|
||||
Animation: cards stagger 0.5s apart, each 2-3s visible
|
||||
|
||||
Scene 3 — Key Stat (12-20s)
|
||||
Background: LIGHT
|
||||
Content: One impressive number (80-120px), testimonial, or key claim
|
||||
Animation: number scales in with elastic ease
|
||||
|
||||
Scene 4 — CTA (20-25s)
|
||||
Background: BRAND PRIMARY
|
||||
Content: Brand name + "Try it free" / URL
|
||||
Animation: clean fade-in, snap to brand colors
|
||||
```
|
||||
|
||||
Portrait layout: 1080x1920. Text minimum 40px body, 80px headlines. Center everything vertically.
|
||||
|
||||
---
|
||||
|
||||
## Explainer (30-90s, Landscape, Narrated)
|
||||
|
||||
Each scene's duration = duration of its narration segment (from transcript.json word timestamps).
|
||||
|
||||
```
|
||||
Scene 1 — Intro (words 0-N)
|
||||
"What is [Product]?" + logo
|
||||
|
||||
Scene 2-N — Feature walkthrough
|
||||
One scene per feature, each with:
|
||||
- CSS-built visual representing the feature
|
||||
- Feature headline
|
||||
Duration synced to narration segment
|
||||
|
||||
Final — CTA
|
||||
Logo + URL + tagline
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Launch Announcement (15-30s)
|
||||
|
||||
```
|
||||
Scene 1 — Build-up (0-10s)
|
||||
Animated shapes/gradient in brand colors
|
||||
Category text: "Video creation, reimagined"
|
||||
|
||||
Scene 2 — Reveal (10-20s)
|
||||
Logo scales in dramatically, product name + tagline
|
||||
|
||||
Scene 3 — CTA (20-25s)
|
||||
"Coming soon" / "Available now" + URL
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Adapting to Content
|
||||
|
||||
- **No testimonials?** Skip trust scene, extend features
|
||||
- **Only one feature?** Make it the hero, skip carousel
|
||||
- **No images?** Use bold typography + CSS-built elements
|
||||
- **E-commerce?** CSS-built product card with price as hero visual
|
||||
Reference in New Issue
Block a user