Create professional demos and 3D mockups in seconds, directly in your browser
feat: add skills
CristianOlivera1b6385bd730f7
diff --git a/.agents/skills/3d-web-experience/SKILL.md b/.agents/skills/3d-web-experience/SKILL.mdnew file mode 100644index 0000000..938005e--- /dev/null+++ b/.agents/skills/3d-web-experience/SKILL.md@@ -0,0 +1,378 @@+---+name: 3d-web-experience+description: Expert in building 3D experiences for the web - Three.js, React+ Three Fiber, Spline, WebGL, and interactive 3D scenes. Covers product+ configurators, 3D portfolios, immersive websites, and bringing depth to web+ experiences.+risk: unknown+source: vibeship-spawner-skills (Apache 2.0)+date_added: 2026-02-27+---++# 3D Web Experience++Expert in building 3D experiences for the web - Three.js, React Three Fiber,+Spline, WebGL, and interactive 3D scenes. Covers product configurators, 3D+portfolios, immersive websites, and bringing depth to web experiences.++**Role**: 3D Web Experience Architect++You bring the third dimension to the web. You know when 3D enhances+and when it's just showing off. You balance visual impact with+performance. You make 3D accessible to users who've never touched+a 3D app. You create moments of wonder without sacrificing usability.++### Expertise++- Three.js+- React Three Fiber+- Spline+- WebGL+- GLSL shaders+- 3D optimization+- Model preparation++## Capabilities++- Three.js implementation+- React Three Fiber+- WebGL optimization+- 3D model integration+- Spline workflows+- 3D product configurators+- Interactive 3D scenes+- 3D performance optimization++## Patterns++### 3D Stack Selection++Choosing the right 3D approach++**When to use**: When starting a 3D web project++## 3D Stack Selection++### Options Comparison+| Tool | Best For | Learning Curve | Control |+|------|----------|----------------|---------|+| Spline | Quick prototypes, designers | Low | Medium |+| React Three Fiber | React apps, complex scenes | Medium | High |+| Three.js vanilla | Max control, non-React | High | Maximum |+| Babylon.js | Games, heavy 3D | High | Maximum |++### Decision Tree+```+Need quick 3D element?+└── Yes → Spline+└── No → Continue++Using React?+└── Yes → React Three Fiber+└── No → Continue++Need max performance/control?+└── Yes → Three.js vanilla+└── No → Spline or R3F+```++### Spline (Fastest Start)+```jsx+import Spline from '@splinetool/react-spline';++export default function Scene() {+ return (+ <Spline scene="https://prod.spline.design/xxx/scene.splinecode" />+ );+}+```++### React Three Fiber+```jsx+import { Canvas } from '@react-three/fiber';+import { OrbitControls, useGLTF } from '@react-three/drei';++function Model() {+ const { scene } = useGLTF('/model.glb');+ return <primitive object={scene} />;+}++export default function Scene() {+ return (+ <Canvas>+ <ambientLight />+ <Model />+ <OrbitControls />+ </Canvas>+ );+}+```++### 3D Model Pipeline++Getting models web-ready++**When to use**: When preparing 3D assets++## 3D Model Pipeline++### Format Selection+| Format | Use Case | Size |+|--------|----------|------|+| GLB/GLTF | Standard web 3D | Smallest |+| FBX | From 3D software | Large |+| OBJ | Simple meshes | Medium |+| USDZ | Apple AR | Medium |++### Optimization Pipeline+```+1. Model in Blender/etc+2. Reduce poly count (< 100K for web)+3. Bake textures (combine materials)+4. Export as GLB+5. Compress with gltf-transform+6. Test file size (< 5MB ideal)+```++### GLTF Compression+```bash+# Install gltf-transform+npm install -g @gltf-transform/cli++# Compress model+gltf-transform optimize input.glb output.glb \+ --compress draco \+ --texture-compress webp+```++### Loading in R3F+```jsx+import { useGLTF, useProgress, Html } from '@react-three/drei';+import { Suspense } from 'react';++function Loader() {+ const { progress } = useProgress();+ return <Html center>{progress.toFixed(0)}%</Html>;+}++export default function Scene() {+ return (+ <Canvas>+ <Suspense fallback={<Loader />}>+ <Model />+ </Suspense>+ </Canvas>+ );+}+```++### Scroll-Driven 3D++3D that responds to scroll++**When to use**: When integrating 3D with scroll++## Scroll-Driven 3D++### R3F + Scroll Controls+```jsx+import { ScrollControls, useScroll } from '@react-three/drei';+import { useFrame } from '@react-three/fiber';++function RotatingModel() {+ const scroll = useScroll();+ const ref = useRef();++ useFrame(() => {+ // Rotate based on scroll position+ ref.current.rotation.y = scroll.offset * Math.PI * 2;+ });++ return <mesh ref={ref}>...</mesh>;+}++export default function Scene() {+ return (+ <Canvas>+ <ScrollControls pages={3}>+ <RotatingModel />+ </ScrollControls>+ </Canvas>+ );+}+```++### GSAP + Three.js+```javascript+import gsap from 'gsap';+import ScrollTrigger from 'gsap/ScrollTrigger';++gsap.to(camera.position, {+ scrollTrigger: {+ trigger: '.section',+ scrub: true,+ },+ z: 5,+ y: 2,+});+```++### Common Scroll Effects+- Camera movement through scene+- Model rotation on scroll+- Reveal/hide elements+- Color/material changes+- Exploded view animations++### Performance Optimization++Keeping 3D fast++**When to use**: Always - 3D is expensive++## 3D Performance++### Performance Targets+| Device | Target FPS | Max Triangles |+|--------|------------|---------------|+| Desktop | 60fps | 500K |+| Mobile | 30-60fps | 100K |+| Low-end | 30fps | 50K |++### Quick Wins+```jsx+// 1. Use instances for repeated objects+import { Instances, Instance } from '@react-three/drei';++// 2. Limit lights+<ambientLight intensity={0.5} />+<directionalLight /> // Just one++// 3. Use LOD (Level of Detail)+import { LOD } from 'three';++// 4. Lazy load models+const Model = lazy(() => import('./Model'));+```++### Mobile Detection+```jsx+const isMobile = /iPhone|iPad|Android/i.test(navigator.userAgent);++<Canvas+ dpr={isMobile ? 1 : 2} // Lower resolution on mobile+ performance={{ min: 0.5 }} // Allow frame drops+>+```++### Fallback Strategy+```jsx+function Scene() {+ const [webGLSupported, setWebGLSupported] = useState(true);++ if (!webGLSupported) {+ return <img src="/fallback.png" alt="3D preview" />;+ }++ return <Canvas onCreated={...} />;+}+```++## Validation Checks++### No 3D Loading Indicator++Severity: HIGH++Message: No loading indicator for 3D content.++Fix action: Add Suspense with loading fallback or useProgress for loading UI++### No WebGL Fallback++Severity: MEDIUM++Message: No fallback for devices without WebGL support.++Fix action: Add WebGL detection and static image fallback++### Uncompressed 3D Models++Severity: MEDIUM++Message: 3D models may be unoptimized.++Fix action: Compress models with gltf-transform using Draco and texture compression++### OrbitControls Blocking Scroll++Severity: MEDIUM++Message: OrbitControls may be capturing scroll events.++Fix action: Add enableZoom={false} or handle scroll/touch events appropriately++### High DPR on Mobile++Severity: MEDIUM++Message: Canvas DPR may be too high for mobile devices.++Fix action: Limit DPR to 1 on mobile devices for better performance++## Collaboration++### Delegation Triggers++- scroll animation|parallax|GSAP -> scroll-experience (Scroll integration)+- react|next|frontend -> frontend (React integration)+- performance|slow|fps -> performance-hunter (3D performance optimization)+- product page|landing|marketing -> landing-page-design (Product landing with 3D)++### Product Configurator++Skills: 3d-web-experience, frontend, landing-page-design++Workflow:++```+1. Prepare 3D product model+2. Set up React Three Fiber scene+3. Add interactivity (colors, variants)+4. Integrate with product page+5. Optimize for mobile+6. Add fallback images+```++### Immersive Portfolio++Skills: 3d-web-experience, scroll-experience, interactive-portfolio++Workflow:++```+1. Design 3D scene concept+2. Build scene in Spline or R3F+3. Add scroll-driven animations+4. Integrate with portfolio sections+5. Ensure mobile fallback+6. Optimize performance+```++## Related Skills++Works well with: `scroll-experience`, `interactive-portfolio`, `frontend`, `landing-page-design`++## When to Use+- User mentions or implies: 3D website+- User mentions or implies: three.js+- User mentions or implies: WebGL+- User mentions or implies: react three fiber+- User mentions or implies: 3D experience+- User mentions or implies: spline+- User mentions or implies: product configurator++## Limitations+- Use this skill only when the task clearly matches the scope described above.+- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.+- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.diff --git a/.agents/skills/gsap/SKILL.md b/.agents/skills/gsap/SKILL.mdnew file mode 100644index 0000000..db40a6c--- /dev/null+++ b/.agents/skills/gsap/SKILL.md@@ -0,0 +1,240 @@+---+name: gsap+description: GSAP animation reference for HyperFrames. Covers gsap.to(), from(), fromTo(), easing, stagger, defaults, timelines (gsap.timeline(), position parameter, labels, nesting, playback), and performance (transforms, will-change, quickTo). Use when writing GSAP animations in HyperFrames compositions.+---++# GSAP++## HyperFrames Contract++HyperFrames controls GSAP through its `gsap` runtime adapter. Create a paused timeline synchronously, register it on `window.__timelines` with the exact `data-composition-id`, and let HyperFrames seek it.++```html+<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>+<script>+ window.__timelines = window.__timelines || {};+ const tl = gsap.timeline({ paused: true });++ tl.from(".title", { y: 48, opacity: 0, duration: 0.6, ease: "power3.out" }, 0);+ tl.to(".accent", { scaleX: 1, duration: 0.5, ease: "power2.out" }, 0.25);++ window.__timelines["main"] = tl; // key must equal data-composition-id on the composition root+</script>+```++- The registry key must match the composition root's `data-composition-id`.+- Do not call `tl.play()` for render-critical motion.+- Do not build timelines inside async code, timers, or event handlers.+- Keep loops finite. HyperFrames renders finite video durations.++## Core Tween Methods++- **gsap.to(targets, vars)** — animate from current state to `vars`. Most common.+- **gsap.from(targets, vars)** — animate from `vars` to current state (entrances).+- **gsap.fromTo(targets, fromVars, toVars)** — explicit start and end.+- **gsap.set(targets, vars)** — apply immediately (duration 0).++Always use **camelCase** property names (e.g. `backgroundColor`, `rotationX`).++## Common vars++- **duration** — seconds (default 0.5).+- **delay** — seconds before start.+- **ease** — `"power1.out"` (default), `"power3.inOut"`, `"back.out(1.7)"`, `"elastic.out(1, 0.3)"`, `"none"`.+- **stagger** — number `0.1` or object: `{ amount: 0.3, from: "center" }`, `{ each: 0.1, from: "random" }`.+- **overwrite** — `false` (default), `true`, or `"auto"`.+- **repeat** — finite number; never `-1` in HyperFrames. Compute repeats from the visible duration. **yoyo** — alternates direction with repeat.+- **onComplete**, **onStart**, **onUpdate** — callbacks.+- **immediateRender** — default `true` for from()/fromTo(). Set `false` on later tweens targeting the same property+element to avoid overwrite.++## Transforms and CSS++Prefer GSAP's **transform aliases** over raw `transform` string:++| GSAP property | Equivalent |+| --------------------------- | ------------------- |+| `x`, `y`, `z` | translateX/Y/Z (px) |+| `xPercent`, `yPercent` | translateX/Y in % |+| `scale`, `scaleX`, `scaleY` | scale |+| `rotation` | rotate (deg) |+| `rotationX`, `rotationY` | 3D rotate |+| `skewX`, `skewY` | skew |+| `transformOrigin` | transform-origin |++- **autoAlpha** — prefer over `opacity`. At 0: also sets `visibility: hidden`.+- **CSS variables** — `"--hue": 180`.+- **svgOrigin** _(SVG only)_ — global SVG coordinate space origin. Don't combine with `transformOrigin`.+- **Directional rotation** — `"360_cw"`, `"-170_short"`, `"90_ccw"`.+- **clearProps** — `"all"` or comma-separated; removes inline styles on complete.+- **Relative values** — `"+=20"`, `"-=10"`, `"*=2"`.++## Function-Based Values++```javascript+gsap.to(".item", {+ x: (i, target, targets) => i * 50,+ stagger: 0.1,+});+```++## Easing++Built-in eases: `power1`–`power4`, `back`, `bounce`, `circ`, `elastic`, `expo`, `sine`. Each has `.in`, `.out`, `.inOut`.++## Defaults++```javascript+gsap.defaults({ duration: 0.6, ease: "power2.out" });+```++## Controlling Tweens++```javascript+const tween = gsap.to(".box", { x: 100 });+tween.pause();+tween.play();+tween.reverse();+tween.kill();+tween.progress(0.5);+tween.time(0.2);+```++## gsap.matchMedia() (Responsive + Accessibility)++Runs setup only when a media query matches; auto-reverts when it stops matching.++```javascript+let mm = gsap.matchMedia();+mm.add(+ {+ isDesktop: "(min-width: 800px)",+ reduceMotion: "(prefers-reduced-motion: reduce)",+ },+ (context) => {+ const { isDesktop, reduceMotion } = context.conditions;+ gsap.to(".box", {+ rotation: isDesktop ? 360 : 180,+ duration: reduceMotion ? 0 : 2,+ });+ },+);+```++---++## Timelines++### Creating a Timeline++```javascript+const tl = gsap.timeline({ defaults: { duration: 0.5, ease: "power2.out" } });+tl.to(".a", { x: 100 }).to(".b", { y: 50 }).to(".c", { opacity: 0 });+```++### Position Parameter++Third argument controls placement:++- **Absolute**: `1` — at 1s+- **Relative**: `"+=0.5"` — after end; `"-=0.2"` — before end+- **Label**: `"intro"`, `"intro+=0.3"`+- **Alignment**: `"<"` — same start as previous; `">"` — after previous ends; `"<0.2"` — 0.2s after previous starts++```javascript+tl.to(".a", { x: 100 }, 0);+tl.to(".b", { y: 50 }, "<"); // same start as .a+tl.to(".c", { opacity: 0 }, "<0.2"); // 0.2s after .b starts+```++### Labels++```javascript+tl.addLabel("intro", 0);+tl.to(".a", { x: 100 }, "intro");+tl.addLabel("outro", "+=0.5");+tl.play("outro");+tl.tweenFromTo("intro", "outro");+```++### Timeline Options++- **paused: true** — create paused; call `.play()` to start.+- **repeat**, **yoyo** — apply to whole timeline.+- **defaults** — vars merged into every child tween.++### Nesting Timelines++```javascript+const master = gsap.timeline();+const child = gsap.timeline();+child.to(".a", { x: 100 }).to(".b", { y: 50 });+master.add(child, 0);+```++### Playback Control++`tl.play()`, `tl.pause()`, `tl.reverse()`, `tl.restart()`, `tl.time(2)`, `tl.progress(0.5)`, `tl.kill()`.++---++## Performance++### Prefer Transform and Opacity++Animating `x`, `y`, `scale`, `rotation`, `opacity` stays on the compositor. Avoid `width`, `height`, `top`, `left` when transforms achieve the same effect.++### will-change++```css+will-change: transform;+```++Only on elements that actually animate.++### gsap.quickTo() for Frequent Updates++```javascript+let xTo = gsap.quickTo("#id", "x", { duration: 0.4, ease: "power3" }),+ yTo = gsap.quickTo("#id", "y", { duration: 0.4, ease: "power3" });+container.addEventListener("mousemove", (e) => {+ xTo(e.pageX);+ yTo(e.pageY);+});+```++### Stagger > Many Tweens++Use `stagger` instead of separate tweens with manual delays.++### Cleanup++Pause or kill off-screen animations.++---++## References (loaded on demand)++- **[references/effects.md](references/effects.md)** — Drop-in effects: typewriter text, audio visualizer. Read when needing ready-made effect patterns for HyperFrames.++## Best Practices++- Use camelCase property names; prefer transform aliases and autoAlpha.+- Prefer timelines over chaining with delay; use the position parameter.+- Add labels with `addLabel()` for readable sequencing.+- Pass defaults into timeline constructor.+- Store tween/timeline return value when controlling playback.++## Do Not++- Animate layout properties (width/height/top/left) when transforms suffice.+- Use both svgOrigin and transformOrigin on the same SVG element.+- Chain animations with delay when a timeline can sequence them.+- Create tweens before the DOM exists.+- Skip cleanup — always kill tweens when no longer needed.+- Use infinite repeat values in HyperFrames compositions. Use finite repeat counts computed from the visible duration.++## Credits And References++- HyperFrames adapter source: `packages/core/src/runtime/adapters/gsap.ts`.+- GSAP documentation: https://gsap.com/docs/v3/+- GSAP timeline pause and seek behavior: https://gsap.com/docs/v3/GSAP/Timeline/pause%28%29/diff --git a/.agents/skills/gsap/references/effects.md b/.agents/skills/gsap/references/effects.mdnew file mode 100644index 0000000..82c0eba--- /dev/null+++ b/.agents/skills/gsap/references/effects.md@@ -0,0 +1,297 @@+# GSAP Effects for HyperFrames++Drop-in animation patterns for HyperFrames compositions. Each effect is self-contained with HTML, CSS, and code.++All effects follow HyperFrames composition rules — deterministic, no randomness, timelines registered via `window.__timelines`.++## Table of Contents++- [Typewriter](#typewriter)+- [Audio Visualizer](#audio-visualizer)++---++## Typewriter++Reveal text character by character using GSAP's TextPlugin.++### Required Plugin++```html+<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>+<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/TextPlugin.min.js"></script>+<script>+ gsap.registerPlugin(TextPlugin);+</script>+```++### Basic Typewriter++```js+const text = "Hello, world!";+const cps = 10; // chars per second: 3-5 dramatic, 8-12 conversational, 15-20 energetic+tl.to(+ "#typed-text",+ { text: { value: text }, duration: text.length / cps, ease: "none" },+ startTime,+);+```++### With Blinking Cursor++Three rules:++1. **One cursor visible at a time** — hide previous before showing next.+2. **Cursor must blink when idle** — after typing, during pauses.+3. **No gap between text and cursor** — elements must be flush in HTML.++```html+<span id="typed-text"></span><span id="cursor" class="cursor-blink">|</span>+```++```css+@keyframes blink {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0;+ }+}+.cursor-blink {+ animation: blink 0.8s step-end infinite;+}+.cursor-solid {+ animation: none;+ opacity: 1;+}+.cursor-hide {+ animation: none;+ opacity: 0;+}+```++Pattern: blink → solid (typing starts) → type → solid → blink (typing done).++```js+tl.call(() => cursor.classList.replace("cursor-blink", "cursor-solid"), [], startTime);+tl.to("#typed-text", { text: { value: text }, duration: dur, ease: "none" }, startTime);+tl.call(() => cursor.classList.replace("cursor-solid", "cursor-blink"), [], startTime + dur);+```++### Backspacing++TextPlugin removes from front — wrong for backspace. Use manual substring removal:++```js+function backspace(tl, selector, word, startTime, cps) {+ const el = document.querySelector(selector);+ const interval = 1 / cps;+ for (let i = word.length - 1; i >= 0; i--) {+ tl.call(+ () => {+ el.textContent = word.slice(0, i);+ },+ [],+ startTime + (word.length - i) * interval,+ );+ }+ return word.length * interval;+}+```++### Spacing with Static Text++When a typewriter word sits next to static text, use `margin-left` on a wrapper span. Don't use flex gap (spaces cursor from text) or trailing space in static text (collapses when dynamic is empty).++```html+<div style="display:flex; align-items:baseline;">+ <span style="font-size:40px; color:#555;">Ship something</span>+ <span style="margin-left:14px;"><span id="word"></span><span id="cursor">|</span></span>+</div>+```++### Word Rotation++Type → hold → backspace → next word. Cursor blinks during every idle moment (holds, after backspace).++```js+words.forEach((word, i) => {+ const typeDur = word.length / 10;+ // Solid while typing+ tl.call(() => cursor.classList.replace("cursor-blink", "cursor-solid"), [], offset);+ tl.to("#typed-text", { text: { value: word }, duration: typeDur, ease: "none" }, offset);+ // Blink during hold+ tl.call(() => cursor.classList.replace("cursor-solid", "cursor-blink"), [], offset + typeDur);+ offset += typeDur + 1.5; // hold++ if (i < words.length - 1) {+ tl.call(() => cursor.classList.replace("cursor-blink", "cursor-solid"), [], offset);+ const clearDur = backspace(tl, el, word, offset, 20);+ tl.call(() => cursor.classList.replace("cursor-solid", "cursor-blink"), [], offset + clearDur);+ offset += clearDur + 0.3;+ }+});+```++### Appending Words++Build a sentence word-by-word into the same element:++```js+let accumulated = "";+words.forEach((word) => {+ const target = accumulated + (accumulated ? " " : "") + word;+ const newChars = target.length - accumulated.length;+ tl.to("#typed-text", { text: { value: target }, duration: newChars / 10, ease: "none" }, offset);+ accumulated = target;+ offset += newChars / 10 + 0.3;+});+```++### Multi-Line Cursor Handoff++When handing off between typewriter lines: hide previous → blink new → pause → solid when typing. Never go hidden→solid (skips idle state).++```js+tl.call(+ () => {+ prevCursor.classList.replace("cursor-blink", "cursor-hide");+ nextCursor.classList.replace("cursor-hide", "cursor-blink");+ },+ [],+ handoffTime,+);++const typeStart = handoffTime + 0.5; // brief blink pause+tl.call(() => nextCursor.classList.replace("cursor-blink", "cursor-solid"), [], typeStart);+tl.to("#next-text", { text: { value: text }, duration: dur, ease: "none" }, typeStart);+tl.call(() => nextCursor.classList.replace("cursor-solid", "cursor-blink"), [], typeStart + dur);+```++### Timing Guide++| CPS | Feel | Good for |+| ----- | ---------------- | -------------------------- |+| 3-5 | Slow, deliberate | Dramatic reveals, suspense |+| 8-12 | Natural typing | Dialogue, narration |+| 15-20 | Fast, energetic | Tech demos, code |+| 30+ | Near-instant | Filling long blocks |++---++## Audio Visualizer++Pre-extract audio data, drive canvas/DOM rendering from GSAP timeline.++### Extract Audio Data++```bash+python scripts/extract-audio-data.py audio.mp3 -o audio-data.json+python scripts/extract-audio-data.py video.mp4 --fps 30 --bands 16 -o audio-data.json+```++Requires ffmpeg and numpy.++### Data Format++```json+{+ "fps": 30, "totalFrames": 5415,+ "frames": [{ "time": 0.0, "rms": 0.42, "bands": [0.8, 0.6, 0.3, ...] }]+}+```++- **rms** (0-1): overall loudness, normalized across track+- **bands[]** (0-1): frequency magnitudes. Index 0 = bass, higher = treble. Each normalized independently.++### Loading the Data++```js+// Option A: inline (small files, under ~500KB)+var AUDIO_DATA = {+ /* paste audio-data.json contents */+};++// Option B: sync XHR (large files — must be synchronous for deterministic timeline construction)+var xhr = new XMLHttpRequest();+xhr.open("GET", "audio-data.json", false);+xhr.send();+var AUDIO_DATA = JSON.parse(xhr.responseText);+```++**Do NOT use async `fetch()` to load audio data.** HyperFrames requires synchronous timeline construction — the capture engine reads `window.__timelines` synchronously after page load. Building timelines inside `.then()` callbacks means the timeline isn't ready when capture starts.++### Rendering Approaches++**Canvas 2D** (most common — bars, waveforms, circles, gradients):++```js+for (let f = 0; f < AUDIO_DATA.totalFrames; f++) {+ tl.call(+ () => {+ const frame = AUDIO_DATA.frames[f];+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ // draw using frame.rms and frame.bands+ },+ [],+ f / AUDIO_DATA.fps,+ );+}+```++**WebGL / Three.js** — HyperFrames patches `THREE.Clock` for deterministic time. Update uniforms from audio data each frame.++**DOM Elements** — fine for < 20 elements, less performant than Canvas for many.++### Spatial Mapping++- **Horizontal**: bass left, treble right (iterate bands left-to-right)+- **Vertical**: bass bottom, treble top+- **Circular**: bass at 12 o'clock, wrap clockwise; mirror for full circle++### Smoothing++```js+let prev = null;+const smoothing = 0.25; // 0.1-0.2 snappy, 0.3-0.5 flowing+function smooth(f) {+ const raw = AUDIO_DATA.frames[f];+ if (!prev) {+ prev = { rms: raw.rms, bands: [...raw.bands] };+ return prev;+ }+ prev = {+ rms: prev.rms * smoothing + raw.rms * (1 - smoothing),+ bands: raw.bands.map((b, i) => prev.bands[i] * smoothing + b * (1 - smoothing)),+ };+ return prev;+}+```++### Motion Principles++- **Bass drives big moves** — scale, glow, position shifts+- **Treble drives detail** — shimmer, flicker, edge effects+- **RMS drives globals** — background brightness, overall energy+- Pick 2-3 properties to animate. More looks noisy.+- Keep minimums above zero — quiet sections need life.++### Band Count++| Bands | Detail | Good for |+| ----- | --------- | -------------------------- |+| 4 | Low | Background glow, pulsing |+| 8 | Medium | Bar charts, basic spectrum |+| 16 | High | Detailed EQ (default) |+| 32 | Very high | Dense radial layouts |++### Layering++Layer multiple canvases with CSS z-index for depth — a background layer driven by bass/rms and a foreground layer driven by individual bands creates depth without complexity.++```html+<canvas id="bg-layer" style="position:absolute;top:0;left:0;z-index:1;"></canvas>+<canvas id="main-layer" style="position:absolute;top:0;left:0;z-index:2;"></canvas>+```diff --git a/.agents/skills/gsap/scripts/extract-audio-data.py b/.agents/skills/gsap/scripts/extract-audio-data.pynew file mode 100644index 0000000..b4efba7--- /dev/null+++ b/.agents/skills/gsap/scripts/extract-audio-data.py@@ -0,0 +1,188 @@+#!/usr/bin/env python3+"""+Extract per-frame audio visualization data from an audio or video file.++Outputs JSON with RMS amplitude and frequency band data at the target FPS,+ready to embed in a HyperFrames composition.++Usage:+ python extract-audio-data.py input.mp3 -o audio-data.json+ python extract-audio-data.py input.mp4 --fps 30 --bands 16 -o audio-data.json++Requirements:+ - Python 3.9++ - ffmpeg (for decoding audio)+ - numpy (pip install numpy)+"""++import argparse+import json+import subprocess+import sys++import numpy as np++# ---------------------------------------------------------------------------+# FFT parameters+#+# A 4096-sample window gives ~10.8 Hz per bin at 44100Hz — enough to resolve+# low-frequency bands cleanly. The per-frame audio slice (44100/30 = 1470+# samples at 30fps) is too small and causes low bands to map to the same bins.+#+# Frequency range 30Hz–16kHz covers the useful range for music. Below 30Hz is+# sub-bass most speakers can't reproduce; above 16kHz is noise/harmonics that+# don't contribute to perceived rhythm or melody.+# ---------------------------------------------------------------------------++SAMPLE_RATE = 44100+FFT_SIZE = 4096+MIN_FREQ = 30.0+MAX_FREQ = 16000.0+++def decode_audio(path: str) -> np.ndarray:+ """Decode audio to mono float32 samples via ffmpeg."""+ cmd = [+ "ffmpeg", "-i", path,+ "-vn", "-ac", "1", "-ar", str(SAMPLE_RATE),+ "-f", "s16le", "-acodec", "pcm_s16le",+ "-loglevel", "error",+ "pipe:1",+ ]+ result = subprocess.run(cmd, capture_output=True)+ if result.returncode != 0:+ print(f"ffmpeg error: {result.stderr.decode()}", file=sys.stderr)+ sys.exit(1)+ return np.frombuffer(result.stdout, dtype=np.int16).astype(np.float32) / 32768.0+++def compute_band_edges(n_bands: int) -> np.ndarray:+ """Logarithmically-spaced frequency band edges from MIN_FREQ to MAX_FREQ."""+ return np.array([+ MIN_FREQ * (MAX_FREQ / MIN_FREQ) ** (i / n_bands)+ for i in range(n_bands + 1)+ ])+++def compute_fft_bands(+ windowed: np.ndarray, freq_per_bin: float, n_bins: int,+ band_edges: np.ndarray, n_bands: int,+) -> np.ndarray:+ """Compute peak magnitude in logarithmically-spaced frequency bands."""+ magnitudes = np.abs(np.fft.rfft(windowed))++ bands = np.zeros(n_bands)+ for b in range(n_bands):+ low_bin = max(0, int(band_edges[b] / freq_per_bin))+ high_bin = min(n_bins, int(band_edges[b + 1] / freq_per_bin))+ if high_bin <= low_bin:+ high_bin = low_bin + 1+ # Clamp to valid range to avoid empty slices+ low_bin = min(low_bin, n_bins - 1)+ high_bin = min(high_bin, n_bins)+ bands[b] = np.max(magnitudes[low_bin:high_bin])++ return bands+++def extract(path: str, fps: int, n_bands: int) -> dict:+ """Extract per-frame audio data."""+ print(f"Decoding audio from {path}...", file=sys.stderr)+ samples = decode_audio(path)+ duration = len(samples) / SAMPLE_RATE+ frame_step = SAMPLE_RATE // fps+ total_frames = int(duration * fps)++ print(f"Duration: {duration:.1f}s, {total_frames} frames at {fps}fps", file=sys.stderr)+ print(f"FFT window: {FFT_SIZE} samples ({SAMPLE_RATE / FFT_SIZE:.1f} Hz/bin)", file=sys.stderr)+ print(f"Frequency range: {MIN_FREQ:.0f}-{MAX_FREQ:.0f} Hz, {n_bands} bands", file=sys.stderr)++ # Precompute constants+ hann = np.hanning(FFT_SIZE)+ band_edges = compute_band_edges(n_bands)+ freq_per_bin = SAMPLE_RATE / FFT_SIZE+ n_bins = FFT_SIZE // 2 + 1+ half_fft = FFT_SIZE // 2++ # Pass 1: extract raw values+ rms_values = np.zeros(total_frames)+ band_values = np.zeros((total_frames, n_bands))++ for f in range(total_frames):+ # RMS from the frame's audio slice+ rms_start = f * frame_step+ rms_end = rms_start + frame_step+ frame_slice = samples[rms_start:min(rms_end, len(samples))]+ if len(frame_slice) > 0:+ rms_values[f] = np.sqrt(np.mean(frame_slice ** 2))++ # FFT from a centered 4096-sample window+ center = rms_start + frame_step // 2+ win_start = center - half_fft+ win_end = center + half_fft++ if win_start >= 0 and win_end <= len(samples):+ window = samples[win_start:win_end] * hann+ else:+ # Zero-pad at edges+ padded = np.zeros(FFT_SIZE)+ src_start = max(0, win_start)+ src_end = min(len(samples), win_end)+ dst_start = src_start - win_start+ dst_end = dst_start + (src_end - src_start)+ padded[dst_start:dst_end] = samples[src_start:src_end]+ window = padded * hann++ band_values[f] = compute_fft_bands(window, freq_per_bin, n_bins, band_edges, n_bands)++ # Pass 2: normalize+ peak_rms = rms_values.max() if total_frames > 0 else 1.0+ if peak_rms > 0:+ rms_values /= peak_rms++ # Per-band normalization so treble is visible alongside louder bass+ band_peaks = band_values.max(axis=0)+ band_peaks[band_peaks == 0] = 1.0+ band_values /= band_peaks++ # Build output+ frames = []+ for f in range(total_frames):+ frames.append({+ "time": round(f / fps, 4),+ "rms": round(float(rms_values[f]), 4),+ "bands": [round(float(b), 4) for b in band_values[f]],+ })++ return {+ "duration": round(duration, 4),+ "fps": fps,+ "bands": n_bands,+ "totalFrames": total_frames,+ "frames": frames,+ }+++def main():+ parser = argparse.ArgumentParser(description="Extract per-frame audio visualization data")+ parser.add_argument("input", help="Audio or video file")+ parser.add_argument("-o", "--output", default="audio-data.json", help="Output JSON path")+ parser.add_argument("--fps", type=int, default=30, help="Frames per second (default: 30)")+ parser.add_argument("--bands", type=int, default=16, help="Number of frequency bands (default: 16)")+ args = parser.parse_args()++ if args.fps < 1:+ parser.error("--fps must be at least 1")+ if args.bands < 1:+ parser.error("--bands must be at least 1")++ data = extract(args.input, args.fps, args.bands)++ with open(args.output, "w") as f:+ json.dump(data, f)++ print(f"Wrote {args.output} ({data['totalFrames']} frames, {data['bands']} bands)", file=sys.stderr)+++if __name__ == "__main__":+ main()diff --git a/.agents/skills/react-three-fiber/SKILL.md b/.agents/skills/react-three-fiber/SKILL.mdnew file mode 100644index 0000000..062d6f3--- /dev/null+++ b/.agents/skills/react-three-fiber/SKILL.md@@ -0,0 +1,180 @@+---+name: react-three-fiber+description: React Three Fiber 3D renderer for json-render. Use when working with @json-render/react-three-fiber, building 3D scenes from JSON specs, rendering meshes/lights/models/environments, or integrating Three.js with json-render catalogs.+---++# @json-render/react-three-fiber++React Three Fiber renderer for json-render. 19 built-in 3D components.++## Two Entry Points++| Entry Point | Exports | Use For |+|-------------|---------|---------|+| `@json-render/react-three-fiber/catalog` | `threeComponentDefinitions` | Catalog schemas (no R3F dependency, safe for server) |+| `@json-render/react-three-fiber` | `threeComponents`, `ThreeRenderer`, `ThreeCanvas`, schemas | R3F implementations and renderer |++## Usage Pattern++Pick the 3D components you need from the standard definitions:++```typescript+import { defineCatalog } from "@json-render/core";+import { schema } from "@json-render/react/schema";+import { threeComponentDefinitions } from "@json-render/react-three-fiber/catalog";+import { defineRegistry } from "@json-render/react";+import { threeComponents, ThreeCanvas } from "@json-render/react-three-fiber";++// Catalog: pick definitions+const catalog = defineCatalog(schema, {+ components: {+ Box: threeComponentDefinitions.Box,+ Sphere: threeComponentDefinitions.Sphere,+ AmbientLight: threeComponentDefinitions.AmbientLight,+ DirectionalLight: threeComponentDefinitions.DirectionalLight,+ OrbitControls: threeComponentDefinitions.OrbitControls,+ },+ actions: {},+});++// Registry: pick matching implementations+const { registry } = defineRegistry(catalog, {+ components: {+ Box: threeComponents.Box,+ Sphere: threeComponents.Sphere,+ AmbientLight: threeComponents.AmbientLight,+ DirectionalLight: threeComponents.DirectionalLight,+ OrbitControls: threeComponents.OrbitControls,+ },+});+```++## Rendering++### ThreeCanvas (convenience wrapper)++```tsx+<ThreeCanvas+ spec={spec}+ registry={registry}+ shadows+ camera={{ position: [5, 5, 5], fov: 50 }}+ style={{ width: "100%", height: "100vh" }}+/>+```++### Manual Canvas setup++```tsx+import { Canvas } from "@react-three/fiber";+import { ThreeRenderer } from "@json-render/react-three-fiber";++<Canvas shadows>+ <ThreeRenderer spec={spec} registry={registry}>+ {/* Additional R3F elements */}+ </ThreeRenderer>+</Canvas>+```++## Available Components (19)++### Primitives (7)+- `Box` -- width, height, depth, material+- `Sphere` -- radius, widthSegments, heightSegments, material+- `Cylinder` -- radiusTop, radiusBottom, height, material+- `Cone` -- radius, height, material+- `Torus` -- radius, tube, material+- `Plane` -- width, height, material+- `Capsule` -- radius, length, material++All primitives share: `position`, `rotation`, `scale`, `castShadow`, `receiveShadow`, `material`.++### Lights (4)+- `AmbientLight` -- color, intensity+- `DirectionalLight` -- position, color, intensity, castShadow+- `PointLight` -- position, color, intensity, distance, decay+- `SpotLight` -- position, color, intensity, angle, penumbra++### Other (8)+- `Group` -- container with position/rotation/scale, supports children+- `Model` -- GLTF/GLB loader via url prop+- `Environment` -- HDRI environment map (preset, background, blur, intensity)+- `Fog` -- linear fog (color, near, far)+- `GridHelper` -- reference grid (size, divisions, color)+- `Text3D` -- SDF text (text, fontSize, color, anchorX, anchorY)+- `PerspectiveCamera` -- camera (position, fov, near, far, makeDefault)+- `OrbitControls` -- orbit controls (enableDamping, enableZoom, autoRotate)++## Shared Schemas++Reusable Zod schemas for custom 3D catalog definitions:++```typescript+import { vector3Schema, materialSchema, transformProps, shadowProps } from "@json-render/react-three-fiber";+import { z } from "zod";++// Custom 3D component+const myComponentDef = {+ props: z.object({+ ...transformProps,+ ...shadowProps,+ material: materialSchema.nullable(),+ myCustomProp: z.string(),+ }),+ description: "My custom 3D component",+};+```++## Material Schema++```typescript+materialSchema = z.object({+ color: z.string().nullable(), // default "#ffffff"+ metalness: z.number().nullable(), // default 0+ roughness: z.number().nullable(), // default 1+ emissive: z.string().nullable(), // default "#000000"+ emissiveIntensity: z.number().nullable(), // default 1+ opacity: z.number().nullable(), // default 1+ transparent: z.boolean().nullable(), // default false+ wireframe: z.boolean().nullable(), // default false+});+```++## Spec Format++3D specs use the standard json-render flat element format:++```json+{+ "root": "scene",+ "elements": {+ "scene": {+ "type": "Group",+ "props": { "position": [0, 0, 0] },+ "children": ["light", "box"]+ },+ "light": {+ "type": "AmbientLight",+ "props": { "intensity": 0.5 },+ "children": []+ },+ "box": {+ "type": "Box",+ "props": {+ "position": [0, 0.5, 0],+ "material": { "color": "#4488ff", "metalness": 0.3, "roughness": 0.7 }+ },+ "children": []+ }+ }+}+```++## Dependencies++Peer dependencies required:+- `@react-three/fiber` >= 8.0.0+- `@react-three/drei` >= 9.0.0+- `three` >= 0.160.0+- `react` ^19.0.0+- `zod` ^4.0.0diff --git a/.gitignore b/.gitignoreindex b101980..4a26e60 100644--- a/.gitignore+++ b/.gitignore@@ -45,7 +45,4 @@ supabase-setup.sqlBACKEND_SPEC.mdBACKEND_TESTING.md-/openvid-back-.agents-.github-skills-lock.json\ No newline at end of file+/openvid-back\ No newline at end of filediff --git a/claude.md b/claude.mdnew file mode 100644index 0000000..decd304--- /dev/null+++ b/claude.md@@ -0,0 +1,548 @@+# openvid (openvidshot) — Guía del proyecto++> Crea demos y mockups profesionales en segundos, directamente en el navegador.+> Graba la pantalla o sube un video, agrega zooms suaves, mockups de dispositivos, efectos 3D y fondos personalizados, y exporta un demo cinematográfico.++---++## 1. Visión general++openvid es un **editor de video web** orientado a la creación de demos, screencasts y mockups. El repo contiene:++| Carpeta | Rol |+|---|---|+| raíz (`app/`, `components/`, `lib/`, `hooks/`, `types/`) | **Frontend / editor 100% client-side** en Next.js 16 + React 19 + Tailwind 4. Grabación, mockups, zoom 3D, audio, exportación en navegador. |+| `openvid-back/` | Subproyecto auxiliar (opcional) para renderizado headless en servidor. Ver §6. |++El **editor funciona sin backend**: todo se procesa con FFmpeg.wasm / MediaBunny / Canvas 2D / Three.js directamente en el cliente. La carpeta `openvid-back/` se mantiene como referencia/spec pero no es prioritaria para el día a día del editor.++---++## 2. Características principales++### Entrada de video+- **Grabación de pantalla** en el navegador (sin instalación) — `useScreenRecording` / `useScreenCapture` + `RecordingContext` con `MediaRecorder` API.+- **Subida de archivos** (MP4, WebM, QuickTime, MKV) con drag & drop.+- **Screen capture** instantáneo desde la landing (`useScreenCapture`).+- **Biblioteca de videos** persistente en IndexedDB (`openvid-videos-library`) con thumbnails, audio flags, file size, etc.++### Modo editor (Video vs Photo)+- **Editor mode** seleccionado por URL (`?mode=video` o `?mode=photo`) — `useEditorMode`.+- `VIDEO_MODE_CONFIG` y `PHOTO_MODE_CONFIG` (`types/editor-mode.types.ts`) activan/desactivan features: timeline, playerControls, videoClips, audioTracks, zoomFragments, camera, cursor, mockups, background, elements, export.+- **Photo mode**: sube/edita imágenes con mockups, 3D previews, image masking, export como PNG/WEBP/JPG/AVIF.++### Mockups (15+ componentes)+Definidos en `lib/mockup-data.tsx` con catálogo `MOCKUPS: Mockup[]` y renderer en `MockupWrapper.tsx`:+- **macOS** (light/dark, glass, ghost, ghost-glass, container-glass, dark-ide, ghost-ide)+- **iPhone** (slim)+- **S24 Ultra** (Samsung)+- **Chrome** / **Brave** / **Browser tab glass**+- **VSCode** (editor oscuro)+- **Glass variants** (curve, full, ui-container, hard-shell)+- **Mockup config**: `darkMode`, `frameColor`, `url`, `headerScale`, `headerOpacity`, `cornerRadius` — cada mockup declara qué features soporta (`MockupFeatures`).+- **Smart radius**: `BOTTOM_ONLY_RADIUS_MOCKUPS` y `SELF_SHADOWING_MOCKUPS` en `lib/constants.ts` controlan cómo se renderiza el `border-radius` y la sombra por mockup.+- **Perspectiva 3D** del frame vía CSS 3D transforms o canvas (`lib/perspective3d.ts` con Three.js `WebGLRenderer` offscreen).+- **Duplicación deliberada**: cada mockup vive en `app/components/ui/editor/mockups/*.tsx` (preview React) y en `lib/mockup-canvas/*.ts` (renderer canvas para export) — **NO tocar uno sin tocar el otro**.++### Fondos+- **100+ presets** categorizados en `lib/wallpaper.catalog.ts` (desktop, gradient, minimal, pattern).+- **Unsplash / Pexels / Pixabay** vía proxy `app/api/photos/route.ts` (descubrimiento rotativo + búsqueda + caché 5min).+- **Imágenes propias** (LocalStorage `openvid-uploaded-images` + IndexedDB `image-upload-cache`).+- **Color sólido / gradiente** vía `BackgroundColorEditor`.+- **Blur 0–100%** aplicado en el canvas render con `ctx.filter`.++### Personalización visual+- Padding dinámico, esquinas redondeadas, sombras, rotación y traslación del frame (`VideoTransform`).+- Crop area (`CropArea`) — soporta `VideoCropperModal` y `ImageCropperModal`.+- Image mask con gradientes lineales (`ImageMaskConfig` con top/bottom/left/right/angle) — `GetMediaMaskStyles` aplica a DOM; canvas usa `createLinearGradient` + `globalCompositeOperation = 'destination-in'`.+- Aspect ratios: `auto`, `16:9`, `9:16`, `1:1`, `4:3`, `3:4`, `custom` — `ASPECT_RATIO_DIMENSIONS` en `types/editor.types.ts`.++### Canvas y elementos+- **3 tipos de elementos** (`types/canvas-elements.types.ts`): `svg`, `image`, `text` — todos extienden `CanvasElementBase` (x, y, width, height, rotation, opacity, zIndex, visible, locked, groupId).+- **Categorías** en `lib/canvas-elements.config.ts`: `SVG_CATEGORIES`, `IMAGE_CATEGORIES`, `PINNED_SVG_ITEMS`, `PINNED_IMAGE_ITEMS`.+- **Sistema de capas**: `VIDEO_Z_INDEX = 1000` separa elementos delante/detrás del video; `layers.utils.ts` agrupa y numera; `LayersPanel.tsx` permite reordenar, bloquear, ocultar, agrupar.+- **Inline text editing** Figma-style (contentEditable) + `T` shortcut para colocar texto con crosshair.+- **Multi-select** con drag-reorder, copy/paste, bring-to-front/send-to-back.++### Zoom y cámara 3D+- **`ZoomFragment`** (`types/zoom.types.ts`): id, startTime, endTime, zoomLevel, speed, focusX/Y, optional `movementEnabled`+`movementEndX/Y`, `enable3D`+`perspective3DIntensity/AngleX/AngleY`.+- **Curvas easing**: `easeOutQuart`, `easeInOutQuart` (en `types/zoom.types.ts`).+- **3-phase zoom** (`calculateZoomPhaseState`): `entry → hold → exit` con `scale`, `focusX`, `focusY`, `rotateX`, `rotateY`, `perspective`.+- **Pivot point** calculado para que el focus quede pinned al centro del canvas a `S=S_target`.+- **3D perspective** vía `lib/perspective3d.ts` (offscreen WebGL + CanvasTexture) — aplicado SOLO al foreground (mockup), no al background.+- **GlobalConfig** (`ZoomGlobalConfig.tsx`) lista fragmentos, **TrackItem** los muestra en la timeline, **Editor** edita focus points + toggle movement/3D.++### Motion / 3D Phone+- **`MotionContext`** (`app/contexts/MotionContext.tsx`) — estado global: `selectedTemplateId`, `motionDuration/Intensity/Style/VariantId/AnimMode/ImageUrl` + `imagePhoneActive/X/Y/Scale/RotX/RotY/Device/PresetId`.+- **`MotionTemplate`** con `ScriptFn` que devuelve un `gsap.core.Timeline` (`types/motion.types.ts`).+- **`Phone3DViewer.tsx`** — única master timeline (idle → entry → hold → exit → done) con `gsap.timeline()` + `gsap.delayedCall`. Carga GLTF (phone default, iPhone 15 Pro Max, Samsung S25 Ultra) desde `public/models/`.+- **Templates registrados** en `lib/template-registry.ts` (`soloVideoTemplate`, `phoneTemplate`; otros comentados para futuro).+- **Style presets** (`STYLE_CFG` en `lib/animation-core.ts`): `smooth` / `normal` / `cinematic` con amplitudes y easings distintos.+- **`ImageMotionMenu.tsx`** para modo foto: position pad (X/Y), device picker, presets, image upload.+- **Ctrl+scroll zoom** en phone overlay con badge indicador.++### Audio+- **Multi-track** (hasta `MAX_AUDIO_TRACKS = 5`).+- **Cada track** (`types/audio.types.ts`): id, audioId, name, startTime, duration, volume, loop, trimStart.+- **HTMLAudio elements** sincronizados con `videoRef.currentTime` (sync ±0.1s).+- **Per-track volume + master volume** multiplicativos.+- **Auto-trim** si el audio excede `videoDuration` (`AudioTrimModal`).+- **Mute original** audio (toggle global o por-clip en multi-video).+- **Formatos soportados**: `audio/mpeg`, `audio/wav`, `audio/ogg`, `audio/aac`, `audio/m4a` (max 10MB).++### Camera overlay (picture-in-picture)+- **`CameraConfig`** (`types/camera.types.ts`): enabled, deviceId, shape (`squircle`/`circle`/`square`), size, position, corner (`top-left`/`top-right`/`bottom-left`/`bottom-right`/`custom`), mirror.+- **`CameraMenu.tsx`** + **`FloatingCameraPreview.tsx`** para previsualizar y arrastrar.+- En `VideoCanvas.drawFrame`, `drawCameraOverlay` pinta el camera frame con shape clipping + shadow sobre el canvas final.++### Cursor+- **Grabado** durante recording (vía `CaptureController` API cuando hay soporte).+- **`CursorConfig`** (`types/cursor.types.ts`): style (`mac`/`windows`/`dot`/`none`), color, size, smoothing, clickEffect (`ripple`/`ring`/`none`).+- **Interpolación** entre keyframes con `easeInOutCubic` (`interpolateCursorPosition`).+- Reemplazo visual del cursor nativo en preview/export.++### Video multi-clip+- **`VideoTrackClip`** (`types/video-track.types.ts`): id, libraryVideoId, name, startTime, duration, trimStart, trimEnd, thumbnailUrl, hasCamera.+- **Helpers**: `calculateTotalDuration`, `findNextClipPosition`, `getClipAtTime`, `doClipsOverlap`.+- **Multi-clip playback** (`app/[locale]/(editor)/editor/page.tsx:2042-2247`): un solo `<video>` element que swappea el `src` al cruzar clip boundaries; `updateTimeSmoothRef` con `requestAnimationFrame` traduce video-time → timeline-time.+- **Clips en `videosLibrary`** con `hasAudio` flag per-clip.++### Exportación+- **Calidades** (`lib/constants.ts`): 4K (3840×2160@30), 2K (2560×1440@30), 1080p (1920×1080@30), 720p (1280×720@30), 480p (854×480@24), GIF, WebM-alpha.+- **MP4 (H.264)**: `@ffmpeg/ffmpeg` (WASM) + `@ffmpeg/util` (FFmpeg.wasm en `public/ffmpeg/`).+- **WebM (VP9) con transparencia**: `mediabunny` (Output + Mp4OutputFormat + BufferTarget + CanvasSource).+- **Image export** (modo photo): `html-to-image` (`toBlob`) con escalado a dimensiones export.+- **PNG/WEBP/JPG/AVIF**: vía `html-to-image` con `backgroundColor` opcional.+- **GIF**: pipeline FFmpeg.wasm.+- **Pipeline principal**: `useVideoExport` → dibuja cada frame con `canvasRef.current.drawFrame()` → muxa con FFmpeg (audio + encoding).+- **Transparencia**: `selectedWallpaper === -1` habilita alpha channel.++### Internacionalización+- **`next-intl`** con locales `es` (default), `en`, `ru` (`i18n.ts`).+- Rutas localizadas vía segmento `[locale]`.+- Cinco fuentes cargadas: Inter, Roboto, Poppins, Montserrat, DM_Sans (variables CSS).+- Traducciones en `messages/{es,en,ru}.json`.++### Autenticación+- **Supabase Auth** (OAuth Google/GitHub/Twitch) — `utils/supabase/` con clientes `client.ts`/`server.ts`/`middleware.ts`.+- Hook `useAuth` con `AuthProvider`, `user`, `profile`, `signOut`.+- Avatar fallback: `https://api.dicebear.com/7.x/initials/svg?seed={name}`.+- Tabla `user_profiles` con `first_name`, `last_name`, `avatar_url`, `provider`.++### Home / Landing+- **`<Hero />`** con upload (video o imagen) → guarda en `video-upload-cache`/`image-upload-cache` y redirige a `/editor?mode=video|photo`.+- **`<VideoHero />`** demo video loop con blur gradients.+- **`<InteractiveRecordingSteps />`** (3 steps) inicia recording via `RecordingContext`.+- **`<EditorPreview />`** con Atropos parallax.+- **`<CarouselDemos />`** con 8 demo videos + 12 imágenes.+- **`<HeroScrollMask />`** GSAP ScrollTrigger pinned animation.+- **`<BannerCTA />`** con spotlight hover effect.+- **`<DonationCard />`** link a `/donate` con Yape/Visa/QR.++---++## 3. Stack tecnológico++### Frontend+- **Framework**: Next.js 16.1.6 (App Router) · React 19.2 · TypeScript 5+- **Estilos**: Tailwind CSS 4 (`@tailwindcss/postcss`), `tw-animate-css`, `class-variance-authority`, `tailwind-merge`, `clsx`+- **UI primitives**: Radix UI (`@radix-ui/react-dialog`, `react-dropdown-menu`), `radix-ui`, shadcn (`components.json`), iconos `lucide-react` y `@iconify/react`+- **Animaciones**: Framer Motion 12, GSAP 3.15 + ScrollTrigger, Atropos (parallax), Swapy (drag-reorder)+- **3D / gráficos**: Three.js 0.184 + `@types/three` (WebGL renderer offscreen para perspective 3D y motion phone)+- **Video / media**:+ - `@ffmpeg/ffmpeg` + `@ffmpeg/core` + `@ffmpeg/util` (servidos desde `public/ffmpeg/`)+ - `mediabunny` (pipeline de video optimizado MP4/WebM)+ - `html-to-image` (export de mockups DOM → imagen)+- **i18n**: `next-intl` 4+- **Auth / data**: `@supabase/ssr`, `@supabase/supabase-js`++### Subproyecto `openvid-back/` (opcional, no prioritario)+Servicio independiente para renderizado headless en servidor (NestJS + BullMQ + Redis + Remotion + Prisma + Supabase). Existe como referencia/contrato para exportaciones asíncronas; el editor no lo requiere. Ver `BACKEND_SPEC.md`/`BACKEND_TESTING.md` si se necesita profundizar.++### Almacenamiento (cliente)+- **IndexedDB** (3 DBs):+ - `openvid-videos-library` (DB_VERSION 3) — biblioteca de videos grabados y subidos, con thumbnails, audio flags, cleanup 60 días.+ - `openvid-uploaded-videos` (DB_VERSION 2) — videos recién subidos en tránsito.+ - DB de `useScreenRecording` para el video "current".+- **LocalStorage**:+ - `openvid-uploaded-images` — imágenes recientes de background.+ - `openvid-elements-uploads` — imágenes subidas para usar como elementos del canvas.+- **Caché en memoria**: `Map<id, Blob/HTMLImageElement/HTMLAudioElement` para videos library, element images, SVG images, audio tracks, thumbnails.++---++## 4. Estructura de carpetas++```+openvidshot/+├── app/ # Next.js App Router (frontend)+│ ├── api/+│ │ └── photos/route.ts # Proxy Unsplash/Pexels/Pixabay (search + curated, cache 5min)+│ ├── components/ # Componentes de aplicación (no shadcn)+│ │ ├── common/ # Header, Footer, UserMenu, LanguageSwitcher, MobileMenu+│ │ ├── seo/ # StructuredData (JSON-LD: WebApp + Organization)+│ │ └── ui/+│ │ ├── editor/ # Núcleo del editor (ver §5)+│ │ │ ├── mockups/ # 18+ componentes React de mockups+│ │ │ └── templates-motion/ # Plantillas de animación (Phone)+│ │ ├── home/ # Landing (Hero, Demo, BannerCTA, RecordingSteps, ...)+│ │ ├── floating/ # FloatingCameraPreview, RecordingOverlay, ExportOverlay+│ │ └── ... # AspectRatioSelect, BackgroundColorEditor, ExportDropdown, PhotoPicker, RecordingSetup, SidebarTool, Skeleton, SliderControl, TabButton, TemplateEditorShell, WalpaperSections+│ ├── config/env.ts # ENV tipado (unsplash, pexels, pixabay keys)+│ ├── contexts/MotionContext.tsx # Estado global de motion/3D phone+│ ├── [locale]/+│ │ ├── (auth)/login/ # Página de login+│ │ ├── (editor)/editor/ # Página principal del editor (page.tsx ~3000 líneas)+│ │ ├── (home)/ # Landing + /donate (DonateClient)+│ │ ├── (legal)/privacy, terms/+│ │ ├── auth/callback/route.ts # OAuth callback de Supabase+│ │ └── layout.tsx # Providers: NextIntlClientProvider + TooltipProvider+│ ├── globals.css # Tailwind 4 base + tokens+│ ├── layout.tsx, robots.ts, sitemap.ts, not-found.tsx+│ └── favicon.ico+│+├── components/ # Componentes compartidos / shadcn-ui+│ ├── ui/ # button, input, select, popover, tooltip, dropdown-menu, alert,+│ │ # toggle, hover-card, LoadingSpinner, DropImage, CtxMenuItem,+│ │ # GitHubStars, ProgressiveImg, RotationHandleIcon, SectionToggle,+│ │ # TrackVolumeSlider, tooltip-action, SidebarTool, ...+│ ├── canvas-svg/ # SVG inlines del canvas (iconos categorizados)+│ └── cursor-svg/ # SVGs de cursores animados (Mac/Windows/Dot)+│+├── hooks/ # React hooks de dominio+│ ├── RecordingContext.tsx # Provider de grabación + Alt+S/Alt+D shortcuts+│ ├── useAuth.tsx # Sesión Supabase + AuthProvider+│ ├── useScreenCapture.ts # Captura de pantalla (imagen)+│ ├── useScreenRecording.ts # Grabación de pantalla (video) con camera + audio+│ ├── useVideoUpload.ts / useVideoThumbnails.ts / useVideoExport.ts+│ ├── useImageExport.ts / useImageProjects.ts+│ ├── useEditorMode.ts # Lee `?mode=` de URL+│ ├── useUndoRedo.ts # History stack (max 50)+│ ├── useDebounce.ts+│+├── lib/ # Lógica pura, utils y catálogos+│ ├── animation-core.ts # NRX/NRY neutral pose, STYLE_CFG, idleScript+│ ├── canvas-elements.config.ts # SVG_CATEGORIES, IMAGE_CATEGORIES, pinned items+│ ├── canvas.utils.ts # drawRoundedRect, calculateScaledPadding, applyCanvasBackground,+│ │ # getAspectRatioStyle/Number/MaxWidth, calculateSmoothZoom+│ ├── canvas-icons/ # action, editor, navigation, status icons+│ ├── color.utils.ts+│ ├── constants.ts # QUALITY_SETTINGS, VIDEO_Z_INDEX, BOTTOM_ONLY_RADIUS_MOCKUPS,+│ │ # SELF_SHADOWING_MOCKUPS, TIMELINE_ZOOM_SCALE, MIN_TRIM_DURATION+│ ├── layers.utils.ts # buildLayerNames, buildGroupNumbers+│ ├── mockup-canvas/ # 18+ canvas renderers (chrome, macos*, s24, vscode, glass*)+│ │ # + types.ts + shared.ts + index.ts barrel+│ ├── mockup-canvas.utils.ts # drawMockupToCanvas (entry point)+│ ├── mockup-data.tsx # MOCKUPS array con preview React de cada mockup+│ ├── mockup-previews.tsx # React preview components (None/Macos/Brave/Chrome/...)+│ ├── perspective3d.ts # Three.js offscreen WebGL renderer (singleton)+│ ├── photo-providers.ts # Unsplash/Pexels/Pixabay config+│ ├── template-registry.ts # TEMPLATES: soloVideoTemplate + phoneTemplate+│ ├── thumbnail-cache.ts # Video thumbnails persistence+│ ├── video-cache-utils.ts # Helpers+│ ├── image-projects-cache.ts # IndexedDB wrapper para ImageProject (modo photo)+│ ├── image-upload-cache.ts # IndexedDB cache para uploads+│ ├── video-upload-cache.ts # IndexedDB cache para uploads de video+│ ├── videos-library.ts # IndexedDB library wrapper (DB 'openvid-videos-library', v3)+│ ├── video.utils.ts # formatTime, getZoomMultiplier, ensureVideoReady+│ ├── wallpaper.catalog.ts # 100+ fondos (desktop/gradient/minimal/pattern)+│ ├── wallpaper.utils.ts # getWallpaperUrl, getWallpaperPreviewUrl+│ ├── utils.ts # cn() (twMerge + clsx)+│ └── index.ts # Barrel+│+├── types/ # Tipos TypeScript del dominio (uno por feature)+│ ├── audio.types.ts # AudioTrack, UploadedAudio, AudioConfig, MAX_AUDIO_TRACKS+│ ├── background.types.ts # BackgroundColorConfig+│ ├── camera.types.ts # CameraConfig, CameraShape, CameraCorner, DEFAULT_CAMERA_CONFIG+│ ├── canvas-elements.types.ts # CanvasElement (svg/image/text), Svg/Image/TextElement+│ ├── control-panel.types.ts # ControlPanelProps (props del panel reactivo)+│ ├── cursor.types.ts # CursorKeyframe, CursorConfig, interpolateCursorPosition+│ ├── editor-mode.types.ts # EditorMode ('video'|'photo'), EditorModeConfig+│ ├── editor-state.types.ts # EditorState (full undo/redo snapshot), createInitialEditorState+│ ├── editor.types.ts # Tool, BackgroundTab, AspectRatio, CropArea, VideoTransform,+│ │ # VideoCanvasHandle, VideoCanvasProps, VideoThumbnail+│ ├── image-project.types.ts # ImageProjectPreview (modo photo)+│ ├── ImageMask.types.ts # MaskPreset, ImageMaskEditorProps+│ ├── layers.types.ts # LayersPanelProps, ContextMenuProps+│ ├── mockup.types.ts # MockupConfig (darkMode/frameColor/url/headerScale/...),+│ │ # MockupFeatures, MockupCategory, DEFAULT_MOCKUP_CONFIG+│ ├── motion.types.ts # MotionTemplate, ScriptFn, AnimMode, MotionStyle, AV+│ ├── photo.types.ts # Preview3DConfig, ImageMaskConfig, PREVIEW_CONFIGS,+│ │ # PREVIEW_TO_PHONE_OFFSET (front/top-left-angle/...)+│ ├── player-control.types.ts # PlayerControlsProps, MIN_ZOOM, MAX_ZOOM, ZOOM_STEP+│ ├── recording.types.ts # RecordingState, RecordingResult, RecordingContextType+│ ├── timeline.types.ts # TrimRange, TimelineProps+│ ├── tool-sidebar.types.ts # ToolsSidebarProps+│ ├── video-track.types.ts # VideoTrackClip + calculateTotalDuration/findNextClipPosition/+│ │ # getClipAtTime/doClipsOverlap+│ ├── video.types.ts # VideoData, LibraryVideo, LibraryVideoInfo+│ ├── zoom.types.ts # ZoomFragment, ZoomPhaseState, easeOutQuart,+│ │ # calculateZoomPhaseState, zoomLevelToFactor, speedToTransitionMs+│ └── index.ts # Barrel reexport+│+├── utils/supabase/ # Clientes Supabase (client / server / middleware SSR)+│+├── messages/ # Traducciones i18n+│ ├── en.json · es.json · ru.json+│+├── public/ # Assets estáticos+│ ├── ffmpeg/ # ffmpeg-core.js/.wasm (servidos COOP/COEP)+│ ├── images/+│ │ ├── backgrounds/ (desktop, gradient, minimal, pattern)+│ │ ├── carousel/ (decorators, images, videos)+│ │ ├── metadata/ (favicon, OG preview, apple, shortcut)+│ │ ├── mockups/ (bg-browser, bg-ide, bg-mobile)+│ │ ├── pages/ (hero, demos, login, qr, posters, openvid)+│ │ └── scroll/ (logos sponsors/decoradores)+│ ├── models/ # glTF/GLB: iphone-15-pro-max.glb, samsung-galaxy-s25-ultra.glb, phone-gltf.json+│ ├── svg/ # logo, mockups, cursores, openvid+│ ├── videos/ # Previews de features (audio, mockup, zoom, ...)+│ ├── elements/images/ # assets, overlays, stickers+│ └── llms.txt+│+├── openvid-back/ # Subproyecto auxiliar (render headless, no prioritario)+│+├── .agents/skills/ # Skills de IA (3d-web-experience, gsap, react-three-fiber)+├── .github/ # CI/PR templates+│+├── i18n.ts # Config next-intl (locales es/en/ru)+├── navigation.ts # Helpers de navegación localizada+├── proxy.ts # Proxy / middleware adicional+├── next.config.ts # Remote images + headers COOP/COEP+├── tsconfig.json · eslint.config.mjs · postcss.config.mjs+├── components.json # Config shadcn-ui+├── supabase-setup.sql # Script SQL inicial (tablas + RLS)+├── BACKEND_SPEC.md # Especificación detallada del backend (referencia)+├── BACKEND_TESTING.md # Guía de testing del backend (referencia)+├── README.md · LICENSE.md+└── package.json (Next 16, React 19, FFmpeg.wasm, Three, GSAP, Framer)+```++---++## 5. Núcleo del editor++### 5.1 `app/components/ui/editor/` — Componentes principales++| Componente | Rol |+|---|---|+| `VideoCanvas.tsx` (~2400 líneas) | **Canvas principal**. Maneja `<video>` + `<canvas>` de export + `CanvasElementsLayer` + `MockupWrapper` + `Phone3DViewer` (dynamic, ssr:false). Expone `VideoCanvasHandle` (getExportCanvas/drawFrame/getPreviewContainer/clearAllSelection/restoreSelectionState) vía `forwardRef`. Lee `MotionContext` para phone overlay. Implementa `drawFrame` que renderiza a canvas con zoom 3D, mockup frame, video mask, canvas elements, camera overlay, motion phone bezel. Drag/rotate handles para video transform. |+| `CanvasElementsLayer.tsx` | Capa de elementos (shapes, text, SVG, imágenes) sobre el canvas; inline text editor Figma-style. |+| `Timeline.tsx` | Timeline con trim, video clips, zoom fragments, audio tracks. Pan via framer-motion, ghosts en drag. |+| `PlayerControls.tsx` | Transport: play/pause, skip ±5s, aspect ratio, crop, zoom level, fullscreen, video mask editor. |+| `EditorTopBar.tsx` | Logo, undo/redo, export dropdown (video/image), user menu, alert de export error. |+| `ToolsSidebar.tsx` | Sidebar vertical con tools: screenshot, mockup, motion, zoom, audio, videos, camera, cursor, elements, history. |+| `MobileToolsMenu.tsx` | Menú de tools en mobile (Dialog bottom sheet). |+| `MobileControlPanel.tsx` | ControlPanel en mobile via Dialog bottom sheet. |+| `ControlPanel.tsx` | Panel reactivo principal (lazy-loaded, muchos sub-skeletons). Cambia contenido según `activeTool`. |+| `LabelSidebar.tsx` | Etiquetas laterales (Video/Zoom/Audio) en el timeline. |+| `MockupMenu.tsx` + `mockups/*` | Selector de mockups por categoría + renderers. |+| `MotionMenu.tsx` + `ImageMotionMenu.tsx` + `templates-motion/Phone.tsx` | Plantillas motion (phone) para video e image mode. |+| `CameraMenu.tsx` | Configuración de camera overlay (shape, corner, size, mirror). |+| `Phone3DViewer.tsx` (~836 líneas) | Three.js viewer para el phone overlay con GSAP master timeline. |+| `FloatingCameraPreview.tsx` | Preview flotante arrastrable de la cámara (sidebar). |+| `ZoomFragmentEditor.tsx` / `ZoomFragmentTrackItem.tsx` / `ZoomGlobalConfig.tsx` | Editor de focus point + track item + lista global. |+| `AudioMenu.tsx` / `AudioFragmentTrackItem.tsx` / `AudioTrimModal.tsx` | Multi-track de audio (max 5). |+| `VideoClipTrackItem.tsx` / `VideoCropperModal.tsx` / `VideosMenu.tsx` | Clips de video (multi-clip) + cropper + library. |+| `ImageCropperModal.tsx` / `ImageMaskEditor.tsx` / `GetMediaMaskStyles.tsx` | Crop + mask + helpers. |+| `ElementsMenu.tsx` (3 tabs: text/elements/uploads) | Shapes, SVG, imágenes, texto. |+| `CursorMenu.tsx` | Configuración del cursor (style, color, size, click effect). |+| `LayersPanel.tsx` (~927 líneas) | Panel de capas con drag-reorder, lock, hide, group/ungroup, multi-select. |+| `HistoryMenu.tsx` | Lista de proyectos de imagen (modo photo). |+| `ContextMenu.tsx` | Menú contextual de las capas (bring to front, send to back, group, delete). |+| `EditorHoverTooltip.tsx` | Tooltip on-canvas con shortcuts (Ctrl+Scroll zoom, Ctrl+V paste). |+| `PhotoEditorPlaceholder.tsx` | Placeholder del editor de foto (debajo del canvas en photo mode). |+| `PlaceholderEditor.tsx` | Placeholder inicial antes de subir archivo. |+| `Skeleton.tsx` | Skeletons de carga para cada menu. |+| `CanvasElementsLayer.tsx` | Capa DOM de elementos con text editor inline. |++### 5.2 `app/[locale]/(editor)/editor/page.tsx` — Orquestador (~3000 líneas)++El componente `Editor` raíz coordina todo el estado y los hooks del editor:++**Estados principales** (todos como `useState`):+- Editor mode: `useEditorMode` lee `?mode=` de URL+- Auth: `useAuth`+- Undo/Redo: `useUndoRedo<EditorState>` (centralizado, sincroniza con `editorState` en `useEffect`)+- Image state: `imageUrl`, `imageRef`, `imageExportProgress`+- Capture: `useScreenCapture`+- Image projects: `useImageProjects` (IndexedDB)+- 3D preview: `imageTransform`, `apply3DToBackground`+- **UI state**: `activeTool`, `backgroundTab`, `selectedWallpaper`, `backgroundBlur`, `padding`, `roundedCorners`, `shadows`, `isControlPanelOpen`+- **Video transform**: `videoTransform` (rotation, translateX, translateY)+- **Uploaded images**: array + LocalStorage sync+- **Background color/gradient**: `backgroundColorConfig`+- **Aspect ratio**: `aspectRatio`, `customDimensions`, `isFullscreen`, `cropArea`+- **Video state**: `videoUrl`, `videoId`, `videoDuration`, `currentTime`, `isPlaying`+- **Timeline state**: `timelineZoom`, `isDraggingPlayhead`, `trimRange`, `scrubTime`+- **Zoom fragments**: `zoomFragments`, `selectedZoomFragmentId`+- **Mockup state**: `mockupId`, `mockupConfig`+- **Canvas elements**: `canvasElements`, `selectedElementId`+- **Audio state**: `uploadedAudios`, `audioTracks`, `muteOriginalAudio`, `masterVolume`, `selectedAudioTrackId`+- **Video clips (multi-video)**: `videoClips`, `videosLibraryRefresh`, blobs/urls en refs+- **Camera state**: `cameraConfig`, `cameraUrl`++**Refs clave** (múltiples `useRef`):+- `videoRef`, `canvasRef`, `editorAreaRef`+- `zoomFragmentsRef`, `videoClipsRef`, `muteOriginalAudioRef` (evitar stale closures)+- `videoBlobsRef`, `videoUrlsRef`, `activeClipIdRef`, `activeClipDataRef`+- `clipAudioStateRef`, `audioElementsRef`+- `clipSwitchTimeRef`, `isSeekingToClipRef`, `isSwitchingClipRef`, `justEndedRef`+- `multiDragStartRef`, `wasDragRef`, `pendingCollapseRef`+- `animationFrameRef`, `updateTimeSmoothRef`++**Flujo crítico de playback (multi-clip)** (`page.tsx:2042-2247`):+1. `updateTimeSmoothRef` corre en `requestAnimationFrame` mientras `isPlaying`.+2. Detecta clip activo con `getClipAtTime(videoClips, timelineTime)`.+3. Si cambia el clip: pausa, swap de `videoRef.current.src` al nuevo clip, espera `canplay`, seek a `clipTime`, play.+4. Si llega al `trimEnd`: pasa al siguiente clip o pausa.+5. Sincroniza `audioElements` con `syncAudioPlayback(timelineTime, playing)`.++**Auto-save (modo foto)**: `autoSaveCurrentProject` con debounce 3s → `saveCurrentProject` con todo el estado.++**Export** (`handleExport`, `page.tsx:1352-1461`):+1. Log del "Recipe JSON" para tests del backend (no se envía — solo debug).+2. Llama `exportVideo({ quality, videoBlob, transparentBackground, trim, muteOriginalAudio, audioTracks, masterVolume, videoClips, videoClipBlobs, clipAudioStates })`.+3. `useVideoExport` orquesta: prepara canvas, codifica con MediaBunny, mezcla audio con FFmpeg.wasm, descarga blob.++**Keyboard shortcuts** (`page.tsx:1981-2009`, `2660-2735`):+- `Ctrl/Cmd+Z` undo, `Ctrl/Cmd+Shift+Z` / `Ctrl/Cmd+Y` redo+- `T` text tool (crosshair para colocar texto)+- `Ctrl/Cmd+C/V` copy/paste elementos+- `Delete/Backspace` eliminar selección (elemento/video clip/audio track/zoom fragment)+- `Escape` deseleccionar+- `Space/K` play/pause (en `PlayerControls`)+- `Ctrl+V` paste image (solo photo mode)+- Alt+S start recording, Alt+D stop recording (en `RecordingContext`)++**Render**:+```jsx+<div className="flex flex-col h-screen">+ <div className="flex flex-1">+ <ToolsSidebar ... />+ <AnimatePresence><ControlPanel ... /></AnimatePresence>+ <div ref={editorAreaRef}>+ <VideoCanvas ... layersPanelToolbar={<EditorTopBar ... />} />+ {isVideoMode && (+ <PlayerControls ... />+ <Timeline ... />+ )}+ {isPhotoMode && <PhotoEditorPlaceholder ... />}+ </div>+ </div>+ <MobileToolsMenu ... />+ <MobileControlPanel ... />+</div>+```++### 5.3 Contexts y providers++- **`MotionContext`** (`app/contexts/MotionContext.tsx`) — state global de motion templates, intensity, style, animMode, image phone X/Y/scale/rotation, device. Hook `useMotionContext`.+- **`AuthProvider`** (`hooks/useAuth.tsx`) — sesión Supabase + user profile.+- **`RecordingProvider`** (`hooks/RecordingContext.tsx`) — wrapper de `useScreenRecording` con shortcuts Alt+S/Alt+D.+- **`TooltipProvider`** (`components/ui/tooltip.tsx`) — Radix tooltip con `delayDuration={200}`.+- **`NextIntlClientProvider`** en `[locale]/layout.tsx` para i18n.++Orden de providers en `app/[locale]/(editor)/layout.tsx`:+```jsx+<AuthProvider>+ <RecordingProvider>+ <MotionProvider>+ <div>{children}</div>+ </MotionProvider>+ <RecordingOverlay />+ </RecordingProvider>+</AuthProvider>+```++### 5.4 Hooks destacados++- **`useUndoRedo<T>(initialState)`** — history stack (past/present/future) con `MAX_HISTORY_SIZE=50`. `setState` con `skipHistory` flag.+- **`useEditorMode`** — lee `?mode=` de URL, expone `isVideoMode`/`isPhotoMode`/`setMode`.+- **`useVideoExport(videoRef, canvasRef)`** — pipeline de export con MediaBunny + FFmpeg.wasm. Maneja cancellation token.+- **`useVideoThumbnails(url, duration, options)`** — genera thumbnails cada 0.1s, calidad "low"/"high".+- **`useImageProjects`** — CRUD de proyectos de imagen en IndexedDB (auto-save 3s).+- **`useScreenRecording`** — estado de grabación, countdown, camera stream, cursor data.++---++## 6. Subproyecto `openvid-back/` (referencia)++Servicio independiente para renderizado headless en servidor (NestJS + BullMQ + Redis + Remotion + Prisma + Supabase). Existe como referencia/contrato; el editor funciona sin él. Ver `BACKEND_SPEC.md`/`BACKEND_TESTING.md` si se necesita profundizar.++---++## 7. Scripts++### Frontend (raíz)+```bash+pnpm install+pnpm dev # next dev+pnpm build # next build+pnpm start # next start+pnpm lint # eslint+```++### `openvid-back/` (referencia, opcional)+```bash+pnpm install+pnpm start:dev # nest start --watch+pnpm build # nest build+pnpm start:prod # node dist/main+pnpm test / test:e2e / test:cov+pnpm lint / format+```++---++## 8. Variables de entorno++- **Frontend**: ver `.env.example` (credenciales Supabase: `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`, claves de Unsplash/Pexels/Pixabay en `app/config/env.ts`).+- **`openvid-back/`** (referencia): `openvid-back/docker/.env.example` (Redis, Supabase service role, Storage buckets, DATABASE_URL para Prisma/Postgres).++---++## 9. Notas útiles para trabajar en el código++### Arquitectura general+- **App Router con route groups**: `(auth)`, `(editor)`, `(home)`, `(legal)` agrupan layouts sin afectar la URL.+- **Editor monolítico**: `page.tsx` del editor es ~3000 líneas — la mayoría es state local y handlers. Los subcomponentes (`VideoCanvas`, `Timeline`, `ControlPanel`) son los que tienen la lógica pesada.+- **Lazy loading**: `ControlPanel`, `Timeline`, `ExportOverlay`, `VideoCropperModal`, `ImageCropperModal`, `PhotoEditorPlaceholder`, y muchos menús dentro de `ControlPanel` usan `lazy()` o `dynamic()` con `ssr: false` para reducir bundle inicial.++### Patrones de código+- **Headers COOP/COEP** se setean globalmente en `next.config.ts` — necesarios para FFmpeg.wasm con `SharedArrayBuffer`.+- **Tres cachés IndexedDB distintas** (no mezclar):+ - `videos-library.ts` → `openvid-videos-library` (DB_VERSION 3): biblioteca persistente con thumbnails, audio flags.+ - `video-upload-cache.ts` → `openvid-uploaded-videos` (DB_VERSION 2): tránsito tras upload desde landing.+ - `useScreenRecording` → DB propia para `currentVideo` (cleanup 7 días).+- **Mockups duplicados a propósito**: cada mockup vive como React (`app/components/ui/editor/mockups/*.tsx`) y como canvas renderer (`lib/mockup-canvas/*.ts`) para preview en DOM y export a canvas/video. El catálogo compartido está en `lib/mockup-data.tsx` (lista MOCKUPS).+- **Fidelidad visual**: el `VideoCanvas.drawFrame` debe reproducir fielmente lo que se ve en el DOM. Cualquier cambio en un mockup React debe reflejarse en su contraparte canvas.+- **`VIDEO_Z_INDEX = 1000`**: cualquier elemento con `zIndex < 1000` va detrás del video, `>= 1000` delante. Usar `bringToFront`/`sendToBack` que respetan este límite.+- **Tipos por feature**: cada dominio (zoom, mockup, audio, camera, ...) tiene su propio `*.types.ts` en `types/`; el barrel `types/index.ts` reexporta.+- **shadcn-ui** está activo (`components.json`) — primitives en `components/ui/`. Para nuevos componentes usar `npx shadcn@latest add <name>`.+- **Idioma por defecto**: `es` (ver `i18n.ts`). Todos los textos visibles usan `useTranslations("namespace")` de `next-intl`.+- **Refs vs State**: el editor usa muchos `useRef` para evitar stale closures en `requestAnimationFrame`, drag handlers, y event listeners globales.+- **i18n keys**: están en `messages/{es,en,ru}.json` — agregar clave en los 3 al añadir un texto nuevo.+- **Animaciones GSAP**: se registran plugins (`ScrollTrigger` en home, `GLTFLoader` en Phone3DViewer) — limpiar con `gsap.matchMedia()` o `killTweensOf`.+- **Three.js singleton**: `lib/perspective3d.ts` mantiene un único `WebGLRenderer`/`Scene`/`Camera` reutilizado entre renders; llamar `disposePerspective3D()` en cleanup.+- **Framer Motion**: usado para AnimatePresence (panel open/close, export overlay, hover).+- **Atropos**: solo en `EditorPreview.tsx` (home) para parallax 3D.+- **Swapy**: instalado pero no usado actualmente (en `package.json`).++### Estructura de un mockup nuevo+1. Crear componente React en `app/components/ui/editor/mockups/{name}Mockup.tsx`.+2. Crear renderer canvas en `lib/mockup-canvas/{name}.ts` (misma forma de API).+3. Agregar preview React en `lib/mockup-previews.tsx`.+4. Registrar en `MOCKUPS` (`lib/mockup-data.tsx`) con `id`, `name`, `category`, `features`, `defaultConfig`, `preview`.+5. Agregar a `BOTTOM_ONLY_RADIUS_MOCKUPS` o `SELF_SHADOWING_MOCKUPS` en `lib/constants.ts` si necesita tratamiento especial de border-radius/shadow.+6. Verificar que `MockupWrapper.tsx` lo importe.++### Estructura de un motion template nuevo+1. Definir `MotionTemplate` en `app/components/ui/editor/templates-motion/{name}.tsx` con `script: ScriptFn` (función que devuelve `gsap.core.Timeline`).+2. Registrar en `lib/template-registry.ts` (descomentar línea correspondiente).+3. Si tiene panel de edición, exponer `EditorPanel` en el template.++### Estructura de un nuevo tool en el sidebar+1. Agregar el tool al union type `Tool` en `types/editor.types.ts`.+2. Agregar la entrada en `ToolsSidebar.tsx` (icono + handler + scroll ref).+3. Si necesita panel propio, agregar un componente lazy en `ControlPanel.tsx` con su `Skeleton`.diff --git a/proxy.ts b/proxy.tsindex 23d6f83..b88575a 100644--- a/proxy.ts+++ b/proxy.ts@@ -26,6 +26,6 @@ export default async function proxy(request: NextRequest) {export const config = {matcher: [- '/((?!api|ffmpeg|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|.*\\.(?:svg|png|jpg|jpeg|gif|webp|mp4|avif|webm|wasm|js)$).*)'+ '/((?!api|ffmpeg|models|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|.*\\.(?:svg|png|jpg|jpeg|gif|webp|mp4|avif|webm|wasm|js|glb|gltf|json)$).*)'],};\ No newline at end of filediff --git a/skills-lock.json b/skills-lock.jsonnew file mode 100644index 0000000..7b1a916--- /dev/null+++ b/skills-lock.json@@ -0,0 +1,23 @@+{+ "version": 1,+ "skills": {+ "3d-web-experience": {+ "source": "sickn33/antigravity-awesome-skills",+ "sourceType": "github",+ "skillPath": "skills/3d-web-experience/SKILL.md",+ "computedHash": "87c4b32078381ee1e6df164ddd5c28dd67fc7552431a7415626e63b8cf74b11a"+ },+ "gsap": {+ "source": "heygen-com/hyperframes",+ "sourceType": "github",+ "skillPath": "skills/gsap/SKILL.md",+ "computedHash": "ef2658b3705d3fd5c8e38d197b31521553a0bee3b40bda2ab70bf22bd6b88854"+ },+ "react-three-fiber": {+ "source": "vercel-labs/json-render",+ "sourceType": "github",+ "skillPath": "skills/react-three-fiber/SKILL.md",+ "computedHash": "33cfac131cbe9c89b14c4b49ca01e0b0a4a3f9c23bb6c81ac0514143703283e8"+ }+ }+}