🎥 Make videos programmatically with React
nice
Jonny Burger6a03cc39150d
diff --git a/packages/example/e2e/constants.mts b/packages/example/e2e/constants.mtsnew file mode 100644index 0000000000..cc9d51d3a5--- /dev/null+++ b/packages/example/e2e/constants.mts@@ -0,0 +1,33 @@+import os from 'os';+import path from 'path';++export const STUDIO_PORT = 3123;+export const STUDIO_URL = `http://localhost:${STUDIO_PORT}`;++export const exampleDir = path.resolve(+ // @ts-expect-error+ new URL('.', import.meta.url).pathname,+ '..',+);++export const rootFile = path.join(exampleDir, 'src', 'Root.tsx');+export const remotionBin = path.join(+ exampleDir,+ 'node_modules',+ '.bin',+ 'remotion',+);++export const LOGS_FILE = path.join(+ os.tmpdir(),+ 'remotion-e2e-studio-logs.ndjson',+);+export const ORIGINAL_CONTENT_FILE = path.join(+ os.tmpdir(),+ 'remotion-e2e-original-root.tsx',+);+export const PID_FILE = path.join(os.tmpdir(), 'remotion-e2e-studio.pid');+export const EXPANDED_SIDEBAR_STATE = path.join(+ os.tmpdir(),+ 'remotion-e2e-expanded-sidebar.json',+);diff --git a/packages/example/e2e/global-setup.mts b/packages/example/e2e/global-setup.mtsnew file mode 100644index 0000000000..7dd1738193--- /dev/null+++ b/packages/example/e2e/global-setup.mts@@ -0,0 +1,88 @@+import {spawn} from 'child_process';+import fs from 'fs';+import {+ EXPANDED_SIDEBAR_STATE,+ LOGS_FILE,+ ORIGINAL_CONTENT_FILE,+ PID_FILE,+ STUDIO_PORT,+ STUDIO_URL,+ exampleDir,+ remotionBin,+ rootFile,+} from './constants.mts';++async function waitForServer(+ url: string,+ timeoutMs: number = 30_000,+): Promise<void> {+ const start = Date.now();+ while (Date.now() - start < timeoutMs) {+ try {+ const res = await fetch(url);+ if (res.ok) {+ return;+ }+ } catch {+ // Server not ready yet+ }++ await new Promise((resolve) => setTimeout(resolve, 500));+ }++ throw new Error(`Server at ${url} did not start within ${timeoutMs}ms`);+}++export default async function globalSetup(): Promise<void> {+ fs.writeFileSync(ORIGINAL_CONTENT_FILE, fs.readFileSync(rootFile, 'utf-8'));+ fs.writeFileSync(LOGS_FILE, '');+ fs.writeFileSync(+ EXPANDED_SIDEBAR_STATE,+ JSON.stringify({+ cookies: [],+ origins: [+ {+ origin: STUDIO_URL,+ localStorage: [+ {+ name: 'remotion.sidebarRightCollapsing',+ value: 'expanded',+ },+ ],+ },+ ],+ }),+ );++ const studioProcess = spawn(+ remotionBin,+ ['studio', '--port', String(STUDIO_PORT), '--props', 'src/my-props.json'],+ {+ cwd: exampleDir,+ stdio: 'pipe',+ env: {+ ...process.env,+ BROWSER: 'none',+ },+ },+ );++ if (studioProcess.pid !== undefined) {+ fs.writeFileSync(PID_FILE, String(studioProcess.pid));+ }++ studioProcess.stderr?.on('data', (data: Buffer) => {+ const msg = data.toString();+ if (!msg.includes('ExperimentalWarning')) {+ process.stderr.write(`[studio stderr] ${msg.trim()}\n`);+ }+ });++ studioProcess.stdout?.on('data', (data: Buffer) => {+ const msg = data.toString();+ fs.appendFileSync(LOGS_FILE, JSON.stringify(msg) + '\n');+ process.stdout.write(`[studio stdout] ${msg.trim()}\n`);+ });++ await waitForServer(STUDIO_URL);+}diff --git a/packages/example/e2e/global-teardown.mts b/packages/example/e2e/global-teardown.mtsnew file mode 100644index 0000000000..87f8e60de7--- /dev/null+++ b/packages/example/e2e/global-teardown.mts@@ -0,0 +1,23 @@+import fs from 'fs';+import {ORIGINAL_CONTENT_FILE, PID_FILE, rootFile} from './constants.mts';++export default async function globalTeardown(): Promise<void> {+ if (fs.existsSync(PID_FILE)) {+ const pid = parseInt(fs.readFileSync(PID_FILE, 'utf-8'), 10);+ try {+ process.kill(pid, 'SIGTERM');+ } catch {+ // Process might already be dead+ }++ fs.unlinkSync(PID_FILE);+ }++ if (fs.existsSync(ORIGINAL_CONTENT_FILE)) {+ fs.writeFileSync(+ rootFile,+ fs.readFileSync(ORIGINAL_CONTENT_FILE, 'utf-8'),+ );+ fs.unlinkSync(ORIGINAL_CONTENT_FILE);+ }+}diff --git a/packages/example/e2e/helpers.mts b/packages/example/e2e/helpers.mtsnew file mode 100644index 0000000000..479479c6e6--- /dev/null+++ b/packages/example/e2e/helpers.mts@@ -0,0 +1,29 @@+import {expect} from '@playwright/test';+import type {Page} from '@playwright/test';+import fs from 'fs';+import {LOGS_FILE, STUDIO_URL} from './constants.mts';++export async function navigateToSchemaTest(page: Page): Promise<void> {+ await page.goto(STUDIO_URL);+ const schemaFolder = page.getByTitle('Schema');+ await schemaFolder.click({timeout: 15_000});+ const schemaTestLink = page.getByText('schema-test', {exact: true}).first();+ await schemaTestLink.click({timeout: 10_000});+ await expect(page).toHaveURL(/schema-test/, {timeout: 10_000});+}++export const stripAnsi = (s: string) =>+ // eslint-disable-next-line no-control-regex+ s.replace(/\x1b\[[0-9;]*m/g, '').replace(/\]8;;[^\x1b]*\x1b\\/g, '');++export const readStudioLogs = (): string[] => {+ if (!fs.existsSync(LOGS_FILE)) {+ return [];+ }++ return fs+ .readFileSync(LOGS_FILE, 'utf-8')+ .split('\n')+ .filter((l) => l.trim())+ .map((l) => JSON.parse(l) as string);+};diff --git a/packages/example/e2e/json-editor.test.mts b/packages/example/e2e/json-editor.test.mtsnew file mode 100644index 0000000000..d9979c33e6--- /dev/null+++ b/packages/example/e2e/json-editor.test.mts@@ -0,0 +1,90 @@+import {expect, test} from '@playwright/test';+import fs from 'fs';+import {EXPANDED_SIDEBAR_STATE, rootFile} from './constants.mts';+import {navigateToSchemaTest} from './helpers.mts';++test.use({storageState: EXPANDED_SIDEBAR_STATE});++async function openJsonEditor(page: import('@playwright/test').Page) {+ await navigateToSchemaTest(page);++ const jsonTab = page.getByRole('button', {name: 'JSON', exact: true});+ await expect(jsonTab).toBeVisible({timeout: 10_000});+ await jsonTab.click();++ const textarea = page.locator('textarea');+ await expect(textarea).toBeVisible({timeout: 10_000});+ return textarea;+}++test.describe('visual mode', () => {+ test('should edit props via JSON editor and save on blur', async ({+ page,+ }) => {+ const textarea = await openJsonEditor(page);++ const currentJson = await textarea.inputValue();+ const parsed = JSON.parse(currentJson);+ const newTitle = 'json-editor-e2e-test';++ const beforeContent = fs.readFileSync(rootFile, 'utf-8');+ expect(beforeContent).not.toContain(newTitle);++ parsed.title = newTitle;+ await textarea.fill(JSON.stringify(parsed, null, 2));+ await textarea.blur();++ await expect+ .poll(+ () => {+ const content = fs.readFileSync(rootFile, 'utf-8');+ return content.includes(newTitle);+ },+ {+ message: `Expected Root.tsx to contain "${newTitle}" after JSON editor edit`,+ timeout: 10_000,+ },+ )+ .toBe(true);+ });++ test('should show error and not save on blur when JSON is invalid', async ({+ page,+ }) => {+ const textarea = await openJsonEditor(page);+ const contentBefore = fs.readFileSync(rootFile, 'utf-8');++ await textarea.fill('{invalid json');++ await expect(+ page.locator('[data-testid="json-props-error"]'),+ ).not.toBeEmpty({timeout: 5_000});++ await textarea.blur();++ await page.waitForTimeout(500);+ expect(fs.readFileSync(rootFile, 'utf-8')).toBe(contentBefore);+ });++ test('should show error and not save on blur when JSON does not match schema', async ({+ page,+ }) => {+ const textarea = await openJsonEditor(page);+ const currentJson = await textarea.inputValue();+ const parsed = JSON.parse(currentJson);+ const contentBefore = fs.readFileSync(rootFile, 'utf-8');++ // delay: -1 violates the .min(0) constraint+ parsed.delay = -1;+ await textarea.fill(JSON.stringify(parsed, null, 2));++ await expect(+ page.locator('[data-testid="json-props-error"]'),+ ).not.toBeEmpty({timeout: 5_000});++ await textarea.blur();++ await page.waitForTimeout(500);+ expect(fs.readFileSync(rootFile, 'utf-8')).toBe(contentBefore);+ });+});diff --git a/packages/example/e2e/schema-editor.test.mts b/packages/example/e2e/schema-editor.test.mtsnew file mode 100644index 0000000000..6c7c5e5df4--- /dev/null+++ b/packages/example/e2e/schema-editor.test.mts@@ -0,0 +1,56 @@+import fs from 'fs';+import {expect, test} from '@playwright/test';+import {EXPANDED_SIDEBAR_STATE, rootFile} from './constants.mts';+import {navigateToSchemaTest, readStudioLogs, stripAnsi} from './helpers.mts';++test.use({storageState: EXPANDED_SIDEBAR_STATE});++test.describe('visual mode', () => {+ test('should edit a prop and update source code', async ({page}) => {+ await navigateToSchemaTest(page);++ const titleInput = page+ .locator(+ 'input[name="title"][type="text"], input[name="title"]:not([type="checkbox"])',+ )+ .first();+ await expect(titleInput).toBeVisible({timeout: 15_000});++ const newTitle = 'e2e-test-title';+ const beforeContent = fs.readFileSync(rootFile, 'utf-8');+ expect(beforeContent).not.toContain(newTitle);++ const logCountBefore = readStudioLogs().length;++ await titleInput.fill(newTitle);+ await titleInput.blur();++ await expect+ .poll(+ () => {+ const content = fs.readFileSync(rootFile, 'utf-8');+ return content.includes(newTitle);+ },+ {+ message: `Expected Root.tsx to contain "${newTitle}" after prop edit`,+ timeout: 10_000,+ },+ )+ .toBe(true);++ expect(fs.readFileSync(rootFile, 'utf-8')).toContain(newTitle);++ // Verify exactly 1 "Updated default props" log was emitted+ await expect+ .poll(+ () => {+ const newLogs = readStudioLogs().slice(logCountBefore);+ return newLogs.filter((log) =>+ stripAnsi(log).includes('Updated default props for "schema-test"'),+ ).length;+ },+ {timeout: 5_000},+ )+ .toBe(1);+ });+});diff --git a/packages/example/e2e/studio.test.mts b/packages/example/e2e/studio.test.mtsindex 8fdfb98e33..28a8131f08 100644--- a/packages/example/e2e/studio.test.mts+++ b/packages/example/e2e/studio.test.mts@@ -1,101 +1,8 @@-import {spawn, type ChildProcess} from 'child_process';-import fs from 'fs';-import path from 'path';import {expect, test} from '@playwright/test';+import {STUDIO_URL} from './constants.mts';+import {navigateToSchemaTest} from './helpers.mts';-let studioProcess: ChildProcess | undefined;--const STUDIO_PORT = 3123;-const STUDIO_URL = `http://localhost:${STUDIO_PORT}`;--const exampleDir = path.resolve(- // @ts-expect-error- new URL('.', import.meta.url).pathname,- '..',-);--const remotionBin = path.join(exampleDir, 'node_modules', '.bin', 'remotion');--const rootFile = path.join(exampleDir, 'src', 'Root.tsx');--async function waitForServer(- url: string,- timeoutMs: number = 30_000,-): Promise<void> {- const start = Date.now();- while (Date.now() - start < timeoutMs) {- try {- const res = await fetch(url);- if (res.ok) {- return;- }- } catch {- // Server not ready yet- }-- await new Promise((resolve) => setTimeout(resolve, 500));- }-- throw new Error(`Server at ${url} did not start within ${timeoutMs}ms`);-}--async function navigateToSchemaTest(page: import('@playwright/test').Page) {- await page.goto(STUDIO_URL);- // Expand the "Schema" folder in the sidebar- const schemaFolder = page.getByTitle('Schema');- await schemaFolder.click({timeout: 15_000});- // Click on the schema-test composition inside the folder- const schemaTestLink = page.getByText('schema-test', {exact: true}).first();- await schemaTestLink.click({timeout: 10_000});- await expect(page).toHaveURL(/schema-test/, {timeout: 10_000});-}--const studioStdoutLogs: string[] = [];-let originalRootContent: string;--test.beforeAll(async () => {- originalRootContent = fs.readFileSync(rootFile, 'utf-8');-- studioProcess = spawn(- remotionBin,- ['studio', '--port', String(STUDIO_PORT), '--props', 'src/my-props.json'],- {- cwd: exampleDir,- stdio: 'pipe',- env: {- ...process.env,- BROWSER: 'none',- },- },- );-- studioProcess.stderr?.on('data', (data: Buffer) => {- const msg = data.toString();- if (!msg.includes('ExperimentalWarning')) {- console.error('[studio stderr]', msg.trim());- }- });-- studioProcess.stdout?.on('data', (data: Buffer) => {- const msg = data.toString();- studioStdoutLogs.push(msg);- console.log('[studio stdout]', msg.trim());- });-- await waitForServer(STUDIO_URL);-});--test.afterAll(async () => {- if (studioProcess) {- studioProcess.kill('SIGTERM');- studioProcess = undefined;- }-- // Restore original file content- fs.writeFileSync(rootFile, originalRootContent);-});--test.describe('Remotion Studio', () => {+test.describe('visual mode', () => {test('should load the studio', async ({page}) => {await page.goto(STUDIO_URL);await expect(page).toHaveTitle(/Remotion/i, {timeout: 15_000});@@ -103,7 +10,6 @@ test.describe('Remotion Studio', () => {test('should show the composition list', async ({page}) => {await page.goto(STUDIO_URL);- // The Schema folder should be visible in the sidebarawait expect(page.getByRole('button', {name: 'Schema'})).toBeVisible({timeout: 15_000,});@@ -112,122 +18,4 @@ test.describe('Remotion Studio', () => {test('should navigate to schema-test composition', async ({page}) => {await navigateToSchemaTest(page);});-- test('should edit a prop and update source code', async ({page}) => {- // Expand the right sidebar- await page.goto(STUDIO_URL);- await page.evaluate(() => {- window.localStorage.setItem(- 'remotion.sidebarRightCollapsing',- 'expanded',- );- });- await page.reload();-- await navigateToSchemaTest(page);-- // Wait for the props editor to load - use the text input, not the nullable checkbox- const titleInput = page- .locator(- 'input[name="title"][type="text"], input[name="title"]:not([type="checkbox"])',- )- .first();- await expect(titleInput).toBeVisible({timeout: 15_000});-- // Verify the new value is not already in the file- const newTitle = 'e2e-test-title';- const beforeContent = fs.readFileSync(rootFile, 'utf-8');- expect(beforeContent).not.toContain(newTitle);-- await titleInput.fill(newTitle);-- // Blur the input to trigger save to file- await titleInput.blur();-- // Wait for the file to be updated- await expect- .poll(- () => {- const content = fs.readFileSync(rootFile, 'utf-8');- return content.includes(newTitle);- },- {- message: `Expected Root.tsx to contain "${newTitle}" after prop edit`,- timeout: 10_000,- },- )- .toBe(true);-- // Verify the old value is no longer in the file- const updatedContent = fs.readFileSync(rootFile, 'utf-8');- expect(updatedContent).not.toContain("title: 'sdasds'");- expect(updatedContent).toContain(newTitle);-- // Verify exactly 1 "Updated default props" log was emitted- // Strip ANSI escape codes for matching- const stripAnsi = (s: string) =>- // eslint-disable-next-line no-control-regex- s.replace(/\x1b\[[0-9;]*m/g, '').replace(/\]8;;[^\x1b]*\x1b\\/g, '');- const updateLogs = studioStdoutLogs.filter((log) => {- const clean = stripAnsi(log);- return clean.includes('Updated default props for "schema-test"');- });- expect(updateLogs).toHaveLength(1);- });-- test('should edit props via JSON editor and save on blur', async ({- page,- }) => {- // Expand the right sidebar- await page.goto(STUDIO_URL);- await page.evaluate(() => {- window.localStorage.setItem(- 'remotion.sidebarRightCollapsing',- 'expanded',- );- });- await page.reload();-- await navigateToSchemaTest(page);-- // Switch to JSON tab- const jsonTab = page.getByRole('button', {name: 'JSON', exact: true});- await expect(jsonTab).toBeVisible({timeout: 10_000});- await jsonTab.click();-- // Wait for the JSON textarea to appear- const textarea = page.locator('textarea');- await expect(textarea).toBeVisible({timeout: 10_000});-- // Read the current JSON, parse it, change the title, and set it back- const currentJson = await textarea.inputValue();- const parsed = JSON.parse(currentJson);- const newTitle = 'json-editor-e2e-test';-- // Verify the new value is not already in the source file- const beforeContent = fs.readFileSync(rootFile, 'utf-8');- expect(beforeContent).not.toContain(newTitle);-- parsed.title = newTitle;- const newJson = JSON.stringify(parsed, null, 2);-- await textarea.fill(newJson);-- // Blur to trigger save- await textarea.blur();-- // Wait for the file to be updated- await expect- .poll(- () => {- const content = fs.readFileSync(rootFile, 'utf-8');- return content.includes(newTitle);- },- {- message: `Expected Root.tsx to contain "${newTitle}" after JSON editor edit`,- timeout: 10_000,- },- )- .toBe(true);- });});diff --git a/packages/example/playwright.config.ts b/packages/example/playwright.config.tsindex 72fc706457..807640ce8a 100644--- a/packages/example/playwright.config.ts+++ b/packages/example/playwright.config.ts@@ -2,6 +2,8 @@ import {defineConfig, devices} from '@playwright/test';export default defineConfig({testDir: './e2e',+ globalSetup: './e2e/global-setup.mts',+ globalTeardown: './e2e/global-teardown.mts',timeout: 60_000,expect: {timeout: 10_000,diff --git a/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsx b/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsxindex 23d5a70fc6..6c6f75f583 100644--- a/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsx+++ b/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsx@@ -117,18 +117,20 @@ export const RenderModalJSONPropsEditor: React.FC<{style={textAreaStyle}/><Spacing y={1} />- {localValue.validJSON === false ? (- <ValidationMessage- align="flex-start"- message={localValue.error}- type="error"- />- ) : localValue.zodValidation.success === false ? (- <ZodErrorMessages- zodValidationResult={localValue.zodValidation}- viewTab="json"- />- ) : null}+ <div data-testid="json-props-error">+ {localValue.validJSON === false ? (+ <ValidationMessage+ align="flex-start"+ message={localValue.error}+ type="error"+ />+ ) : localValue.zodValidation.success === false ? (+ <ZodErrorMessages+ zodValidationResult={localValue.zodValidation}+ viewTab="json"+ />+ ) : null}+ </div><Spacing y={1} /><Row><Button