Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.local.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
GEMINI_API_KEY=
UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=
3 changes: 0 additions & 3 deletions .eslintrc.json

This file was deleted.

45 changes: 45 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
name: CI

on:
push:
branches:
- main
pull_request:

jobs:
verify:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm

- name: Install dependencies
run: npm ci

- name: Typecheck
run: npm run typecheck

- name: Lint
run: npm run lint

- name: Test
run: npm test

- name: Install Playwright browser
run: npx playwright install --with-deps chromium

- name: Test e2e
run: npm run test:e2e

- name: Build
run: npm run build

- name: Audit dependencies
run: npm audit --omit=dev --audit-level=moderate
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@

# testing
/coverage
/test-results
/playwright-report
/.lighthouseci

# next.js
/.next/
Expand Down
2,895 changes: 0 additions & 2,895 deletions .lighthouseci/lhr-1772957950506.html

This file was deleted.

10,091 changes: 0 additions & 10,091 deletions .lighthouseci/lhr-1772957950506.json

This file was deleted.

52 changes: 31 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
# MotionCode

**The Advanced Motion Intelligence Platform.**
**Video motion analysis for production code snippets.**

MotionCode is a sophisticated tool designed to bridge the gap between video inspiration and production-ready code. By leveraging AI and advanced frame extraction, MotionCode analyzes animations and transitions from videos to generate clean, high-performance GSAP and Framer Motion code.
MotionCode helps turn video motion references into implementation-ready animation snippets. The browser extracts frames from supported media, the server-side Gemini endpoint analyzes those frames, and the app returns validated CSS, GSAP, Framer Motion, and React Spring code.



## ✨ Features
## Features

- **Video-to-Code Analysis**: Upload any video and extract animation patterns automatically.
- **GSAP & Framer Motion Output**: Get production-ready code snippets instantly.
- **Puter.js Integration**: Powered by Puter.js for robust, client-side intelligence.
- **Frame Extraction**: High-precision frame extraction using FFmpeg for deep analysis.
- **Modern UI**: Dark-themed, glassmorphic interface with smooth GSAP animations.
- **Code Preview**: Interactive Monaco editor for immediate code inspection and editing.
- **Video-to-Code Analysis**: Upload MP4, WebM, MOV, or GIF media and extract frames in the browser.
- **Server-Side Gemini Analysis**: `/api/analyze` sends extracted JPEG frames to Gemini using a server-only API key.
- **Validated Code Output**: Gemini responses are normalized before display as CSS, GSAP, Framer Motion, and React Spring snippets.
- **Usage Guardrails**: Free analysis requests are rate-limited before Gemini is called.
- **Modern UI**: Dark-themed upload, analysis, and code output panels built for motion review.

## 🚀 Getting Started
## Getting Started

### Prerequisites

- Node.js 18.x or later
- NPM, PNPM, or Yarn
- Node.js 20.19.x or newer
- npm

### Installation

Expand All @@ -34,11 +33,18 @@ MotionCode is a sophisticated tool designed to bridge the gap between video insp
2. **Install dependencies:**

```bash
npm install
npm ci
```

3. **Set up Environment Variables:**
Create a `.env.local` file based on `.env.local.example` (if required).

Create `.env.local` and provide the server-side Gemini key:

```bash
GEMINI_API_KEY=your_key_here
UPSTASH_REDIS_REST_URL=your_redis_rest_url
UPSTASH_REDIS_REST_TOKEN=your_redis_rest_token
```

4. **Run the development server:**

Expand All @@ -49,17 +55,21 @@ MotionCode is a sophisticated tool designed to bridge the gap between video insp
5. **Open the application:**
Navigate to [http://localhost:3000](http://localhost:3000) to see the platform in action.

## 🛠️ Built With
## Built With

- **Next.js 14** - React Framework
- **Next.js 16** - React Framework
- **GSAP** - Animation Library
- **Framer Motion** - Production-ready motion for React
- **Puter.js** - Cloud Computing & AI
- **FFmpeg.wasm** - Video processing in the browser
- **Framer Motion** - Motion library for React
- **Google Gemini API** - Server-side frame analysis
- **Zod** - Request and response validation
- **Tailwind CSS** - Styling
- **Monaco Editor** - Code editing experience
- **Vitest** - Unit testing

## Production Readiness

See [docs/production-readiness.md](docs/production-readiness.md) for the current production posture, required environment variables, security controls, verification commands, and known follow-up work.

## 📄 License
## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Expand Down
33 changes: 33 additions & 0 deletions app/api/analyze/prompt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
export function buildAnimationPrompt(frameCount: number): string {
return `
You are a frontend animation engineer analyzing ${frameCount} frames.

Analyze the motion and respond with Raw JSON only.
No markdown. No backticks. No explanation.

Return this exact JSON shape:
{
"intent": "hover",
"element": "button",
"duration_ms": 400,
"delay_ms": 0,
"easing": "cubic-bezier(0.4, 0, 0.2, 1)",
"loops": false,
"description": "One sentence description.",
"keyframes_detected": 4,
"performance_score": 90,
"gpu_accelerated": true,
"accessibility_note": "Add prefers-reduced-motion fallback.",
"css": ".el{transition:transform 400ms ease}",
"gsap": "gsap.to('.el',{duration:0.4,scale:0.95})",
"framer_motion": "const v={animate:{scale:0.95}}",
"react_spring": "const s=useSpring({scale:0.95})"
}

Rules:
- Keep code strings concise.
- Prefer transform and opacity.
- Include reduced-motion guidance.
- Do not include unsafe script tags or event handlers.
`.trim();
}
78 changes: 78 additions & 0 deletions app/api/analyze/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { NextResponse } from "next/server";
import { createHash } from "node:crypto";
import { analysisRequestSchema } from "@/app/api/analyze/schema";
import { publicErrorMessage, publicErrorStatus } from "@/lib/server/errors";
import { analyzeFramesWithGemini } from "@/lib/server/gemini";
import { getFreeUsageLimiter } from "@/lib/server/usage";

export const runtime = "nodejs";

const VERCEL_IDENTITY_HEADERS = ["x-vercel-forwarded-for"] as const;
const LOCAL_IDENTITY_HEADERS = [
"x-vercel-forwarded-for",
"x-real-ip",
"x-forwarded-for",
] as const;

function identityFromRequest(request: Request): string {
const headers =
process.env.VERCEL === "1"
? VERCEL_IDENTITY_HEADERS
: process.env.NODE_ENV !== "production"
? LOCAL_IDENTITY_HEADERS
: [];

for (const header of headers) {
const identity = firstHeaderValue(request.headers.get(header));

if (identity) {
return hashIdentity(identity);
}
}

if (process.env.NODE_ENV === "production") {
throw new Error("Trusted request identity is required for quota enforcement");
}

return hashIdentity("anonymous");
}

function firstHeaderValue(value: string | null): string | undefined {
return value?.split(",")[0]?.trim() || undefined;
}

function hashIdentity(identity: string): string {
return createHash("sha256").update(identity).digest("hex");
}

export async function POST(request: Request) {
try {
const body = await request.json();
const input = analysisRequestSchema.parse(body);
const usage = await getFreeUsageLimiter().consume(identityFromRequest(request));

if (!usage.allowed) {
return NextResponse.json(
{
error: "Daily analysis limit reached.",
limit: usage.limit,
remaining: usage.remaining,
},
{ status: 429 },
);
}

const result = await analyzeFramesWithGemini(input.frames);

return NextResponse.json(result);
} catch (error) {
console.error("[analyze]", {
error: error instanceof Error ? error.message : String(error),
});

return NextResponse.json(
{ error: publicErrorMessage(error) },
{ status: publicErrorStatus(error) },
);
}
}
20 changes: 20 additions & 0 deletions app/api/analyze/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { z } from "zod";
import {
animationAnalysisResultSchema,
numberFromNumericInput,
} from "@/lib/animationResult";

export const analysisRequestSchema = z
.object({
frames: z.array(z.string().min(1).max(1_000_000)).min(1).max(12),
frameCount: numberFromNumericInput(z.number().int().min(1).max(12)),
})
.refine(({ frames, frameCount }) => frames.length === frameCount, {
message: "frameCount must match frames length",
path: ["frameCount"],
});

export const analysisResponseSchema = animationAnalysisResultSchema;

export type AnalysisRequest = z.infer<typeof analysisRequestSchema>;
export type AnalysisResponse = z.infer<typeof analysisResponseSchema>;
Loading
Loading