🎥 Make videos programmatically with React
Add StreamingOverlay, add copy button, show protected imports, show toast when trying to edit it
ASchwad30c111442af8
diff --git a/bun.lock b/bun.lockindex e95ad519a2..11fb55b79e 100644--- a/bun.lock+++ b/bun.lock@@ -1429,6 +1429,7 @@"clsx": "^2.1.1","lucide-react": "^0.555.0","monaco-editor": "^0.55.1",+ "monaco-jsx-syntax-highlight": "^1.2.2","next": "16.0.0","react": "19.0.0","react-dom": "19.0.0",@@ -5754,6 +5755,8 @@"monaco-editor": ["[email protected]", "", { "dependencies": { "dompurify": "3.2.7", "marked": "14.0.0" } }, "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A=="],+ "monaco-jsx-syntax-highlight": ["[email protected]", "", {}, "sha512-V1JkspFJKIaRX5C2D3UuWjIz2xgWI+7slf+gMFgz8yIr0LSTl3AhD8Gk/7gvbMqp6pKOynIhWJEaluwwUtLz7w=="],+"morgan": ["[email protected]", "", { "dependencies": { "basic-auth": "2.0.1", "debug": "2.6.9", "depd": "2.0.0", "on-finished": "2.3.0", "on-headers": "1.0.2" } }, "sha512-AbegBVI4sh6El+1gNwvD5YIck7nSA36weD7xvIxG4in80j/UoK8AEGaWnnz8v1GxonMCltmlNs5ZKbGvl9b1XQ=="],"mri": ["[email protected]", "", {}, "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA=="],diff --git a/packages/template-code-generation/package.json b/packages/template-code-generation/package.jsonindex 3ce940ae42..faa571b896 100644--- a/packages/template-code-generation/package.json+++ b/packages/template-code-generation/package.json@@ -29,6 +29,7 @@"clsx": "^2.1.1","lucide-react": "^0.555.0","monaco-editor": "^0.55.1",+ "monaco-jsx-syntax-highlight": "^1.2.2","next": "16.0.0","react": "19.0.0","react-dom": "19.0.0",diff --git a/packages/template-code-generation/src/components/CodeEditor.tsx b/packages/template-code-generation/src/components/CodeEditor.tsxdeleted file mode 100644index 30a58bd60f..0000000000--- a/packages/template-code-generation/src/components/CodeEditor.tsx+++ /dev/null@@ -1,127 +0,0 @@-"use client";--import React, { useRef, useEffect } from "react";-import dynamic from "next/dynamic";-import type { Monaco } from "@monaco-editor/react";-import type { editor } from "monaco-editor";--// Monaco must be loaded client-side only-const MonacoEditor = dynamic(() => import("@monaco-editor/react"), {- ssr: false,- loading: () => (- <div className="w-[600px] h-full flex justify-center items-center bg-[#1e1e1e]">- <span className="text-[#888] font-sans">Loading editor...</span>- </div>- ),-});--interface CodeEditorProps {- code: string;- onChange: (value: string) => void;- isStreaming?: boolean;-}--const headerText = `// Available Remotion imports:-// Remotion.AbsoluteFill, Remotion.interpolate,-// Remotion.useCurrentFrame, Remotion.useVideoConfig,-// Remotion.spring, Remotion.Sequence`;--export const CodeEditor: React.FC<CodeEditorProps> = ({- code,- onChange,- isStreaming = false,-}) => {- const monacoRef = useRef<Monaco | null>(null);- const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);- const isStreamingRef = useRef(isStreaming);-- // Keep ref in sync with prop and clear markers during streaming- useEffect(() => {- isStreamingRef.current = isStreaming;- }, [isStreaming]);-- // Switch language based on streaming state- useEffect(() => {- const model = editorRef.current?.getModel();- if (model && monacoRef.current) {- const language = isStreaming ? "plaintext" : "javascript";- monacoRef.current.editor.setModelLanguage(model, language);- }- }, [isStreaming]);-- // Continuously clear markers while streaming- useEffect(() => {- if (!isStreaming || !monacoRef.current) return;-- const clearAllMarkers = () => {- monacoRef.current?.editor.getModels().forEach((model) => {- // Clear markers from all known owners- monacoRef.current?.editor.setModelMarkers(model, "javascript", []);- monacoRef.current?.editor.setModelMarkers(model, "typescript", []);- monacoRef.current?.editor.setModelMarkers(model, "owner", []);- });- };-- // Clear immediately and on interval while streaming- clearAllMarkers();- const interval = setInterval(clearAllMarkers, 100);-- return () => clearInterval(interval);- }, [isStreaming, code]);-- const handleEditorMount = (- editorInstance: editor.IStandaloneCodeEditor,- monaco: Monaco,- ) => {- monacoRef.current = monaco;- editorRef.current = editorInstance;-- // Override marker setting to suppress during streaming- const originalSetModelMarkers = monaco.editor.setModelMarkers;- monaco.editor.setModelMarkers = (model, owner, markers) => {- // Check the ref (not the prop) to get current value- if (isStreamingRef.current) {- return;- }- originalSetModelMarkers.call(monaco.editor, model, owner, markers);- };- };-- return (- <div className="w-[600px] h-full flex flex-col bg-[#1e1e1e] border-l border-[#2a2a2a]">- <div className="p-3 px-4 bg-[#252526] border-b border-[#2a2a2a] font-mono text-xs text-[#6a9955] leading-relaxed whitespace-pre">- {headerText}- </div>- <div className="flex-1 overflow-hidden relative">- {isStreaming && (- <div className="absolute inset-0 bg-black/40 z-10 flex items-center justify-center pointer-events-none">- <div className="flex items-center gap-3 bg-[#1e1e1e] px-4 py-3 rounded-lg border border-[#333]">- <div className="w-4 h-4 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />- <span className="text-white text-sm font-sans">- Generating code...- </span>- </div>- </div>- )}- <MonacoEditor- height="100%"- defaultLanguage="javascript"- theme="vs-dark"- value={code}- onChange={(value) => onChange(value || "")}- onMount={handleEditorMount}- options={{- minimap: { enabled: false },- fontSize: 14,- lineNumbers: "on",- scrollBeyondLastLine: false,- automaticLayout: true,- tabSize: 2,- wordWrap: "on",- padding: { top: 16 },- }}- />- </div>- </div>- );-};diff --git a/packages/template-code-generation/src/components/CodeEditor/CodeEditor.tsx b/packages/template-code-generation/src/components/CodeEditor/CodeEditor.tsxnew file mode 100644index 0000000000..6af23722df--- /dev/null+++ b/packages/template-code-generation/src/components/CodeEditor/CodeEditor.tsx@@ -0,0 +1,309 @@+"use client";++import React, { useRef, useEffect } from "react";+import dynamic from "next/dynamic";+import type { Monaco } from "@monaco-editor/react";+import type { editor } from "monaco-editor";+import {+ MonacoJsxSyntaxHighlight,+ getWorker,+} from "monaco-jsx-syntax-highlight";++import { EditorHeader } from "./EditorHeader";+import { StreamingOverlay } from "./StreamingOverlay";+import { ReadOnlyToast } from "./ReadOnlyToast";+import { EDITOR_STYLES } from "./styles";++// Monaco must be loaded client-side only+const MonacoEditor = dynamic(() => import("@monaco-editor/react"), {+ ssr: false,+ loading: () => (+ <div className="w-[600px] h-full flex justify-center items-center bg-[#1e1e1e]">+ <span className="text-[#888] font-sans">Loading editor...</span>+ </div>+ ),+});++interface CodeEditorProps {+ code: string;+ onChange: (value: string) => void;+ isStreaming?: boolean;+}++const WRAPPER_PREFIX = `import * as Remotion from 'remotion';++export const MyAnimation = () => {+`;++const WRAPPER_SUFFIX = `+};`;++// Calculate line counts for wrapper boundaries+const PREFIX_LINE_COUNT = WRAPPER_PREFIX.split("\n").length - 1;+const SUFFIX_LINE_COUNT = WRAPPER_SUFFIX.split("\n").length - 1;++export const CodeEditor: React.FC<CodeEditorProps> = ({+ code,+ onChange,+ isStreaming = false,+}) => {+ const monacoRef = useRef<Monaco | null>(null);+ const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);+ const isStreamingRef = useRef(isStreaming);+ const decorationsRef = useRef<string[]>([]);+ const [showReadOnlyToast, setShowReadOnlyToast] = React.useState(false);+ const toastTimeoutRef = useRef<NodeJS.Timeout | null>(null);++ // Keep ref in sync with prop and clear markers during streaming+ useEffect(() => {+ isStreamingRef.current = isStreaming;+ }, [isStreaming]);++ // Switch language based on streaming state+ useEffect(() => {+ const model = editorRef.current?.getModel();+ if (model && monacoRef.current) {+ const language = isStreaming ? "plaintext" : "javascript";+ monacoRef.current.editor.setModelLanguage(model, language);+ }+ }, [isStreaming]);++ // Continuously clear markers while streaming+ useEffect(() => {+ if (!isStreaming || !monacoRef.current) return;++ const clearAllMarkers = () => {+ monacoRef.current?.editor.getModels().forEach((model) => {+ monacoRef.current?.editor.setModelMarkers(model, "javascript", []);+ monacoRef.current?.editor.setModelMarkers(model, "typescript", []);+ monacoRef.current?.editor.setModelMarkers(model, "owner", []);+ });+ };++ clearAllMarkers();+ const interval = setInterval(clearAllMarkers, 100);++ return () => clearInterval(interval);+ }, [isStreaming, code]);++ // Apply read-only decorations to prefix and suffix lines+ const applyReadOnlyDecorations = (totalLines: number) => {+ if (!editorRef.current || !monacoRef.current) return;++ const decorations: editor.IModelDeltaDecoration[] = [];++ // Prefix lines (lines 1 to PREFIX_LINE_COUNT)+ for (let i = 1; i <= PREFIX_LINE_COUNT; i++) {+ decorations.push({+ range: new monacoRef.current.Range(i, 1, i, 1),+ options: {+ isWholeLine: true,+ className: "readonly-line",+ glyphMarginClassName: "readonly-glyph",+ },+ });+ }++ // Suffix lines (last SUFFIX_LINE_COUNT lines)+ const suffixStart = totalLines - SUFFIX_LINE_COUNT + 1;+ for (let i = suffixStart; i <= totalLines; i++) {+ decorations.push({+ range: new monacoRef.current.Range(i, 1, i, 1),+ options: {+ isWholeLine: true,+ className: "readonly-line",+ glyphMarginClassName: "readonly-glyph",+ },+ });+ }++ decorationsRef.current = editorRef.current.deltaDecorations(+ decorationsRef.current,+ decorations,+ );+ };++ const handleEditorMount = (+ editorInstance: editor.IStandaloneCodeEditor,+ monaco: Monaco,+ ) => {+ monacoRef.current = monaco;+ editorRef.current = editorInstance;++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const ts = (monaco.languages as any).typescript;++ // Apply initial decorations+ const totalLines = (WRAPPER_PREFIX + code + WRAPPER_SUFFIX).split(+ "\n",+ ).length;+ applyReadOnlyDecorations(totalLines);++ // Configure TypeScript compiler options+ ts?.typescriptDefaults?.setCompilerOptions({+ target: ts.ScriptTarget?.ESNext,+ module: ts.ModuleKind?.ESNext,+ jsx: ts.JsxEmit?.React,+ jsxFactory: "React.createElement",+ allowNonTsExtensions: true,+ strict: false,+ noEmit: true,+ esModuleInterop: true,+ });++ // Add React types so TS understands JSX+ ts?.typescriptDefaults?.addExtraLib(+ `+ declare namespace React {+ type ReactNode = string | number | boolean | null | undefined | React.ReactElement | React.ReactNode[];+ interface ReactElement<P = any> { type: any; props: P; key: string | null; }+ type FC<P = {}> = (props: P) => ReactElement | null;+ type CSSProperties = Record<string, string | number>;+ interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {+ className?: string;+ style?: CSSProperties;+ [key: string]: any;+ }+ interface AriaAttributes { [key: string]: any; }+ interface DOMAttributes<T> { children?: ReactNode; [key: string]: any; }+ function createElement(type: any, props?: any, ...children: any[]): ReactElement;+ }+ declare const React: typeof React;+ `,+ "react.d.ts",+ );++ // Add type declaration for remotion module+ ts?.typescriptDefaults?.addExtraLib(+ `declare module 'remotion' {+ export const AbsoluteFill: React.FC<React.HTMLAttributes<HTMLDivElement>>;+ export function useCurrentFrame(): number;+ export function useVideoConfig(): { fps: number; durationInFrames: number; width: number; height: number };+ export function interpolate(input: number, inputRange: number[], outputRange: number[], options?: any): number;+ export function spring(options: { frame: number; fps: number; config?: any }): number;+ export const Sequence: React.FC<{ from?: number; durationInFrames?: number; children: React.ReactNode }>;+ }`,+ "remotion.d.ts",+ );++ // Block editing in protected lines by intercepting model changes+ const model = editorInstance.getModel();+ if (model) {+ let lastValidContent = model.getValue();++ model.onDidChangeContent(() => {+ const currentContent = model.getValue();+ const hasValidPrefix = currentContent.startsWith(WRAPPER_PREFIX);+ const hasValidSuffix = currentContent.endsWith(WRAPPER_SUFFIX);++ if (!hasValidPrefix || !hasValidSuffix) {+ model.setValue(lastValidContent);++ if (toastTimeoutRef.current) {+ clearTimeout(toastTimeoutRef.current);+ }+ setShowReadOnlyToast(true);+ toastTimeoutRef.current = setTimeout(() => {+ setShowReadOnlyToast(false);+ }, 2000);+ } else {+ lastValidContent = currentContent;+ }+ });+ }++ // Override marker setting to suppress during streaming+ const originalSetModelMarkers = monaco.editor.setModelMarkers;+ monaco.editor.setModelMarkers = (mdl, owner, markers) => {+ if (isStreamingRef.current) {+ return;+ }+ originalSetModelMarkers.call(monaco.editor, mdl, owner, markers);+ };++ // Set up JSX syntax highlighting+ const monacoJsxSyntaxHighlight = new MonacoJsxSyntaxHighlight(+ getWorker(),+ monaco,+ );+ const { highlighter } = monacoJsxSyntaxHighlight.highlighterBuilder({+ editor: editorInstance,+ });+ highlighter();+ editorInstance.onDidChangeModelContent(() => {+ highlighter();+ });+ };++ // Wrap the body code with prefix/suffix for display+ const displayCode = WRAPPER_PREFIX + code + WRAPPER_SUFFIX;++ // Extract body from full code when user edits, restore wrapper if modified+ const handleChange = (value: string | undefined) => {+ if (!value) {+ onChange("");+ return;+ }++ const hasValidPrefix = value.startsWith(WRAPPER_PREFIX);+ const hasValidSuffix = value.endsWith(WRAPPER_SUFFIX);++ // If wrapper was modified, restore it+ if (!hasValidPrefix || !hasValidSuffix) {+ let body = value;+ if (hasValidPrefix) {+ body = body.slice(WRAPPER_PREFIX.length);+ }+ if (hasValidSuffix) {+ body = body.slice(0, -WRAPPER_SUFFIX.length);+ }++ const restoredCode = WRAPPER_PREFIX + body + WRAPPER_SUFFIX;+ editorRef.current?.setValue(restoredCode);++ const totalLines = restoredCode.split("\n").length;+ applyReadOnlyDecorations(totalLines);++ onChange(body);+ return;+ }++ // Normal case: wrapper intact, extract body+ const body = value.slice(WRAPPER_PREFIX.length, -WRAPPER_SUFFIX.length);++ const totalLines = value.split("\n").length;+ applyReadOnlyDecorations(totalLines);++ onChange(body);+ };++ return (+ <div className="w-[600px] h-full flex flex-col bg-[#1e1e1e] border-l border-[#2a2a2a]">+ <EditorHeader filename="MyAnimation.tsx" code={displayCode} />+ <style>{EDITOR_STYLES}</style>+ <div className="flex-1 overflow-hidden relative">+ <StreamingOverlay visible={isStreaming} />+ <ReadOnlyToast visible={showReadOnlyToast} />+ <MonacoEditor+ height="100%"+ defaultLanguage="javascript"+ theme="vs-dark"+ value={displayCode}+ onChange={handleChange}+ onMount={handleEditorMount}+ options={{+ minimap: { enabled: false },+ fontSize: 14,+ lineNumbers: "on",+ scrollBeyondLastLine: false,+ automaticLayout: true,+ tabSize: 2,+ wordWrap: "on",+ padding: { top: 16 },+ glyphMargin: true,+ }}+ />+ </div>+ </div>+ );+};diff --git a/packages/template-code-generation/src/components/CodeEditor/CopyButton.tsx b/packages/template-code-generation/src/components/CodeEditor/CopyButton.tsxnew file mode 100644index 0000000000..a21e502696--- /dev/null+++ b/packages/template-code-generation/src/components/CodeEditor/CopyButton.tsx@@ -0,0 +1,41 @@+"use client";++import React, { useState } from "react";+import { Copy, Check } from "lucide-react";++interface CopyButtonProps {+ text: string;+ className?: string;+}++export const CopyButton: React.FC<CopyButtonProps> = ({ text, className }) => {+ const [copied, setCopied] = useState(false);++ const handleCopy = async () => {+ await navigator.clipboard.writeText(text);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ };++ return (+ <button+ onClick={handleCopy}+ className={+ className ??+ "flex items-center gap-1.5 px-2 py-1 text-xs text-[#888] hover:text-white hover:bg-[#3a3a3a] rounded transition-colors"+ }+ >+ {copied ? (+ <>+ <Check className="w-3.5 h-3.5 text-green-400" />+ <span className="text-green-400">Copied!</span>+ </>+ ) : (+ <>+ <Copy className="w-3.5 h-3.5" />+ <span>Copy</span>+ </>+ )}+ </button>+ );+};diff --git a/packages/template-code-generation/src/components/CodeEditor/EditorHeader.tsx b/packages/template-code-generation/src/components/CodeEditor/EditorHeader.tsxnew file mode 100644index 0000000000..0c6b787d2a--- /dev/null+++ b/packages/template-code-generation/src/components/CodeEditor/EditorHeader.tsx@@ -0,0 +1,21 @@+"use client";++import React from "react";+import { CopyButton } from "./CopyButton";++interface EditorHeaderProps {+ filename: string;+ code: string;+}++export const EditorHeader: React.FC<EditorHeaderProps> = ({+ filename,+ code,+}) => {+ return (+ <div className="flex items-center justify-between px-4 py-2 bg-[#252526] border-b border-[#2a2a2a]">+ <span className="text-xs text-[#888] font-mono">{filename}</span>+ <CopyButton text={code} />+ </div>+ );+};diff --git a/packages/template-code-generation/src/components/CodeEditor/ReadOnlyToast.tsx b/packages/template-code-generation/src/components/CodeEditor/ReadOnlyToast.tsxnew file mode 100644index 0000000000..740bffbbb3--- /dev/null+++ b/packages/template-code-generation/src/components/CodeEditor/ReadOnlyToast.tsx@@ -0,0 +1,21 @@+"use client";++import React from "react";+import { Lock } from "lucide-react";++interface ReadOnlyToastProps {+ visible: boolean;+}++export const ReadOnlyToast: React.FC<ReadOnlyToastProps> = ({ visible }) => {+ if (!visible) return null;++ return (+ <div className="absolute top-4 left-1/2 -translate-x-1/2 z-20 animate-fade-in">+ <div className="flex items-center gap-2 bg-amber-900/90 text-amber-100 px-4 py-2 rounded-lg border border-amber-700 shadow-lg">+ <Lock className="w-4 h-4" />+ <span className="text-sm font-sans">These lines are read-only</span>+ </div>+ </div>+ );+};diff --git a/packages/template-code-generation/src/components/CodeEditor/StreamingOverlay.tsx b/packages/template-code-generation/src/components/CodeEditor/StreamingOverlay.tsxnew file mode 100644index 0000000000..749408495a--- /dev/null+++ b/packages/template-code-generation/src/components/CodeEditor/StreamingOverlay.tsx@@ -0,0 +1,24 @@+"use client";++import React from "react";++interface StreamingOverlayProps {+ visible: boolean;+ message?: string;+}++export const StreamingOverlay: React.FC<StreamingOverlayProps> = ({+ visible,+ message = "Generating code...",+}) => {+ if (!visible) return null;++ return (+ <div className="absolute inset-0 bg-black/40 z-10 flex items-center justify-center pointer-events-none">+ <div className="flex items-center gap-3 bg-[#1e1e1e] px-4 py-3 rounded-lg border border-[#333]">+ <div className="w-4 h-4 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />+ <span className="text-white text-sm font-sans">{message}</span>+ </div>+ </div>+ );+};diff --git a/packages/template-code-generation/src/components/CodeEditor/index.ts b/packages/template-code-generation/src/components/CodeEditor/index.tsnew file mode 100644index 0000000000..a2fc417c8b--- /dev/null+++ b/packages/template-code-generation/src/components/CodeEditor/index.ts@@ -0,0 +1 @@+export { CodeEditor } from "./CodeEditor";diff --git a/packages/template-code-generation/src/components/CodeEditor/styles.ts b/packages/template-code-generation/src/components/CodeEditor/styles.tsnew file mode 100644index 0000000000..4405b9ec9e--- /dev/null+++ b/packages/template-code-generation/src/components/CodeEditor/styles.ts@@ -0,0 +1,27 @@+export const EDITOR_STYLES = `+ .readonly-line {+ background-color: rgba(80, 80, 80, 0.2) !important;+ }+ .readonly-glyph {+ background-color: rgba(255, 255, 255, 0.15);+ border-radius: 2px;+ margin-left: 5px;+ }+ /* JSX syntax highlighting classes */+ .jsx-tag-angle-bracket { color: #808080; }+ .jsx-tag-name { color: #4ec9b0; }+ .jsx-tag-attribute-key { color: #9cdcfe; }+ .jsx-expression-braces { color: #ffd700; }+ .jsx-text { color: #ce9178; }+ .jsx-tag-order-1 { }+ .jsx-tag-order-2 { }+ .jsx-tag-order-3 { }+ /* Toast animation */+ @keyframes fade-in {+ from { opacity: 0; transform: translateY(-10px); }+ to { opacity: 1; transform: translateY(0); }+ }+ .animate-fade-in {+ animation: fade-in 0.2s ease-out;+ }+`;