π₯ Make videos programmatically with React
Fix e2e test flakiness: restart server per test, wait for source maps
Jonny Burgerd7f54db974b2
diff --git a/packages/example/e2e/global-setup.mts b/packages/example/e2e/global-setup.mtsindex 44617c3824..6f0262b29f 100644--- a/packages/example/e2e/global-setup.mts+++ b/packages/example/e2e/global-setup.mts@@ -1,101 +1,15 @@-import {spawn} from 'child_process';import fs from 'fs';import {- EXPANDED_SIDEBAR_STATE,- LOGS_FILE,ORIGINAL_CONTENT_FILE,ORIGINAL_VISUAL_CONTROLS_FILE,- PID_FILE,- STUDIO_PORT,- STUDIO_URL,- exampleDir,- remotionBin,rootFile,visualControlsFile,} 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(ORIGINAL_VISUAL_CONTROLS_FILE,fs.readFileSync(visualControlsFile, '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',- '--log=trace',- ],- {- 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.mtsindex 10f5a3b892..4b35f17837 100644--- a/packages/example/e2e/global-teardown.mts+++ b/packages/example/e2e/global-teardown.mts@@ -2,23 +2,11 @@ import fs from 'fs';import {ORIGINAL_CONTENT_FILE,ORIGINAL_VISUAL_CONTROLS_FILE,- PID_FILE,rootFile,visualControlsFile,} 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,diff --git a/packages/example/e2e/helpers.mts b/packages/example/e2e/helpers.mtsindex 0590ebe864..bb79f756f6 100644--- a/packages/example/e2e/helpers.mts+++ b/packages/example/e2e/helpers.mts@@ -14,13 +14,6 @@ export async function navigateToSchemaTest(page: Page): Promise<void> {export async function navigateToVisualControls(page: Page): Promise<void> {await page.goto(STUDIO_URL);- // Wait for any in-progress build to settle before interacting.- // The afterEach of the previous test may have written a file that- // triggered a webpack rebuild.- await page.waitForFunction(- () => !document.querySelector('.__remotion_spinner_line'),- {timeout: 30_000},- );const folder = page.getByTitle('visual-controls');await folder.click({timeout: 15_000});const compositionLink = page.locator(@@ -30,6 +23,20 @@ export async function navigateToVisualControls(page: Page): Promise<void> {await expect(page).toHaveURL(/visual-controls/, {timeout: 10_000});}+export async function openVisualControlsPanel(page: Page): Promise<void> {+ await navigateToVisualControls(page);+ const controlsTab = page.getByText('Controls', {exact: true});+ await expect(controlsTab).toBeVisible({timeout: 15_000});+ await controlsTab.click();++ // Wait for the source map to resolve β the header shows "Loading..."+ // until it's done, then shows the file name.+ await page.waitForFunction(+ () => !document.body.innerText.includes('Loading...'),+ {timeout: 15_000},+ );+}+export const stripAnsi = (s: string) =>// eslint-disable-next-line no-control-regexs.replace(/\x1b\[[0-9;]*m/g, '').replace(/\]8;;[^\x1b]*\x1b\\/g, '');diff --git a/packages/example/e2e/json-editor.test.mts b/packages/example/e2e/json-editor.test.mtsindex ce7a36b2a1..b707e775bb 100644--- a/packages/example/e2e/json-editor.test.mts+++ b/packages/example/e2e/json-editor.test.mts@@ -2,6 +2,7 @@ import {expect, test} from '@playwright/test';import fs from 'fs';import {EXPANDED_SIDEBAR_STATE, rootFile} from './constants.mts';import {navigateToSchemaTest} from './helpers.mts';+import {startStudio, stopStudio} from './studio-server.mts';test.use({storageState: EXPANDED_SIDEBAR_STATE});@@ -18,6 +19,14 @@ async function openJsonEditor(page: import('@playwright/test').Page) {}test.describe('visual mode', () => {+ test.beforeEach(async () => {+ await startStudio();+ });++ test.afterEach(async () => {+ await stopStudio();+ });+test('should edit props via JSON editor and save on blur', async ({page,}) => {diff --git a/packages/example/e2e/schema-editor.test.mts b/packages/example/e2e/schema-editor.test.mtsindex 6c7c5e5df4..5eab8d14b7 100644--- a/packages/example/e2e/schema-editor.test.mts+++ b/packages/example/e2e/schema-editor.test.mts@@ -2,10 +2,19 @@ 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';+import {startStudio, stopStudio} from './studio-server.mts';test.use({storageState: EXPANDED_SIDEBAR_STATE});test.describe('visual mode', () => {+ test.beforeEach(async () => {+ await startStudio();+ });++ test.afterEach(async () => {+ await stopStudio();+ });+test('should edit a prop and update source code', async ({page}) => {await navigateToSchemaTest(page);diff --git a/packages/example/e2e/studio-server.mts b/packages/example/e2e/studio-server.mtsnew file mode 100644index 0000000000..d8a62ded36--- /dev/null+++ b/packages/example/e2e/studio-server.mts@@ -0,0 +1,191 @@+import type {ChildProcess} from 'child_process';+import {spawn} from 'child_process';+import fs from 'fs';+import {+ EXPANDED_SIDEBAR_STATE,+ LOGS_FILE,+ ORIGINAL_CONTENT_FILE,+ ORIGINAL_VISUAL_CONTROLS_FILE,+ STUDIO_PORT,+ STUDIO_URL,+ exampleDir,+ remotionBin,+ rootFile,+ visualControlsFile,+} from './constants.mts';++let studioProcess: ChildProcess | null = null;++async function waitForServer(+ url: string,+ timeoutMs: number = 60_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 async function startStudio(): Promise<void> {+ // Save original files if not already saved+ if (!fs.existsSync(ORIGINAL_CONTENT_FILE)) {+ fs.writeFileSync(+ ORIGINAL_CONTENT_FILE,+ fs.readFileSync(rootFile, 'utf-8'),+ );+ }++ if (!fs.existsSync(ORIGINAL_VISUAL_CONTROLS_FILE)) {+ fs.writeFileSync(+ ORIGINAL_VISUAL_CONTROLS_FILE,+ fs.readFileSync(visualControlsFile, 'utf-8'),+ );+ }++ // Restore original files before starting+ fs.writeFileSync(+ rootFile,+ fs.readFileSync(ORIGINAL_CONTENT_FILE, 'utf-8'),+ );+ fs.writeFileSync(+ visualControlsFile,+ fs.readFileSync(ORIGINAL_VISUAL_CONTROLS_FILE, 'utf-8'),+ );++ fs.writeFileSync(LOGS_FILE, '');+ fs.writeFileSync(+ EXPANDED_SIDEBAR_STATE,+ JSON.stringify({+ cookies: [],+ origins: [+ {+ origin: STUDIO_URL,+ localStorage: [+ {+ name: 'remotion.sidebarRightCollapsing',+ value: 'expanded',+ },+ ],+ },+ ],+ }),+ );++ studioProcess = spawn(+ remotionBin,+ [+ 'studio',+ '--port',+ String(STUDIO_PORT),+ '--props',+ 'src/my-props.json',+ '--log=trace',+ ],+ {+ cwd: exampleDir,+ stdio: 'pipe',+ env: {+ ...process.env,+ BROWSER: 'none',+ },+ },+ );++ let buildResolve: (() => void) | null = null;+ const buildPromise = new Promise<void>((resolve) => {+ buildResolve = resolve;+ });++ 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`);+ if (msg.includes('Built in') && buildResolve) {+ buildResolve();+ buildResolve = null;+ }+ });++ await waitForServer(STUDIO_URL);+ await buildPromise;++ // Wait until no new "Building..." appears for 3 seconds,+ // meaning all builds (including secondary ones) have settled.+ let lastBuildTime = Date.now();+ const onData = (data: Buffer) => {+ const msg = data.toString();+ if (msg.includes('Building...') || msg.includes('Built in')) {+ lastBuildTime = Date.now();+ }+ };++ studioProcess.stdout?.on('data', onData);+ await new Promise<void>((resolve) => {+ const check = () => {+ if (Date.now() - lastBuildTime >= 3_000) {+ studioProcess?.stdout?.removeListener('data', onData);+ resolve();+ } else {+ setTimeout(check, 500);+ }+ };++ setTimeout(check, 500);+ });+}++export async function stopStudio(): Promise<void> {+ if (studioProcess?.pid) {+ try {+ process.kill(studioProcess.pid, 'SIGTERM');+ } catch {+ // Process might already be dead+ }++ // Wait for process to exit+ await new Promise<void>((resolve) => {+ if (!studioProcess) {+ resolve();+ return;+ }++ studioProcess.on('exit', () => resolve());+ setTimeout(resolve, 5_000);+ });+ }++ studioProcess = null;++ // Restore original files+ if (fs.existsSync(ORIGINAL_CONTENT_FILE)) {+ fs.writeFileSync(+ rootFile,+ fs.readFileSync(ORIGINAL_CONTENT_FILE, 'utf-8'),+ );+ }++ if (fs.existsSync(ORIGINAL_VISUAL_CONTROLS_FILE)) {+ fs.writeFileSync(+ visualControlsFile,+ fs.readFileSync(ORIGINAL_VISUAL_CONTROLS_FILE, 'utf-8'),+ );+ }+}diff --git a/packages/example/e2e/studio.test.mts b/packages/example/e2e/studio.test.mtsindex 28a8131f08..a667e17f92 100644--- a/packages/example/e2e/studio.test.mts+++ b/packages/example/e2e/studio.test.mts@@ -1,8 +1,17 @@import {expect, test} from '@playwright/test';import {STUDIO_URL} from './constants.mts';import {navigateToSchemaTest} from './helpers.mts';+import {startStudio, stopStudio} from './studio-server.mts';test.describe('visual mode', () => {+ test.beforeEach(async () => {+ await startStudio();+ });++ test.afterEach(async () => {+ await stopStudio();+ });+test('should load the studio', async ({page}) => {await page.goto(STUDIO_URL);await expect(page).toHaveTitle(/Remotion/i, {timeout: 15_000});diff --git a/packages/example/e2e/suppress-rebuild.test.mts b/packages/example/e2e/suppress-rebuild.test.mtsindex c545066f43..7d7b9fb7e1 100644--- a/packages/example/e2e/suppress-rebuild.test.mts+++ b/packages/example/e2e/suppress-rebuild.test.mts@@ -2,8 +2,17 @@ import fs from 'fs';import {expect, test} from '@playwright/test';import {rootFile, STUDIO_URL} from './constants.mts';import {readStudioLogs, stripAnsi} from './helpers.mts';+import {startStudio, stopStudio} from './studio-server.mts';test.describe('suppress webpack rebuild', () => {+ test.beforeEach(async () => {+ await startStudio();+ });++ test.afterEach(async () => {+ await stopStudio();+ });+test('updating default props via API should not trigger a webpack rebuild, but a manual file edit should', async () => {const logCountBefore = readStudioLogs().length;diff --git a/packages/example/e2e/undo-redo-sync.test.mts b/packages/example/e2e/undo-redo-sync.test.mtsindex 2abb715d60..7ac2326642 100644--- a/packages/example/e2e/undo-redo-sync.test.mts+++ b/packages/example/e2e/undo-redo-sync.test.mts@@ -5,10 +5,19 @@ import {STUDIO_URL,newVideoFile,} from './constants.mts';+import {startStudio, stopStudio} from './studio-server.mts';test.use({storageState: EXPANDED_SIDEBAR_STATE});test.describe('undo redo sync across tabs', () => {+ test.beforeEach(async () => {+ await startStudio();+ });++ test.afterEach(async () => {+ await stopStudio();+ });+test('a new studio tab should receive the current undo/redo state', async ({browser,}) => {diff --git a/packages/example/e2e/undo-redo.test.mts b/packages/example/e2e/undo-redo.test.mtsindex c3fee8cedc..36570a2240 100644--- a/packages/example/e2e/undo-redo.test.mts+++ b/packages/example/e2e/undo-redo.test.mts@@ -5,10 +5,19 @@ import {STUDIO_URL,newVideoFile,} from './constants.mts';+import {startStudio, stopStudio} from './studio-server.mts';test.use({storageState: EXPANDED_SIDEBAR_STATE});test.describe('undo redo', () => {+ test.beforeEach(async () => {+ await startStudio();+ });++ test.afterEach(async () => {+ await stopStudio();+ });+test('should undo and redo a playback rate change', async ({page}) => {const originalContent = fs.readFileSync(newVideoFile, 'utf-8');expect(originalContent).not.toContain('playbackRate');diff --git a/packages/example/e2e/visual-controls.test.mts b/packages/example/e2e/visual-controls.test.mtsindex 085b24006f..5bff30dc8d 100644--- a/packages/example/e2e/visual-controls.test.mts+++ b/packages/example/e2e/visual-controls.test.mts@@ -1,28 +1,22 @@import fs from 'fs';import {expect, test} from '@playwright/test';import {EXPANDED_SIDEBAR_STATE, visualControlsFile} from './constants.mts';-import {navigateToVisualControls} from './helpers.mts';+import {openVisualControlsPanel} from './helpers.mts';+import {startStudio, stopStudio} from './studio-server.mts';test.use({storageState: EXPANDED_SIDEBAR_STATE});test.describe('visual controls', () => {- let originalContent: string;-- test.beforeEach(() => {- originalContent = fs.readFileSync(visualControlsFile, 'utf-8');+ test.beforeEach(async () => {+ await startStudio();});- test.afterEach(() => {- fs.writeFileSync(visualControlsFile, originalContent);+ test.afterEach(async () => {+ await stopStudio();});test('should edit rotation and update source file', async ({page}) => {- await navigateToVisualControls(page);-- // Click the Controls tab on the right panel- const controlsTab = page.getByText('Controls', {exact: true});- await expect(controlsTab).toBeVisible({timeout: 15_000});- await controlsTab.click();+ await openVisualControlsPanel(page);// Find the rotation control's fieldset via the data-json-path labelconst rotationFieldset = page@@ -61,12 +55,7 @@ test.describe('visual controls', () => {});test('should edit label string and update source file', async ({page}) => {- await navigateToVisualControls(page);-- // Click the Controls tab on the right panel- const controlsTab = page.getByText('Controls', {exact: true});- await expect(controlsTab).toBeVisible({timeout: 15_000});- await controlsTab.click();+ await openVisualControlsPanel(page);// Find the label string input by its name attributeconst labelInput = page.locator('input[name="label"]');@@ -94,11 +83,7 @@ test.describe('visual controls', () => {test('should edit nullable subtitle and update source file', async ({page,}) => {- await navigateToVisualControls(page);-- const controlsTab = page.getByText('Controls', {exact: true});- await expect(controlsTab).toBeVisible({timeout: 15_000});- await controlsTab.click();+ await openVisualControlsPanel(page);// Edit the subtitle text (nullable string, default 'A subtitle')const subtitleInput = page.locator(@@ -146,11 +131,7 @@ test.describe('visual controls', () => {test('should edit optional extra-rotation and update source file', async ({page,}) => {- await navigateToVisualControls(page);-- const controlsTab = page.getByText('Controls', {exact: true});- await expect(controlsTab).toBeVisible({timeout: 15_000});- await controlsTab.click();+ await openVisualControlsPanel(page);// The extra-rotation control defaults to undefined.// First, enable it by unchecking the "undefined" checkbox.@@ -180,9 +161,7 @@ test.describe('visual controls', () => {() => {const content = fs.readFileSync(visualControlsFile, 'utf-8');// The codemod may format the value on the next line- const match = content.match(- /'extra-rotation',\s*(\d+)/,- );+ const match = content.match(/'extra-rotation',\s*(\d+)/);return match?.[1] === newValue;},{diff --git a/packages/studio/src/visual-controls/VisualControls.tsx b/packages/studio/src/visual-controls/VisualControls.tsxindex ed138c13a4..bbb6f3aa2c 100644--- a/packages/studio/src/visual-controls/VisualControls.tsx+++ b/packages/studio/src/visual-controls/VisualControls.tsx@@ -95,7 +95,7 @@ export const VisualControlsProvider: React.FC<{[key]: {...value,unsavedValue:- existingHandle !== undefined+ existingHandle !== undefined && !changedSavedValue? existingHandle.unsavedValue: value.valueInCode,valueInCode: value.valueInCode,@@ -191,19 +191,6 @@ export const VisualControlsProvider: React.FC<{};}, [updateHandles]);- useEffect(() => {- const prev = window.remotion_finishedBuilding;- window.remotion_finishedBuilding = () => {- prev?.();- imperativeHandles.current = {};- setHandles({});- };-- return () => {- window.remotion_finishedBuilding = prev;- };- }, []);-const setState: SetVisualControlsContextType = useMemo(() => {return {setControl,