🎥 Make videos programmatically with React
undo stack
JonnyBurgere5c0eab894ee
diff --git a/packages/studio-server/src/codemods/update-default-props.ts b/packages/studio-server/src/codemods/update-default-props.tsindex 9830da0caa..616c4c1b18 100644--- a/packages/studio-server/src/codemods/update-default-props.ts+++ b/packages/studio-server/src/codemods/update-default-props.ts@@ -12,7 +12,7 @@ export const updateDefaultProps = async ({compositionId: string;newDefaultProps: Record<string, unknown>;enumPaths: EnumPath[];-}): Promise<Promise<Promise<Promise<string>>>> => {+}): Promise<{output: string; formatted: boolean}> => {const ast = parseAst(input);recast.types.visit(ast, {@@ -121,6 +121,8 @@ export const updateDefaultProps = async ({},});+ const finalfile = serializeAst(ast);+// 5: finally, format the file// eslint-disable-next-line @typescript-eslint/consistent-type-importstype PrettierType = typeof import('prettier');@@ -129,30 +131,26 @@ export const updateDefaultProps = async ({try {prettier = await import('prettier');} catch {- throw new Error('Prettier cannot be found in the current project.');+ return {output: finalfile, formatted: false};}const {format, resolveConfig, resolveConfigFile} = prettier as PrettierType;const configFilePath = await resolveConfigFile();if (!configFilePath) {- throw new Error('The Prettier config file was not found');+ return {output: finalfile, formatted: false};}const prettierConfig = await resolveConfig(configFilePath);if (!prettierConfig) {- throw new Error(- 'The Prettier config file was not found. For this feature, the "prettier" package must be installed and a .prettierrc file must exist.',- );+ return {output: finalfile, formatted: false};}- const finalfile = serializeAst(ast);-const prettified = await format(finalfile, {...prettierConfig,filepath: 'test.tsx',plugins: [],endOfLine: 'auto',});- return prettified;+ return {output: prettified, formatted: true};};diff --git a/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.tsindex 302d1039a4..ec0ff2d5c5 100644--- a/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts+++ b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts@@ -1,17 +1,22 @@import {readFileSync, writeFileSync} from 'node:fs';import path from 'node:path';+import {RenderInternals} from '@remotion/renderer';import type {ApplyVisualControlRequest,ApplyVisualControlResponse,} from '@remotion/studio-shared';import {parseAst, serializeAst} from '../../codemods/parse-ast';import {applyCodemod} from '../../codemods/recast-mods';+import {makeHyperlink} from '../../hyperlinks/make-link';import type {ApiHandler} from '../api-types';+import {suppressHmrForFile} from '../hmr-suppression';+import {pushToUndoStack, suppressUndoStackInvalidation} from '../undo-stack';+import {warnAboutPrettierOnce} from './log-update';export const applyVisualControlHandler: ApiHandler<ApplyVisualControlRequest,ApplyVisualControlResponse-> = ({input: {fileName, changes}, remotionRoot}) => {+> = async ({input: {fileName, changes}, remotionRoot, logLevel}) => {const absolutePath = path.resolve(remotionRoot, fileName);const fileRelativeToRoot = path.relative(remotionRoot, absolutePath);if (fileRelativeToRoot.startsWith('..')) {@@ -35,11 +40,51 @@ export const applyVisualControlHandler: ApiHandler<throw new Error('No changes were made to the file');}- const output = serializeAst(newAst);+ let output = serializeAst(newAst);+ let formatted = false;+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports+ type PrettierType = typeof import('prettier');+ try {+ const prettier: PrettierType = await import('prettier');+ const {format, resolveConfig, resolveConfigFile} = prettier;+ const configFilePath = await resolveConfigFile();+ if (configFilePath) {+ const prettierConfig = await resolveConfig(configFilePath);+ if (prettierConfig) {+ output = await format(output, {+ ...prettierConfig,+ filepath: 'test.tsx',+ plugins: [],+ endOfLine: 'auto',+ });+ formatted = true;+ }+ }+ } catch {+ // Prettier not available, use unformatted output+ }++ pushToUndoStack(absolutePath, fileContents);+ suppressUndoStackInvalidation(absolutePath);+ suppressHmrForFile(absolutePath);writeFileSync(absolutePath, output);- return Promise.resolve({- success: true,+ const locationLabel = `${fileRelativeToRoot}`;+ const fileLink = makeHyperlink({+ url: `file://${absolutePath}`,+ text: locationLabel,+ fallback: locationLabel,});+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${fileLink}:`)} Applied visual control changes`,+ );+ if (!formatted) {+ warnAboutPrettierOnce(logLevel);+ }++ return {+ success: true,+ };};diff --git a/packages/studio-server/src/preview-server/routes/log-update.ts b/packages/studio-server/src/preview-server/routes/log-update.tsindex b42be810f5..927272b781 100644--- a/packages/studio-server/src/preview-server/routes/log-update.ts+++ b/packages/studio-server/src/preview-server/routes/log-update.ts@@ -4,6 +4,20 @@ import {makeHyperlink} from '../../hyperlinks/make-link';let warnedAboutPrettier = false;+export const warnAboutPrettierOnce = (logLevel: LogLevel) => {+ if (warnedAboutPrettier) {+ return;+ }++ warnedAboutPrettier = true;+ RenderInternals.Log.warn(+ {indent: false, logLevel},+ RenderInternals.chalk.yellow(+ 'Could not format with Prettier. File will need to be formatted manually.',+ ),+ );+};+const normalizeQuotes = (str: string): string => {if (str.length >= 2 &&@@ -123,13 +137,7 @@ export const logUpdate = ({{indent: false, logLevel},`${RenderInternals.chalk.blueBright(`${fileLink}:`)} ${propChange}`,);- if (!formatted && !warnedAboutPrettier) {- warnedAboutPrettier = true;- RenderInternals.Log.warn(- {indent: false, logLevel},- RenderInternals.chalk.yellow(- 'Could not format with Prettier. File will need to be formatted manually.',- ),- );+ if (!formatted) {+ warnAboutPrettierOnce(logLevel);}};diff --git a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts b/packages/studio-server/src/preview-server/routes/save-sequence-props.tsindex e8cedab4c3..62d984f8f8 100644--- a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts+++ b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts@@ -7,6 +7,7 @@ import type {import {updateSequenceProps} from '../../codemods/update-sequence-props';import type {ApiHandler} from '../api-types';import {suppressHmrForFile} from '../hmr-suppression';+import {pushToUndoStack, suppressUndoStackInvalidation} from '../undo-stack';import {logUpdate} from './log-update';export const saveSequencePropsHandler: ApiHandler<@@ -34,6 +35,8 @@ export const saveSequencePropsHandler: ApiHandler<defaultValue: defaultValue !== null ? JSON.parse(defaultValue) : null,});+ pushToUndoStack(absolutePath, fileContents);+ suppressUndoStackInvalidation(absolutePath);suppressHmrForFile(absolutePath);writeFileSync(absolutePath, output);@@ -59,6 +62,7 @@ export const saveSequencePropsHandler: ApiHandler<return {success: false,reason: (err as Error).message,+ stack: (err as Error).stack as string,};}};diff --git a/packages/studio-server/src/preview-server/routes/update-default-props.ts b/packages/studio-server/src/preview-server/routes/update-default-props.tsindex afc5792fe9..b8601af331 100644--- a/packages/studio-server/src/preview-server/routes/update-default-props.ts+++ b/packages/studio-server/src/preview-server/routes/update-default-props.ts@@ -1,13 +1,18 @@import {readFileSync, writeFileSync} from 'node:fs';+import path from 'node:path';+import {RenderInternals} from '@remotion/renderer';import type {UpdateDefaultPropsRequest,UpdateDefaultPropsResponse,} from '@remotion/studio-shared';import {updateDefaultProps} from '../../codemods/update-default-props';+import {makeHyperlink} from '../../hyperlinks/make-link';import type {ApiHandler} from '../api-types';import {suppressHmrForFile} from '../hmr-suppression';import {getProjectInfo} from '../project-info';+import {pushToUndoStack, suppressUndoStackInvalidation} from '../undo-stack';import {checkIfTypeScriptFile} from './can-update-default-props';+import {warnAboutPrettierOnce} from './log-update';export const updateDefaultPropsHandler: ApiHandler<UpdateDefaultPropsRequest,@@ -16,6 +21,7 @@ export const updateDefaultPropsHandler: ApiHandler<input: {compositionId, defaultProps, enumPaths},remotionRoot,entryPoint,+ logLevel,}) => {try {const projectInfo = await getProjectInfo(remotionRoot, entryPoint);@@ -25,15 +31,37 @@ export const updateDefaultPropsHandler: ApiHandler<checkIfTypeScriptFile(projectInfo.rootFile);- const updated = await updateDefaultProps({+ const fileContents = readFileSync(projectInfo.rootFile, 'utf-8');+ const {output, formatted} = await updateDefaultProps({compositionId,- input: readFileSync(projectInfo.rootFile, 'utf-8'),+ input: fileContents,newDefaultProps: JSON.parse(defaultProps),enumPaths,});+ pushToUndoStack(projectInfo.rootFile, fileContents);+ suppressUndoStackInvalidation(projectInfo.rootFile);suppressHmrForFile(projectInfo.rootFile);- writeFileSync(projectInfo.rootFile, updated);+ writeFileSync(projectInfo.rootFile, output);++ const fileRelativeToRoot = path.relative(+ remotionRoot,+ projectInfo.rootFile,+ );+ const locationLabel = `${fileRelativeToRoot}`;+ const fileLink = makeHyperlink({+ url: `file://${projectInfo.rootFile}`,+ text: locationLabel,+ fallback: locationLabel,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${fileLink}:`)} Updated default props for "${compositionId}"`,+ );+ if (!formatted) {+ warnAboutPrettierOnce(logLevel);+ }+return {success: true,};diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.tsnew file mode 100644index 0000000000..5f1df5002f--- /dev/null+++ b/packages/studio-server/src/preview-server/undo-stack.ts@@ -0,0 +1,74 @@+import {installFileWatcher} from '../file-watcher';++interface UndoEntry {+ filePath: string;+ oldContents: string;+}++const MAX_ENTRIES = 100;+const stack: UndoEntry[] = [];+const suppressedWrites = new Set<string>();+const watchers = new Map<string, {unwatch: () => void}>();++export function pushToUndoStack(filePath: string, oldContents: string) {+ stack.push({filePath, oldContents});+ if (stack.length > MAX_ENTRIES) {+ stack.shift();+ }++ ensureWatching(filePath);+}++export function suppressUndoStackInvalidation(filePath: string) {+ suppressedWrites.add(filePath);+}++function ensureWatching(filePath: string) {+ if (watchers.has(filePath)) {+ return;+ }++ const watcher = installFileWatcher({+ file: filePath,+ onChange: () => {+ if (suppressedWrites.has(filePath)) {+ suppressedWrites.delete(filePath);+ return;+ }++ invalidateForFile(filePath);+ },+ });++ watchers.set(filePath, watcher);+}++function invalidateForFile(filePath: string) {+ let lastIndex = -1;+ for (let i = stack.length - 1; i >= 0; i--) {+ if (stack[i].filePath === filePath) {+ lastIndex = i;+ break;+ }+ }++ if (lastIndex !== -1) {+ stack.splice(0, lastIndex + 1);+ }++ cleanupWatchers();+}++function cleanupWatchers() {+ const filesInStack = new Set(stack.map((e) => e.filePath));+ for (const [filePath, watcher] of watchers) {+ if (!filesInStack.has(filePath)) {+ watcher.unwatch();+ watchers.delete(filePath);+ }+ }+}++export function getUndoStack(): readonly UndoEntry[] {+ return stack;+}diff --git a/packages/studio-server/src/test/update-default-props.test.ts b/packages/studio-server/src/test/update-default-props.test.tsindex 02291e0de5..6afac05ee5 100644--- a/packages/studio-server/src/test/update-default-props.test.ts+++ b/packages/studio-server/src/test/update-default-props.test.ts@@ -13,14 +13,14 @@ test('Should be able to update default props', async () => {'utf-8',);- const update = await updateDefaultProps({+ const {output} = await updateDefaultProps({input: file,compositionId: 'Comp3',newDefaultProps: {abc: 'def', newDate: 'remotion-date:2022-01-02'},enumPaths: [],});- expect(update).toBe(expected);+ expect(output).toBe(expected);});test('Should be able to update default props', async () => {@@ -33,12 +33,12 @@ test('Should be able to update default props', async () => {'utf-8',);- const update = await updateDefaultProps({+ const {output} = await updateDefaultProps({input: file,compositionId: 'schema-test',newDefaultProps: {abc: 'def', newDate: 'remotion-date:2022-01-02'},enumPaths: [],});- expect(update).toBe(expected);+ expect(output).toBe(expected);});diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 56ef10e1ad..2efe28a80d 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -251,6 +251,7 @@ export type SaveSequencePropsResponse =| {success: false;reason: string;+ stack: string;};export type UpdateAvailableRequest = {};