🎥 Make videos programmatically with React
Add Rendering Lambda
ASchwad6d5431e106d4
diff --git a/packages/template-prompt-to-motion-graphics/deploy.mjs b/packages/template-prompt-to-motion-graphics/deploy.mjsindex 2dcc0bd8fe..6e97f921f0 100644--- a/packages/template-prompt-to-motion-graphics/deploy.mjs+++ b/packages/template-prompt-to-motion-graphics/deploy.mjs@@ -63,7 +63,7 @@ console.log(process.stdout.write("Deploying site... ");const { siteName } = await deploySite({bucketName,- entryPoint: path.join(process.cwd(), "src", "remotion", "index.ts"),+ entryPoint: path.join(process.cwd(), "src", "remotion", "index.tsx"),siteName: SITE_NAME,region: REGION,options: { webpackOverride },diff --git a/packages/template-prompt-to-motion-graphics/src/app/api/lambda/render/route.ts b/packages/template-prompt-to-motion-graphics/src/app/api/lambda/render/route.tsindex 822349c0b4..f811700d13 100644--- a/packages/template-prompt-to-motion-graphics/src/app/api/lambda/render/route.ts+++ b/packages/template-prompt-to-motion-graphics/src/app/api/lambda/render/route.ts@@ -10,6 +10,7 @@ import {SITE_NAME,TIMEOUT,} from "../../../../../config.mjs";+import { COMP_NAME } from "../../../../../types/constants";import { RenderRequest } from "../../../../../types/schema";import { executeApi } from "../../../../helpers/api-response";@@ -42,9 +43,9 @@ export const POST = executeApi<RenderMediaOnLambdaOutput, typeof RenderRequest>(}),region: REGION as AwsRegion,serveUrl: SITE_NAME,- composition: body.id,+ composition: COMP_NAME,inputProps: body.inputProps,- framesPerLambda: 10,+ framesPerLambda: 60,downloadBehavior: {type: "download",fileName: "video.mp4",diff --git a/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsx b/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsxindex 6d530481a7..70a4a4497d 100644--- a/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsx+++ b/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsx@@ -6,6 +6,7 @@ import { useSearchParams } from "next/navigation";import { Loader2 } from "lucide-react";import { CodeEditor } from "../../components/CodeEditor";import { AnimationPlayer } from "../../components/AnimationPlayer";+import { RenderControls } from "../../components/RenderControls";import { PageLayout } from "../../components/PageLayout";import {PromptInput,@@ -137,15 +138,18 @@ function GeneratePageContent() {isStreaming={isStreaming}streamPhase={streamPhase}/>- <AnimationPlayer- Component={Component}- durationInFrames={durationInFrames}- fps={fps}- isCompiling={isCompiling}- isStreaming={isStreaming}- error={apiError || error}- errorType={apiError ? "api" : "compilation"}- />+ <div className="flex flex-3 flex-col min-w-0 gap-4">+ <AnimationPlayer+ Component={Component}+ durationInFrames={durationInFrames}+ fps={fps}+ isCompiling={isCompiling}+ isStreaming={isStreaming}+ error={apiError || error}+ errorType={apiError ? "api" : "compilation"}+ />+ <RenderControls code={code} />+ </div></div><PromptInputdiff --git a/packages/template-prompt-to-motion-graphics/src/components/RenderControls.tsx b/packages/template-prompt-to-motion-graphics/src/components/RenderControls.tsxindex efc07a8514..d18c88de10 100644--- a/packages/template-prompt-to-motion-graphics/src/components/RenderControls.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/RenderControls.tsx@@ -1,52 +1,40 @@-import { z } from "zod";+"use client";+import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";import { DownloadButton } from "./DownloadButton";import { ErrorComp } from "./Error";import { ProgressBar } from "./ProgressBar";-import { COMP_NAME, CompositionProps } from "../../types/constants";import { useRendering } from "../helpers/use-rendering";export const RenderControls: React.FC<{- text: string;- setText: React.Dispatch<React.SetStateAction<string>>;- inputProps: z.infer<typeof CompositionProps>;-}> = ({ text, setText, inputProps }) => {- const { renderMedia, state, undo } = useRendering(COMP_NAME, inputProps);+ code: string;+}> = ({ code }) => {+ const { renderMedia, state, undo } = useRendering({ code });return (- <div className="border border-unfocused-border-color p-geist rounded-geist bg-background flex flex-col">+ <div className="flex flex-col gap-2">{state.status === "init" ||state.status === "invoking" ||state.status === "error" ? (- <div className="flex flex-col gap-geist-quarter">- <Input- disabled={state.status === "invoking"}- value={text}- onChange={(e) => setText(e.target.value)}- />- <div className="self-end">- <Button- disabled={state.status === "invoking"}- loading={state.status === "invoking"}- onClick={renderMedia}- >- Render video- </Button>- </div>+ <>+ <Button+ disabled={state.status === "invoking" || !code}+ loading={state.status === "invoking"}+ onClick={renderMedia}+ >+ Render video+ </Button>{state.status === "error" ? (<ErrorComp message={state.error.message} />) : null}- </div>+ </>) : null}{state.status === "rendering" || state.status === "done" ? (- <div className="flex flex-col gap-geist-quarter">+ <div className="flex flex-col gap-2"><ProgressBarprogress={state.status === "rendering" ? state.progress : 1}/>- <div className="self-end">- <DownloadButton undo={undo} state={state} />- </div>+ <DownloadButton undo={undo} state={state} /></div>) : null}</div>diff --git a/packages/template-prompt-to-motion-graphics/src/helpers/use-rendering.ts b/packages/template-prompt-to-motion-graphics/src/helpers/use-rendering.tsindex ff7c29efdb..ace2b96c2f 100644--- a/packages/template-prompt-to-motion-graphics/src/helpers/use-rendering.ts+++ b/packages/template-prompt-to-motion-graphics/src/helpers/use-rendering.ts@@ -36,7 +36,6 @@ const wait = async (milliSeconds: number) => {};export const useRendering = (- id: string,inputProps: z.infer<typeof CompositionProps>,) => {const [state, setState] = useState<State>({@@ -48,7 +47,7 @@ export const useRendering = (status: "invoking",});try {- const { renderId, bucketName } = await renderVideo({ id, inputProps });+ const { renderId, bucketName } = await renderVideo({ inputProps });setState({status: "rendering",progress: 0,@@ -100,7 +99,7 @@ export const useRendering = (renderId: null,});}- }, [id, inputProps]);+ }, [inputProps]);const undo = useCallback(() => {setState({ status: "init" });diff --git a/packages/template-prompt-to-motion-graphics/src/lambda/api.ts b/packages/template-prompt-to-motion-graphics/src/lambda/api.tsindex f1182d9577..ab9a12c87f 100644--- a/packages/template-prompt-to-motion-graphics/src/lambda/api.ts+++ b/packages/template-prompt-to-motion-graphics/src/lambda/api.ts@@ -28,14 +28,11 @@ const makeRequest = async <Res>(};export const renderVideo = async ({- id,inputProps,}: {- id: string;inputProps: z.infer<typeof CompositionProps>;}) => {const body: z.infer<typeof RenderRequest> = {- id,inputProps,};diff --git a/packages/template-prompt-to-motion-graphics/src/remotion/DynamicComp.tsx b/packages/template-prompt-to-motion-graphics/src/remotion/DynamicComp.tsxnew file mode 100644index 0000000000..fbc6539402--- /dev/null+++ b/packages/template-prompt-to-motion-graphics/src/remotion/DynamicComp.tsx@@ -0,0 +1,81 @@+import React, { useEffect, useState } from "react";+import {+ getInputProps,+ delayRender,+ continueRender,+ AbsoluteFill,+} from "remotion";+import { compileCode } from "./compiler";++interface DynamicCompProps {+ code: string;+ [key: string]: unknown;+}++export const DynamicComp: React.FC = () => {+ const { code } = getInputProps() as DynamicCompProps;++ const [handle] = useState(() => delayRender("Compiling code..."));+ const [Component, setComponent] = useState<React.ComponentType | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ try {+ const result = compileCode(code);++ if (result.error) {+ setError(result.error);+ } else {+ setComponent(() => result.Component);+ }+ } catch (e) {+ setError(e instanceof Error ? e.message : "Unknown error");+ } finally {+ continueRender(handle);+ }+ }, [code, handle]);++ if (error) {+ return (+ <AbsoluteFill+ style={{+ backgroundColor: "#1a1a2e",+ justifyContent: "center",+ alignItems: "center",+ padding: 60,+ }}+ >+ <div+ style={{+ color: "#ff6b6b",+ fontSize: 42,+ fontFamily: "system-ui, sans-serif",+ textAlign: "center",+ maxWidth: "80%",+ }}+ >+ Compilation Error+ </div>+ <div+ style={{+ color: "#fff",+ fontSize: 24,+ fontFamily: "monospace",+ marginTop: 24,+ textAlign: "center",+ maxWidth: "80%",+ wordBreak: "break-word",+ }}+ >+ {error}+ </div>+ </AbsoluteFill>+ );+ }++ if (!Component) {+ return null;+ }++ return <Component />;+};diff --git a/packages/template-prompt-to-motion-graphics/src/remotion/compiler.ts b/packages/template-prompt-to-motion-graphics/src/remotion/compiler.tsnew file mode 100644index 0000000000..6821f770f4--- /dev/null+++ b/packages/template-prompt-to-motion-graphics/src/remotion/compiler.ts@@ -0,0 +1,148 @@+import { useState, useEffect, useMemo, useRef } from "react";+import * as Babel from "@babel/standalone";+import React from "react";+import {+ AbsoluteFill,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+ spring,+ Sequence,+} from "remotion";+import * as RemotionShapes from "@remotion/shapes";++export interface CompilationResult {+ Component: React.ComponentType | null;+ error: string | null;+}++// Extract component body from full ES6 code with imports+function extractComponentBody(code: string): string {+ // Strip import lines+ const lines = code.split("\n");+ const nonImportLines = lines.filter(+ (line) => !line.trim().startsWith("import ")+ );+ const codeWithoutImports = nonImportLines.join("\n");++ // Extract body from "export const MyAnimation = () => { ... };"+ const match = codeWithoutImports.match(+ /export\s+const\s+\w+\s*=\s*\(\s*\)\s*=>\s*\{([\s\S]*)\};?\s*$/+ );+ if (match) {+ return match[1].trim();+ }++ // Fallback: return code as-is (backward compatible with body-only input)+ return code;+}++// Standalone compile function for use outside React components+export function compileCode(code: string): CompilationResult {+ if (!code?.trim()) {+ return { Component: null, error: "No code provided" };+ }++ try {+ const componentBody = extractComponentBody(code);+ const wrappedSource = `const DynamicAnimation = () => {\n${componentBody}\n};`;++ const transpiled = Babel.transform(wrappedSource, {+ presets: ["react", "typescript"],+ filename: "dynamic-animation.tsx",+ });++ if (!transpiled.code) {+ return { Component: null, error: "Transpilation failed" };+ }++ const Remotion = {+ AbsoluteFill,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+ spring,+ Sequence,+ };++ const wrappedCode = `${transpiled.code}\nreturn DynamicAnimation;`;++ const createComponent = new Function(+ "React",+ "Remotion",+ "RemotionShapes",+ "AbsoluteFill",+ "interpolate",+ "useCurrentFrame",+ "useVideoConfig",+ "spring",+ "Sequence",+ "useState",+ "useEffect",+ "useMemo",+ "useRef",+ "Rect",+ "Circle",+ "Triangle",+ "Star",+ "Polygon",+ "Ellipse",+ "Heart",+ "Pie",+ "makeRect",+ "makeCircle",+ "makeTriangle",+ "makeStar",+ "makePolygon",+ "makeEllipse",+ "makeHeart",+ "makePie",+ wrappedCode,+ );++ const Component = createComponent(+ React,+ Remotion,+ RemotionShapes,+ AbsoluteFill,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+ spring,+ Sequence,+ useState,+ useEffect,+ useMemo,+ useRef,+ RemotionShapes.Rect,+ RemotionShapes.Circle,+ RemotionShapes.Triangle,+ RemotionShapes.Star,+ RemotionShapes.Polygon,+ RemotionShapes.Ellipse,+ RemotionShapes.Heart,+ RemotionShapes.Pie,+ RemotionShapes.makeRect,+ RemotionShapes.makeCircle,+ RemotionShapes.makeTriangle,+ RemotionShapes.makeStar,+ RemotionShapes.makePolygon,+ RemotionShapes.makeEllipse,+ RemotionShapes.makeHeart,+ RemotionShapes.makePie,+ );++ if (typeof Component !== "function") {+ return {+ Component: null,+ error: "Code must be a function that returns a React component",+ };+ }++ return { Component, error: null };+ } catch (error) {+ const errorMessage =+ error instanceof Error ? error.message : "Unknown compilation error";+ return { Component: null, error: errorMessage };+ }+}diff --git a/packages/template-prompt-to-motion-graphics/src/remotion/index.tsx b/packages/template-prompt-to-motion-graphics/src/remotion/index.tsxnew file mode 100644index 0000000000..e960522298--- /dev/null+++ b/packages/template-prompt-to-motion-graphics/src/remotion/index.tsx@@ -0,0 +1,26 @@+import React from "react";+import { Composition, registerRoot } from "remotion";+import { DynamicComp } from "./DynamicComp";++const defaultCode = `import { AbsoluteFill } from "remotion";+export const MyAnimation = () => <AbsoluteFill style={{ backgroundColor: "#000" }} />;`;++const RemotionRoot: React.FC = () => {+ return (+ <>+ <Composition+ id="DynamicComp"+ component={DynamicComp}+ durationInFrames={180}+ fps={30}+ width={1920}+ height={1080}+ defaultProps={{+ code: defaultCode,+ }}+ />+ </>+ );+};++registerRoot(RemotionRoot);diff --git a/packages/template-prompt-to-motion-graphics/src/remotion/webpack-override.mjs b/packages/template-prompt-to-motion-graphics/src/remotion/webpack-override.mjsnew file mode 100644index 0000000000..54d517a983--- /dev/null+++ b/packages/template-prompt-to-motion-graphics/src/remotion/webpack-override.mjs@@ -0,0 +1,3 @@+export const webpackOverride = (config) => {+ return config;+};diff --git a/packages/template-prompt-to-motion-graphics/types/constants.ts b/packages/template-prompt-to-motion-graphics/types/constants.tsindex 38a2d46028..ec50a39996 100644--- a/packages/template-prompt-to-motion-graphics/types/constants.ts+++ b/packages/template-prompt-to-motion-graphics/types/constants.ts@@ -1,6 +1,7 @@import { z } from "zod";-export const COMP_NAME = "MyComp";++export const COMP_NAME = "DynamicComp";export const CompositionProps = z.object({- title: z.string(),+ code: z.string(),});diff --git a/packages/template-prompt-to-motion-graphics/types/schema.ts b/packages/template-prompt-to-motion-graphics/types/schema.tsindex da1562f334..d979128063 100644--- a/packages/template-prompt-to-motion-graphics/types/schema.ts+++ b/packages/template-prompt-to-motion-graphics/types/schema.ts@@ -2,7 +2,6 @@ import { z } from "zod";import { CompositionProps } from "./constants";export const RenderRequest = z.object({- id: z.string(),inputProps: CompositionProps,});