🎥 Make videos programmatically with React
wow really nice
Jonny Burgera296ac2f9666
diff --git a/packages/convert/app/components/timing-editor/CodeModal.tsx b/packages/convert/app/components/timing-editor/CodeModal.tsxnew file mode 100644index 0000000000..586f6133fc--- /dev/null+++ b/packages/convert/app/components/timing-editor/CodeModal.tsx@@ -0,0 +1,135 @@+import {Button} from '@remotion/design';+import React, {useEffect, useState} from 'react';+import {codeToHtml} from 'shikiji';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+} from '~/components/ui/dialog';+import {copyText} from './copy-text';+import {generateCode} from './generate-code';+import type {TimingComponent} from './types';++const CodeBlock: React.FC<{+ readonly code: string;+ readonly highlightedHtml: string;+}> = ({code, highlightedHtml}) => {+ return (+ <div className="overflow-auto rounded-md bg-[#24292e]">+ {highlightedHtml ? (+ <div+ // eslint-disable-next-line react/no-danger+ dangerouslySetInnerHTML={{__html: highlightedHtml}}+ className="p-4 text-sm [&_pre]:m-0 [&_pre]:bg-transparent"+ />+ ) : (+ <pre className="p-4 text-sm text-gray-300">+ <code>{code}</code>+ </pre>+ )}+ </div>+ );+};++export const CodeModal: React.FC<{+ readonly open: boolean;+ readonly onOpenChange: (open: boolean) => void;+ readonly components: TimingComponent[];+}> = ({open, onOpenChange, components}) => {+ const [highlightedImports, setHighlightedImports] = useState<string>('');+ const [highlightedCode, setHighlightedCode] = useState<string>('');+ const [copied, setCopied] = useState<'imports' | 'code' | null>(null);++ const generated = generateCode(components);++ useEffect(() => {+ if (!open) return;++ if (generated.imports) {+ codeToHtml(generated.imports, {+ lang: 'typescript',+ theme: 'github-dark',+ }).then((html) => {+ setHighlightedImports(html);+ });+ }++ codeToHtml(generated.code, {+ lang: 'typescript',+ theme: 'github-dark',+ }).then((html) => {+ setHighlightedCode(html);+ });+ }, [generated.imports, generated.code, open]);++ const handleCopy = async (type: 'imports' | 'code') => {+ const textToCopy = type === 'imports' ? generated.imports : generated.code;++ try {+ await copyText(textToCopy);+ setCopied(type);+ setTimeout(() => setCopied(null), 2000);+ } catch {+ // Fallback using clipboard API directly+ await navigator.clipboard.writeText(textToCopy);+ setCopied(type);+ setTimeout(() => setCopied(null), 2000);+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <div className="overflow-y-auto max-h-[500px]">+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogDescription>+ Copy this code into your Remotion project:+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ {generated.imports ? (+ <div>+ <div className="flex items-center justify-between mb-2">+ <span className="text-sm font-medium text-muted-foreground">+ Imports+ </span>+ <Button+ type="button"+ onClick={() => handleCopy('imports')}+ className="h-7 px-2 text-xs w-[60px]"+ >+ {copied === 'imports' ? 'Copied!' : 'Copy'}+ </Button>+ </div>+ <CodeBlock+ code={generated.imports}+ highlightedHtml={highlightedImports}+ />+ </div>+ ) : null}++ <div>+ <div className="flex items-center justify-between mb-2">+ <span className="text-sm font-medium text-muted-foreground">+ Code+ </span>+ <Button+ type="button"+ onClick={() => handleCopy('code')}+ className="h-7 px-2 text-xs"+ >+ {copied === 'code' ? 'Copied!' : 'Copy'}+ </Button>+ </div>+ <CodeBlock+ code={generated.code}+ highlightedHtml={highlightedCode}+ />+ </div>+ </div>+ </DialogContent>+ </div>+ </Dialog>+ );+};diff --git a/packages/convert/app/components/timing-editor/Sidebar.tsx b/packages/convert/app/components/timing-editor/Sidebar.tsxindex 89361cb70b..95a30d1916 100644--- a/packages/convert/app/components/timing-editor/Sidebar.tsx+++ b/packages/convert/app/components/timing-editor/Sidebar.tsx@@ -1,5 +1,6 @@import {Button} from '@remotion/design';-import React from 'react';+import React, {useState} from 'react';+import {CodeModal} from './CodeModal';import {ReplayIcon} from './ReplayIcon';import {TimingComponentEditor} from './TimingComponentEditor';import type {MixingMode, TimingComponent, TimingConfig} from './types';@@ -35,17 +36,30 @@ export const Sidebar: React.FC<{removeComponent,onMixingModeChange,}) => {+ const [codeModalOpen, setCodeModalOpen] = useState(false);+return (<div className="p-4 flex flex-col flex-1 w-full md:w-[400px] md:h-full md:flex-none overflow-y-auto"><div className="flex items-center justify-between mb-4"><div className="font-brand font-bold text-xl">Timing Editor</div>- <Button- type="button"- onClick={onReplay}- className="rounded-full w-10 h-10"- >- <ReplayIcon />- </Button>+ <div className="flex gap-2">+ <Button+ type="button"+ depth={0.7}+ onClick={() => setCodeModalOpen(true)}+ className="px-3 h-10 text-sm rounded-full"+ >+ Get Code+ </Button>+ <Button+ type="button"+ depth={0.7}+ onClick={onReplay}+ className="rounded-full w-10 h-10"+ >+ <ReplayIcon />+ </Button>+ </div></div>{components.map((component, index) => (<TimingComponentEditor@@ -77,6 +91,11 @@ export const Sidebar: React.FC<{+ Add component</Button></div>+ <CodeModal+ open={codeModalOpen}+ onOpenChange={setCodeModalOpen}+ components={components}+ /></div>);};diff --git a/packages/convert/app/components/timing-editor/TimingEditor.tsx b/packages/convert/app/components/timing-editor/TimingEditor.tsxindex afdc073bed..0da3c32439 100644--- a/packages/convert/app/components/timing-editor/TimingEditor.tsx+++ b/packages/convert/app/components/timing-editor/TimingEditor.tsx@@ -140,7 +140,7 @@ export function TimingEditor() {return (<div className="flex justify-center items-center h-full w-full absolute flex-col">- <div className="flex overflow-hidden w-full flex-1 flex-col md:flex-row p-2">+ <div className="flex overflow-hidden w-full flex-1 flex-col md:flex-row"><Sidebarcomponents={components}draggedState={draggedState}diff --git a/packages/convert/app/components/timing-editor/generate-code.ts b/packages/convert/app/components/timing-editor/generate-code.tsnew file mode 100644index 0000000000..39109a24b1--- /dev/null+++ b/packages/convert/app/components/timing-editor/generate-code.ts@@ -0,0 +1,227 @@+import type {EasingType, TimingComponent} from './types';++const getEasingCode = (easing: EasingType): string => {+ switch (easing) {+ case 'linear':+ return 'Easing.linear';+ case 'ease':+ return 'Easing.ease';+ case 'ease-in-quad':+ return 'Easing.in(Easing.quad)';+ case 'ease-out-quad':+ return 'Easing.out(Easing.quad)';+ case 'ease-in-out-quad':+ return 'Easing.inOut(Easing.quad)';+ case 'ease-in-cubic':+ return 'Easing.in(Easing.cubic)';+ case 'ease-out-cubic':+ return 'Easing.out(Easing.cubic)';+ case 'ease-in-out-cubic':+ return 'Easing.inOut(Easing.cubic)';+ case 'ease-in-sin':+ return 'Easing.in(Easing.sin)';+ case 'ease-out-sin':+ return 'Easing.out(Easing.sin)';+ case 'ease-in-out-sin':+ return 'Easing.inOut(Easing.sin)';+ case 'ease-in-exp':+ return 'Easing.in(Easing.exp)';+ case 'ease-out-exp':+ return 'Easing.out(Easing.exp)';+ case 'ease-in-out-exp':+ return 'Easing.inOut(Easing.exp)';+ case 'ease-in-circle':+ return 'Easing.in(Easing.circle)';+ case 'ease-out-circle':+ return 'Easing.out(Easing.circle)';+ case 'ease-in-out-circle':+ return 'Easing.inOut(Easing.circle)';+ case 'ease-in-bounce':+ return 'Easing.in(Easing.bounce)';+ case 'ease-out-bounce':+ return 'Easing.out(Easing.bounce)';+ case 'ease-in-out-bounce':+ return 'Easing.inOut(Easing.bounce)';+ default:+ return 'Easing.linear';+ }+};++const generateSpringCode = (+ component: TimingComponent,+ varName: string,+): string => {+ if (component.config.type !== 'spring') {+ throw new Error('Expected spring config');+ }++ const {springConfig, reverse, durationInFrames, delay} = component.config;+ const {damping, mass, stiffness, overshootClamping} = springConfig;++ const configLines: string[] = [];++ if (mass !== 1) {+ configLines.push(` mass: ${mass},`);+ }++ if (damping !== 10) {+ configLines.push(` damping: ${damping},`);+ }++ if (stiffness !== 100) {+ configLines.push(` stiffness: ${stiffness},`);+ }++ if (overshootClamping) {+ configLines.push(` overshootClamping: true,`);+ }++ const lines: string[] = [`const ${varName} = spring({`, ' frame,', ' fps,'];++ if (configLines.length > 0) {+ lines.push(' config: {');+ lines.push(...configLines);+ lines.push(' },');+ }++ if (durationInFrames !== null) {+ lines.push(` durationInFrames: ${durationInFrames},`);+ }++ if (delay > 0) {+ lines.push(` delay: ${delay},`);+ }++ if (reverse) {+ lines.push(' reverse: true,');+ }++ lines.push('});');++ return lines.join('\n');+};++const generateInterpolateCode = (+ component: TimingComponent,+ varName: string,+): string => {+ if (component.config.type !== 'interpolate') {+ throw new Error('Expected interpolate config');+ }++ const {easing, durationInFrames, delay} = component.config;+ const easingCode = getEasingCode(easing);++ const frameExpr = delay > 0 ? `frame - ${delay}` : 'frame';++ const lines: string[] = [+ `const ${varName} = interpolate(`,+ ` ${frameExpr},`,+ ` [0, ${durationInFrames}],`,+ ' [0, 1],',+ ' {',+ ` easing: ${easingCode},`,+ " extrapolateLeft: 'clamp',",+ " extrapolateRight: 'clamp',",+ ' }',+ ');',+ ];++ return lines.join('\n');+};++const generateSineCode = (+ component: TimingComponent,+ varName: string,+): string => {+ if (component.config.type !== 'sine') {+ throw new Error('Expected sine config');+ }++ const {durationInFrames, amplitude, frequency, frameOffset} = component.config;++ const frameExpr = frameOffset !== 0 ? `(frame + ${frameOffset})` : 'frame';+ const amplitudeStr = amplitude !== 1 ? `${amplitude} * ` : '';++ return `const ${varName} = ${amplitudeStr}Math.sin((2 * Math.PI * ${frequency} * ${frameExpr}) / ${durationInFrames});`;+};++export type GeneratedCode = {+ imports: string;+ code: string;+};++export const generateCode = (components: TimingComponent[]): GeneratedCode => {+ if (components.length === 0) {+ return {+ imports: '',+ code: '// No timing components configured',+ };+ }++ const hasSpring = components.some((c) => c.config.type === 'spring');+ const hasInterpolate = components.some((c) => c.config.type === 'interpolate');+ const needsEasing =+ hasInterpolate &&+ components.some(+ (c) => c.config.type === 'interpolate' && c.config.easing !== 'linear',+ );++ // Generate imports+ const importsList: string[] = [];+ if (hasSpring) {+ importsList.push('spring');+ }++ if (hasInterpolate) {+ importsList.push('interpolate');+ }++ if (needsEasing) {+ importsList.push('Easing');+ }++ const imports =+ importsList.length > 0+ ? `import {${importsList.join(', ')}} from 'remotion';`+ : '';++ // Generate variable declarations+ const varDeclarations: string[] = [];+ const varNames: string[] = [];++ components.forEach((component, index) => {+ const varName = `value${index + 1}`;+ varNames.push(varName);++ if (component.config.type === 'spring') {+ varDeclarations.push(generateSpringCode(component, varName));+ } else if (component.config.type === 'interpolate') {+ varDeclarations.push(generateInterpolateCode(component, varName));+ } else {+ varDeclarations.push(generateSineCode(component, varName));+ }+ });++ // Generate total line with mixing modes+ let totalExpr = varNames[0];+ for (let i = 1; i < components.length; i++) {+ const mixingMode = components[i].mixingMode;+ const operator = mixingMode === 'subtractive' ? '-' : '+';+ totalExpr += ` ${operator} ${varNames[i]}`;+ }++ const totalLine =+ components.length > 1 ? `\nconst total = ${totalExpr};` : '';++ // Combine code parts+ const codeParts: string[] = [...varDeclarations];+ if (totalLine) {+ codeParts.push(totalLine);+ }++ return {+ imports,+ code: codeParts.join('\n'),+ };+};diff --git a/packages/convert/app/components/ui/dialog.tsx b/packages/convert/app/components/ui/dialog.tsxindex 3d2b343d6b..51de6b5c2d 100644--- a/packages/convert/app/components/ui/dialog.tsx+++ b/packages/convert/app/components/ui/dialog.tsx@@ -1,112 +1,131 @@'use client';import * as DialogPrimitive from '@radix-ui/react-dialog';-import {X} from 'lucide-react';+import {XIcon} from 'lucide-react';import * as React from 'react';import {cn} from '@/lib/utils';-const Dialog = DialogPrimitive.Root;+function Dialog({...props}: React.ComponentProps<typeof DialogPrimitive.Root>) {+ return <DialogPrimitive.Root data-slot="dialog" {...props} />;+}-const DialogTrigger = DialogPrimitive.Trigger;--const DialogPortal = DialogPrimitive.Portal;+function DialogTrigger({+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {+ return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;+}-const DialogClose = DialogPrimitive.Close;+function DialogPortal({+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Portal>) {+ return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;+}-const DialogOverlay = React.forwardRef<- React.ElementRef<typeof DialogPrimitive.Overlay>,- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>->(({className, ...props}, ref) => (- <DialogPrimitive.Overlay- ref={ref}- className={cn(- 'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',- className,- )}- {...props}- />-));-DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;+function DialogClose({+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Close>) {+ return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;+}-const DialogContent = React.forwardRef<- React.ElementRef<typeof DialogPrimitive.Content>,- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>->(({className, children, ...props}, ref) => (- <DialogPortal>- <DialogOverlay />- <DialogPrimitive.Content- ref={ref}+function DialogOverlay({+ className,+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {+ return (+ <DialogPrimitive.Overlay+ data-slot="dialog-overlay"className={cn(- 'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',+ 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50',className,)}{...props}- >- {children}- <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">- <X className="h-4 w-4" />- <span className="sr-only">Close</span>- </DialogPrimitive.Close>- </DialogPrimitive.Content>- </DialogPortal>-));-DialogContent.displayName = DialogPrimitive.Content.displayName;+ />+ );+}-const DialogHeader = ({+function DialogContent({className,+ children,+ showCloseButton = true,...props-}: React.HTMLAttributes<HTMLDivElement>) => (- <div- className={cn(- 'flex flex-col space-y-1.5 text-center sm:text-left',- className,- )}- {...props}- />-);-DialogHeader.displayName = 'DialogHeader';+}: React.ComponentProps<typeof DialogPrimitive.Content> & {+ readonly showCloseButton?: boolean;+}) {+ return (+ <DialogPortal data-slot="dialog-portal">+ <DialogOverlay />+ <DialogPrimitive.Content+ data-slot="dialog-content"+ className={cn(+ 'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg',+ className,+ )}+ {...props}+ >+ {children}+ {showCloseButton && (+ <DialogPrimitive.Close+ data-slot="dialog-close"+ className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"+ >+ <XIcon />+ <span className="sr-only">Close</span>+ </DialogPrimitive.Close>+ )}+ </DialogPrimitive.Content>+ </DialogPortal>+ );+}++function DialogHeader({className, ...props}: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="dialog-header"+ className={cn('flex flex-col gap-2 text-center sm:text-left', className)}+ {...props}+ />+ );+}++function DialogFooter({className, ...props}: React.ComponentProps<'div'>) {+ return (+ <div+ data-slot="dialog-footer"+ className={cn(+ 'flex flex-col-reverse gap-2 sm:flex-row sm:justify-end',+ className,+ )}+ {...props}+ />+ );+}-const DialogFooter = ({+function DialogTitle({className,...props-}: React.HTMLAttributes<HTMLDivElement>) => (- <div- className={cn(- 'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',- className,- )}- {...props}- />-);-DialogFooter.displayName = 'DialogFooter';--const DialogTitle = React.forwardRef<- React.ElementRef<typeof DialogPrimitive.Title>,- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>->(({className, ...props}, ref) => (- <DialogPrimitive.Title- ref={ref}- className={cn(- 'text-lg font-semibold leading-none tracking-tight',- className,- )}- {...props}- />-));-DialogTitle.displayName = DialogPrimitive.Title.displayName;+}: React.ComponentProps<typeof DialogPrimitive.Title>) {+ return (+ <DialogPrimitive.Title+ data-slot="dialog-title"+ className={cn('text-lg leading-none font-semibold', className)}+ {...props}+ />+ );+}-const DialogDescription = React.forwardRef<- React.ElementRef<typeof DialogPrimitive.Description>,- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>->(({className, ...props}, ref) => (- <DialogPrimitive.Description- ref={ref}- className={cn('text-sm text-muted-foreground', className)}- {...props}- />-));-DialogDescription.displayName = DialogPrimitive.Description.displayName;+function DialogDescription({+ className,+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Description>) {+ return (+ <DialogPrimitive.Description+ data-slot="dialog-description"+ className={cn('text-muted-foreground text-sm', className)}+ {...props}+ />+ );+}export {Dialog,