Skip to content

πŸŽ₯ Make videos programmatically with React

cool

Jonny Burgerb7604137c218
diff --git a/packages/example/e2e/visual-controls.test.mts b/packages/example/e2e/visual-controls.test.mts
index 4c8bc4715c..44e292ed75 100644
--- a/packages/example/e2e/visual-controls.test.mts
+++ b/packages/example/e2e/visual-controls.test.mts
@@ -59,4 +59,144 @@ test.describe('visual controls', () => {
)
.toBe(true);
});
+
+ 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();
+
+ // Find the label string input by its name attribute
+ const labelInput = page.locator('input[name="label"]');
+ await expect(labelInput).toBeVisible({timeout: 10_000});
+
+ const newLabel = 'e2e-test-label';
+ await labelInput.fill(newLabel);
+ await labelInput.blur();
+
+ // Wait for the source file to be updated on disk
+ await expect
+ .poll(
+ () => {
+ const content = fs.readFileSync(visualControlsFile, 'utf-8');
+ return content.includes(newLabel);
+ },
+ {
+ message: `Expected VisualControls/index.tsx to contain label "${newLabel}"`,
+ timeout: 10_000,
+ },
+ )
+ .toBe(true);
+ });
+
+ 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();
+
+ // Edit the subtitle text (nullable string, default 'A subtitle')
+ const subtitleInput = page.locator('input[name="subtitle"]');
+ await expect(subtitleInput).toBeVisible({timeout: 10_000});
+
+ const newSubtitle = 'e2e-nullable-test';
+ await subtitleInput.fill(newSubtitle);
+ await subtitleInput.blur();
+
+ await expect
+ .poll(
+ () => {
+ const content = fs.readFileSync(visualControlsFile, 'utf-8');
+ return content.includes(newSubtitle);
+ },
+ {
+ message: `Expected VisualControls/index.tsx to contain subtitle "${newSubtitle}"`,
+ timeout: 10_000,
+ },
+ )
+ .toBe(true);
+
+ // Now toggle to null via the checkbox
+ const nullCheckbox = page.locator('input[name="subtitle"][type="checkbox"]');
+ await expect(nullCheckbox).toBeVisible({timeout: 5_000});
+ await nullCheckbox.check();
+
+ await expect
+ .poll(
+ () => {
+ const content = fs.readFileSync(visualControlsFile, 'utf-8');
+ return content.includes("'subtitle', null");
+ },
+ {
+ message:
+ 'Expected VisualControls/index.tsx to contain subtitle set to null',
+ timeout: 10_000,
+ },
+ )
+ .toBe(true);
+ });
+
+ 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();
+
+ // Find the extra-rotation fieldset and its dragger
+ const fieldset = page
+ .locator('[data-json-path="extra-rotation"]')
+ .locator('..');
+ const dragger = fieldset.locator('button.__remotion_input_dragger');
+ await expect(dragger).toBeVisible({timeout: 10_000});
+ await dragger.click();
+
+ const input = fieldset.locator('input[type="number"]');
+ await expect(input).toBeVisible({timeout: 5_000});
+
+ const newValue = '90';
+ await input.fill(newValue);
+ await input.press('Enter');
+
+ await expect
+ .poll(
+ () => {
+ const content = fs.readFileSync(visualControlsFile, 'utf-8');
+ return content.includes(`'extra-rotation', ${newValue}`);
+ },
+ {
+ message: `Expected VisualControls/index.tsx to contain extra-rotation value ${newValue}`,
+ timeout: 10_000,
+ },
+ )
+ .toBe(true);
+
+ // Now toggle to undefined via the checkbox
+ const undefinedCheckbox = page.locator(
+ 'input[name="extra-rotation"][type="checkbox"]',
+ );
+ await expect(undefinedCheckbox).toBeVisible({timeout: 5_000});
+ await undefinedCheckbox.check();
+
+ await expect
+ .poll(
+ () => {
+ const content = fs.readFileSync(visualControlsFile, 'utf-8');
+ return content.includes("'extra-rotation', undefined");
+ },
+ {
+ message:
+ 'Expected VisualControls/index.tsx to contain extra-rotation set to undefined',
+ timeout: 10_000,
+ },
+ )
+ .toBe(true);
+ });
});
diff --git a/packages/it-tests/src/codemods/visual-controls.test.ts b/packages/it-tests/src/codemods/visual-controls.test.ts
index 8282c2b580..e0e9726693 100644
--- a/packages/it-tests/src/codemods/visual-controls.test.ts
+++ b/packages/it-tests/src/codemods/visual-controls.test.ts
@@ -45,11 +45,13 @@ test('Should be able to create visual control', () => {
{
id: 'my-matrix-4',
newValueSerialized: JSON.stringify(123),
+ newValueIsUndefined: false,
enumPaths: [],
},
{
id: 'my-matrix-2',
newValueSerialized: JSON.stringify(456),
+ newValueIsUndefined: false,
enumPaths: [[]],
},
],
diff --git a/packages/studio-server/src/codemods/apply-visual-control.ts b/packages/studio-server/src/codemods/apply-visual-control.ts
index 7dc98bbda4..4e35b6fc20 100644
--- a/packages/studio-server/src/codemods/apply-visual-control.ts
+++ b/packages/studio-server/src/codemods/apply-visual-control.ts
@@ -65,13 +65,23 @@ export const applyVisualControl = ({
continue;
}
- const parsed = (
- (
- parseAst(
- `a = ${stringifyDefaultProps({props: JSON.parse(change.newValueSerialized), enumPaths: change.enumPaths})}`,
- ).program.body[0] as unknown as ExpressionStatement
- ).expression as AssignmentExpression
- ).right as ExpressionKind;
+ let parsed: ExpressionKind;
+ if (change.newValueIsUndefined) {
+ parsed = (
+ (
+ parseAst('a = undefined').program
+ .body[0] as unknown as ExpressionStatement
+ ).expression as AssignmentExpression
+ ).right as ExpressionKind;
+ } else {
+ parsed = (
+ (
+ parseAst(
+ `a = ${stringifyDefaultProps({props: JSON.parse(change.newValueSerialized), enumPaths: change.enumPaths})}`,
+ ).program.body[0] as unknown as ExpressionStatement
+ ).expression as AssignmentExpression
+ ).right as ExpressionKind;
+ }
node.arguments[1] = parsed;
diff --git a/packages/studio-server/src/codemods/format-inline-content.ts b/packages/studio-server/src/codemods/format-inline-content.ts
new file mode 100644
index 0000000000..be239c6bcf
--- /dev/null
+++ b/packages/studio-server/src/codemods/format-inline-content.ts
@@ -0,0 +1,98 @@
+// eslint-disable-next-line @typescript-eslint/consistent-type-imports
+type PrettierType = typeof import('prettier');
+
+/**
+ * Instead of running prettier on the entire file (which is slow),
+ * format only a small snippet of inline content (e.g. stringified defaultProps).
+ *
+ * @param inlineContent - The raw content to format (e.g. stringified props)
+ * @param linePrefix - Everything from the start of the line to where
+ * inlineContent will appear (used to calculate column offset and indentation)
+ * @param endOfLine - Prettier endOfLine option
+ *
+ * We wrap the content in `const __x__ = CONTENT;` and adjust printWidth
+ * so prettier makes the same line-breaking decisions as if the content
+ * were at its actual column position in the file.
+ */
+export const formatInlineContent = async ({
+ inlineContent,
+ linePrefix,
+ endOfLine,
+}: {
+ inlineContent: string;
+ linePrefix: string;
+ endOfLine: 'auto' | 'lf';
+}): Promise<{formatted: string; didFormat: boolean}> => {
+ let prettier: PrettierType | null = null;
+
+ try {
+ prettier = await import('prettier');
+ } catch {
+ return {formatted: inlineContent, didFormat: false};
+ }
+
+ const {format, resolveConfig, resolveConfigFile} = prettier as PrettierType;
+
+ const configFilePath = await resolveConfigFile();
+ if (!configFilePath) {
+ return {formatted: inlineContent, didFormat: false};
+ }
+
+ const prettierConfig = await resolveConfig(configFilePath);
+ if (!prettierConfig) {
+ return {formatted: inlineContent, didFormat: false};
+ }
+
+ const tabWidth = (prettierConfig.tabWidth as number) ?? 2;
+ const baseIndent = linePrefix.match(/^(\s*)/)?.[1] ?? '';
+
+ // Calculate visual column offset (tabs expand to tabWidth columns)
+ const columnOffset = [...linePrefix].reduce(
+ (col, ch) => (ch === '\t' ? col + tabWidth : col + 1),
+ 0,
+ );
+
+ // Adjust printWidth so the wrapper prefix occupies the same visual
+ // width as the actual file prefix, ensuring identical line breaks.
+ const configPrintWidth = (prettierConfig.printWidth as number) ?? 80;
+ const wrapperPrefix = 'const __x__ = ';
+ const effectivePrintWidth = Math.max(
+ configPrintWidth - columnOffset + wrapperPrefix.length,
+ 20,
+ );
+
+ const wrappedSource = `${wrapperPrefix}${inlineContent};\n`;
+ const formattedWrapped = await format(wrappedSource, {
+ ...prettierConfig,
+ printWidth: effectivePrintWidth,
+ filepath: 'test.tsx',
+ plugins: [],
+ endOfLine,
+ });
+
+ // Extract the formatted value from the wrapper
+ const withoutSemicolon = formattedWrapped.replace(/;\s*$/, '');
+ let formattedProps: string;
+
+ if (withoutSemicolon.startsWith(wrapperPrefix)) {
+ formattedProps = withoutSemicolon.slice(wrapperPrefix.length);
+ } else {
+ // Prettier broke the line after `=` β€” extract and dedent one level
+ const lines = withoutSemicolon.split('\n').slice(1);
+ const useTabs = prettierConfig.useTabs as boolean;
+ const oneIndent = useTabs ? '\t' : ' '.repeat(tabWidth);
+ formattedProps = lines
+ .map((l) => (l.startsWith(oneIndent) ? l.slice(oneIndent.length) : l))
+ .join('\n');
+ }
+
+ // Add base indentation to all lines except the first
+ const indentedProps = formattedProps
+ .split('\n')
+ .map((line, i) =>
+ i === 0 ? line : line.length > 0 ? baseIndent + line : line,
+ )
+ .join('\n');
+
+ return {formatted: indentedProps, didFormat: true};
+};
diff --git a/packages/studio-server/src/codemods/read-visual-control-values.ts b/packages/studio-server/src/codemods/read-visual-control-values.ts
new file mode 100644
index 0000000000..85c4e8703f
--- /dev/null
+++ b/packages/studio-server/src/codemods/read-visual-control-values.ts
@@ -0,0 +1,189 @@
+import type {File} from '@babel/types';
+import type {ExpressionKind} from 'ast-types/lib/gen/kinds';
+import * as recast from 'recast';
+
+export type VisualControlValueFromCode = {
+ id: string;
+ value: unknown;
+ isUndefined: boolean;
+};
+
+const getStringValue = (
+ node: ExpressionKind | recast.types.namedTypes.SpreadElement,
+): string | null => {
+ if (node.type === 'StringLiteral') {
+ return (node as unknown as {value: string}).value;
+ }
+
+ if (node.type === 'TemplateLiteral') {
+ const tl = node as unknown as {
+ expressions: unknown[];
+ quasis: Array<{value: {raw: string}}>;
+ };
+ if (tl.expressions.length > 0) {
+ return null;
+ }
+
+ return tl.quasis[0].value.raw;
+ }
+
+ return null;
+};
+
+const evaluateExpression = (node: ExpressionKind): unknown => {
+ switch (node.type) {
+ case 'NumericLiteral':
+ return (node as unknown as {value: number}).value;
+ case 'StringLiteral':
+ return (node as unknown as {value: string}).value;
+ case 'BooleanLiteral':
+ return (node as unknown as {value: boolean}).value;
+ case 'NullLiteral':
+ return null;
+ case 'Identifier': {
+ const name = (node as unknown as {name: string}).name;
+ if (name === 'undefined') {
+ return undefined;
+ }
+
+ throw new Error(`Cannot evaluate identifier: ${name}`);
+ }
+
+ case 'UnaryExpression': {
+ const unary = node as unknown as {
+ operator: string;
+ argument: ExpressionKind;
+ };
+ if (unary.operator === '-') {
+ const arg = evaluateExpression(unary.argument);
+ if (typeof arg === 'number') {
+ return -arg;
+ }
+ }
+
+ if (unary.operator === '+') {
+ const arg = evaluateExpression(unary.argument);
+ if (typeof arg === 'number') {
+ return arg;
+ }
+ }
+
+ throw new Error(`Cannot evaluate unary: ${unary.operator}`);
+ }
+
+ case 'ObjectExpression': {
+ const obj: Record<string, unknown> = {};
+ const properties = (
+ node as unknown as {
+ properties: Array<{
+ type: string;
+ key: {type: string; name?: string; value?: string | number};
+ value: ExpressionKind;
+ }>;
+ }
+ ).properties;
+ for (const prop of properties) {
+ if (prop.type !== 'ObjectProperty') {
+ continue;
+ }
+
+ let key: string | null = null;
+ if (prop.key.type === 'Identifier') {
+ key = prop.key.name as string;
+ } else if (prop.key.type === 'StringLiteral') {
+ key = prop.key.value as string;
+ } else if (prop.key.type === 'NumericLiteral') {
+ key = String(prop.key.value);
+ }
+
+ if (key !== null) {
+ obj[key] = evaluateExpression(prop.value);
+ }
+ }
+
+ return obj;
+ }
+
+ case 'ArrayExpression': {
+ const elements = (
+ node as unknown as {elements: Array<ExpressionKind | null>}
+ ).elements;
+ return elements.map((el) => {
+ if (el === null) {
+ return null;
+ }
+
+ return evaluateExpression(el);
+ });
+ }
+
+ case 'TemplateLiteral': {
+ const tl = node as unknown as {
+ expressions: unknown[];
+ quasis: Array<{value: {cooked: string}}>;
+ };
+ if (tl.expressions.length === 0) {
+ return tl.quasis[0].value.cooked;
+ }
+
+ throw new Error('Cannot evaluate template literal with expressions');
+ }
+
+ default:
+ throw new Error(`Cannot evaluate AST node: ${node.type}`);
+ }
+};
+
+export const readVisualControlValues = (
+ file: File,
+): VisualControlValueFromCode[] => {
+ const values: VisualControlValueFromCode[] = [];
+
+ recast.types.visit(file.program, {
+ visitCallExpression(path) {
+ const {node} = path;
+
+ if (
+ node.callee.type !== 'Identifier' ||
+ (node.callee as unknown as {name: string}).name !== 'visualControl'
+ ) {
+ return this.traverse(path);
+ }
+
+ const firstArg = node.arguments[0];
+ const id = getStringValue(
+ firstArg as ExpressionKind | recast.types.namedTypes.SpreadElement,
+ );
+ if (id === null) {
+ return this.traverse(path);
+ }
+
+ if (node.arguments.length < 2) {
+ return this.traverse(path);
+ }
+
+ const valueNode = node.arguments[1] as ExpressionKind;
+
+ try {
+ if (
+ valueNode.type === 'Identifier' &&
+ (valueNode as unknown as {name: string}).name === 'undefined'
+ ) {
+ values.push({id, value: null, isUndefined: true});
+ } else {
+ values.push({
+ id,
+ value: evaluateExpression(valueNode),
+ isUndefined: false,
+ });
+ }
+ } catch {
+ // Skip values we can't evaluate statically
+ }
+
+ return this.traverse(path);
+ },
+ });
+
+ return values;
+};
diff --git a/packages/studio-server/src/codemods/update-default-props.ts b/packages/studio-server/src/codemods/update-default-props.ts
index 616c4c1b18..ec856b74e8 100644
--- a/packages/studio-server/src/codemods/update-default-props.ts
+++ b/packages/studio-server/src/codemods/update-default-props.ts
@@ -1,6 +1,36 @@
import {stringifyDefaultProps, type EnumPath} from '@remotion/studio-shared';
import * as recast from 'recast';
-import {parseAst, serializeAst} from './parse-ast';
+import {formatInlineContent} from './format-inline-content';
+import {parseAst} from './parse-ast';
+
+// Recast uses tabWidth=4 for column counting, so columns don't
+// correspond to character indices when tabs are present.
+// This converts a recast loc (line/column) to a character offset.
+const RECAST_TAB_WIDTH = 4;
+
+const recastLocToOffset = (
+ input: string,
+ loc: {line: number; column: number},
+): number => {
+ const lines = input.split('\n');
+ let offset = 0;
+ for (let i = 0; i < loc.line - 1; i++) {
+ offset += lines[i].length + 1;
+ }
+
+ // Convert recast's tab-expanded column to character index
+ const line = lines[loc.line - 1];
+ let col = 0;
+ for (let i = 0; i < line.length; i++) {
+ if (col >= loc.column) {
+ return offset + i;
+ }
+
+ col += line[i] === '\t' ? RECAST_TAB_WIDTH : 1;
+ }
+
+ return offset + line.length;
+};
export const updateDefaultProps = async ({
input,
@@ -14,6 +44,13 @@ export const updateDefaultProps = async ({
enumPaths: EnumPath[];
}): Promise<{output: string; formatted: boolean}> => {
const ast = parseAst(input);
+ const stringified = stringifyDefaultProps({
+ props: newDefaultProps,
+ enumPaths,
+ });
+
+ let replaceStart: number | undefined;
+ let replaceEnd: number | undefined;
recast.types.visit(ast, {
visitJSXElement(path) {
@@ -113,44 +150,43 @@ export const updateDefaultProps = async ({
);
}
- defaultPropsAttr.value.expression = recast.types.builders.identifier(
- stringifyDefaultProps({props: newDefaultProps, enumPaths}),
- );
+ // Capture source positions for direct string replacement
+ // instead of modifying the AST and serializing (avoids recast artifacts)
+ const valueLoc = defaultPropsAttr.value.loc;
+ if (!valueLoc) {
+ throw new Error('Could not determine source location of defaultProps');
+ }
+
+ replaceStart = recastLocToOffset(input, valueLoc.start);
+ replaceEnd = recastLocToOffset(input, valueLoc.end);
this.traverse(path); // Continue traversing the AST
},
});
- const finalfile = serializeAst(ast);
-
- // 5: finally, format the file
- // eslint-disable-next-line @typescript-eslint/consistent-type-imports
- type PrettierType = typeof import('prettier');
- let prettier: PrettierType | null = null;
-
- try {
- prettier = await import('prettier');
- } catch {
- return {output: finalfile, formatted: false};
+ if (replaceStart === undefined || replaceEnd === undefined) {
+ throw new Error(
+ `Could not find defaultProps for composition "${compositionId}"`,
+ );
}
- const {format, resolveConfig, resolveConfigFile} = prettier as PrettierType;
-
- const configFilePath = await resolveConfigFile();
- if (!configFilePath) {
- return {output: finalfile, formatted: false};
- }
+ // linePrefix includes the JSX container opening brace
+ const lineStart = input.lastIndexOf('\n', replaceStart) + 1;
+ const linePrefix = input.substring(lineStart, replaceStart + 1);
- const prettierConfig = await resolveConfig(configFilePath);
- if (!prettierConfig) {
- return {output: finalfile, formatted: false};
- }
-
- const prettified = await format(finalfile, {
- ...prettierConfig,
- filepath: 'test.tsx',
- plugins: [],
+ const {formatted, didFormat} = await formatInlineContent({
+ inlineContent: stringified,
+ linePrefix,
endOfLine: 'auto',
});
- return {output: prettified, formatted: true};
+
+ // Replace the JSX expression container in the original input
+ const output =
+ input.substring(0, replaceStart) +
+ '{' +
+ formatted +
+ '}' +
+ input.substring(replaceEnd);
+
+ return {output, formatted: didFormat};
};
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.ts
index b8ad5fb513..cdc5d8ec10 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
@@ -11,6 +11,7 @@ import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {makeHyperlink} from '../../hyperlinks/make-link';
import type {ApiHandler} from '../api-types';
import {suppressHmrForFile} from '../hmr-suppression';
+import {waitForLiveEventsListener} from '../live-events';
import {
printUndoHint,
pushToUndoStack,
@@ -78,6 +79,19 @@ export const applyVisualControlHandler: ApiHandler<
suppressHmrForFile(absolutePath);
writeFileAndNotifyFileWatchers(absolutePath, output);
+ waitForLiveEventsListener().then((listener) => {
+ listener.sendEventToClient({
+ type: 'visual-control-values-changed',
+ values: changes.map((change) => ({
+ id: change.id,
+ value: change.newValueIsUndefined
+ ? null
+ : JSON.parse(change.newValueSerialized),
+ isUndefined: change.newValueIsUndefined,
+ })),
+ });
+ });
+
const locationLabel = `${fileRelativeToRoot}`;
const fileLink = makeHyperlink({
url: `file://${absolutePath}`,
diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.ts
index ceaa31f57e..1119f320ce 100644
--- a/packages/studio-server/src/preview-server/undo-stack.ts
+++ b/packages/studio-server/src/preview-server/undo-stack.ts
@@ -2,6 +2,8 @@ import {readFileSync} from 'node:fs';
import path from 'node:path';
import type {LogLevel} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
+import {parseAst} from '../codemods/parse-ast';
+import {readVisualControlValues} from '../codemods/read-visual-control-values';
import {
installFileWatcher,
writeFileAndNotifyFileWatchers,
@@ -198,6 +200,23 @@ function cleanupWatchers() {
}
}
+function emitVisualControlChanges(fileContents: string) {
+ try {
+ const ast = parseAst(fileContents);
+ const values = readVisualControlValues(ast);
+ if (values.length > 0) {
+ waitForLiveEventsListener().then((listener) => {
+ listener.sendEventToClient({
+ type: 'visual-control-values-changed',
+ values,
+ });
+ });
+ }
+ } catch {
+ // File might not contain visual controls or might not be parseable
+ }
+}
+
function logFileAction(action: string, filePath: string) {
const locationLabel = storedRemotionRoot
? path.relative(storedRemotionRoot, filePath)
@@ -239,6 +258,7 @@ export function popUndo(): {success: true} | {success: false; reason: string} {
);
logFileAction(entry.description.undoMessage, entry.filePath);
+ emitVisualControlChanges(entry.oldContents);
ensureWatching(entry.filePath);
broadcastState();
return {success: true};
@@ -270,6 +290,7 @@ export function popRedo(): {success: true} | {success: false; reason: string} {
);
logFileAction(entry.description.redoMessage, entry.filePath);
+ emitVisualControlChanges(entry.oldContents);
ensureWatching(entry.filePath);
broadcastState();
return {success: true};
diff --git a/packages/studio-shared/src/codemods.ts b/packages/studio-shared/src/codemods.ts
index 5ad3ecc1e2..17ce352b72 100644
--- a/packages/studio-shared/src/codemods.ts
+++ b/packages/studio-shared/src/codemods.ts
@@ -3,6 +3,7 @@ import type {EnumPath} from './stringify-default-props';
export type VisualControlChange = {
id: string;
newValueSerialized: string;
+ newValueIsUndefined: boolean;
enumPaths: EnumPath[];
};
diff --git a/packages/studio-shared/src/event-source-event.ts b/packages/studio-shared/src/event-source-event.ts
index 781b611e73..4b7afa6e5e 100644
--- a/packages/studio-shared/src/event-source-event.ts
+++ b/packages/studio-shared/src/event-source-event.ts
@@ -65,4 +65,12 @@ export type EventSourceEvent =
type: 'undo-redo-stack-changed';
undoFile: string | null;
redoFile: string | null;
+ }
+ | {
+ type: 'visual-control-values-changed';
+ values: Array<{
+ id: string;
+ value: unknown;
+ isUndefined: boolean;
+ }>;
};
diff --git a/packages/studio/src/components/EditorContexts.tsx b/packages/studio/src/components/EditorContexts.tsx
index 8d35a325b6..850d15f4ff 100644
--- a/packages/studio/src/components/EditorContexts.tsx
+++ b/packages/studio/src/components/EditorContexts.tsx
@@ -17,6 +17,7 @@ import {RenderQueueContextProvider} from './RenderQueue/context';
import {SetTimelineInOutProvider} from './SetTimelineInOutProvider';
import {ShowGuidesProvider} from './ShowGuidesProvider';
import {ShowRulersProvider} from './ShowRulersProvider';
+import {VisualControlsUndoSync} from './VisualControls/VisualControlsUndoSync';
import {ZoomGesturesProvider} from './ZoomGesturesProvider';
export const EditorContexts: React.FC<{
@@ -27,6 +28,7 @@ export const EditorContexts: React.FC<{
<ZodProvider>
<VisualControlsProvider>
<PreviewServerConnection readOnlyStudio={readOnlyStudio}>
+ <VisualControlsUndoSync />
<RenderQueueContextProvider>
<ClientRenderQueueProcessor />
<KeybindingContextProvider>
diff --git a/packages/studio/src/components/MenuBuildIndicator.tsx b/packages/studio/src/components/MenuBuildIndicator.tsx
index e3344cff09..d430ad8065 100644
--- a/packages/studio/src/components/MenuBuildIndicator.tsx
+++ b/packages/studio/src/components/MenuBuildIndicator.tsx
@@ -10,6 +10,7 @@ const cwd: React.CSSProperties = {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
+ userSelect: 'none',
};
const spinnerSize = 14;
diff --git a/packages/studio/src/components/RenderModal/SchemaEditor/ZodColorEditor.tsx b/packages/studio/src/components/RenderModal/SchemaEditor/ZodColorEditor.tsx
index 8d5a7f35cb..9c2f974f60 100644
--- a/packages/studio/src/components/RenderModal/SchemaEditor/ZodColorEditor.tsx
+++ b/packages/studio/src/components/RenderModal/SchemaEditor/ZodColorEditor.tsx
@@ -60,14 +60,8 @@ export const ZodColorEditor: React.FC<{
const onColorBlur: React.FocusEventHandler<HTMLInputElement> =
useCallback(() => {
- setValue(
- (v) => {
- // TODO: Does not yet work
- return v;
- },
- {shouldSave: true},
- );
- }, [setValue]);
+ setValue(() => value, {shouldSave: true});
+ }, [setValue, value]);
const onTextChange: React.ChangeEventHandler<HTMLInputElement> = useCallback(
(e) => {
@@ -79,8 +73,8 @@ export const ZodColorEditor: React.FC<{
const onTextBlur: React.FocusEventHandler<HTMLInputElement> =
useCallback(() => {
- setValue((v) => v, {shouldSave: true});
- }, [setValue]);
+ setValue(() => value, {shouldSave: true});
+ }, [setValue, value]);
const rgb = `#${r.toString(16).padStart(2, '0')}${g
.toString(16)
diff --git a/packages/studio/src/components/RenderModal/SchemaEditor/ZodStringEditor.tsx b/packages/studio/src/components/RenderModal/SchemaEditor/ZodStringEditor.tsx
index f9d381eee1..5cdcba0708 100644
--- a/packages/studio/src/components/RenderModal/SchemaEditor/ZodStringEditor.tsx
+++ b/packages/studio/src/components/RenderModal/SchemaEditor/ZodStringEditor.tsx
@@ -39,8 +39,8 @@ export const ZodStringEditor: React.FC<{
);
const onBlur: React.FocusEventHandler<HTMLInputElement> = useCallback(() => {
- setValue((v) => v, {shouldSave: true});
- }, [setValue]);
+ setValue(() => value, {shouldSave: true});
+ }, [setValue, value]);
return (
<Fieldset shouldPad={mayPad}>
diff --git a/packages/studio/src/components/RenderModal/SchemaEditor/ZodTextareaEditor.tsx b/packages/studio/src/components/RenderModal/SchemaEditor/ZodTextareaEditor.tsx
index c40c374bcc..670ac79b93 100644
--- a/packages/studio/src/components/RenderModal/SchemaEditor/ZodTextareaEditor.tsx
+++ b/packages/studio/src/components/RenderModal/SchemaEditor/ZodTextareaEditor.tsx
@@ -48,8 +48,8 @@ export const ZodTextareaEditor: React.FC<{
const onBlur: React.FocusEventHandler<HTMLTextAreaElement> =
useCallback(() => {
- setValue((v) => v, {shouldSave: true});
- }, [setValue]);
+ setValue(() => value, {shouldSave: true});
+ }, [setValue, value]);
const zodValidation = React.useMemo(
() => zodSafeParse(schema, value),
diff --git a/packages/studio/src/components/VisualControls/VisualControlHandle.tsx b/packages/studio/src/components/VisualControls/VisualControlHandle.tsx
index b641ef16e0..d43b37e1e8 100644
--- a/packages/studio/src/components/VisualControls/VisualControlHandle.tsx
+++ b/packages/studio/src/components/VisualControls/VisualControlHandle.tsx
@@ -75,11 +75,14 @@ export const VisualControlHandle: React.FC<{
{
id: keyName,
newValueSerialized:
- NoReactInternals.serializeJSONWithSpecialTypes({
- data: val as Record<string, unknown>,
- indent: 2,
- staticBase: window.remotion_staticBase,
- }).serializedString,
+ val === undefined
+ ? ''
+ : NoReactInternals.serializeJSONWithSpecialTypes({
+ data: val as Record<string, unknown>,
+ indent: 2,
+ staticBase: window.remotion_staticBase,
+ }).serializedString,
+ newValueIsUndefined: val === undefined,
enumPaths,
},
],
diff --git a/packages/studio/src/components/VisualControls/VisualControlsUndoSync.tsx b/packages/studio/src/components/VisualControls/VisualControlsUndoSync.tsx
new file mode 100644
index 0000000000..d582ac772b
--- /dev/null
+++ b/packages/studio/src/components/VisualControls/VisualControlsUndoSync.tsx
@@ -0,0 +1,29 @@
+import type {EventSourceEvent} from '@remotion/studio-shared';
+import type React from 'react';
+import {useContext, useEffect} from 'react';
+import {StudioServerConnectionCtx} from '../../helpers/client-id';
+import {SetVisualControlsContext} from '../../visual-controls/VisualControls';
+
+export const VisualControlsUndoSync: React.FC = () => {
+ const {subscribeToEvent} = useContext(StudioServerConnectionCtx);
+ const {updateValue} = useContext(SetVisualControlsContext);
+
+ useEffect(() => {
+ const unsub = subscribeToEvent(
+ 'visual-control-values-changed',
+ (event: EventSourceEvent) => {
+ if (event.type !== 'visual-control-values-changed') {
+ return;
+ }
+
+ for (const entry of event.values) {
+ updateValue(entry.id, entry.isUndefined ? undefined : entry.value);
+ }
+ },
+ );
+
+ return () => unsub();
+ }, [subscribeToEvent, updateValue]);
+
+ return null;
+};
diff --git a/packages/studio/src/visual-controls/VisualControls.tsx b/packages/studio/src/visual-controls/VisualControls.tsx
index f693618035..bde4031ca5 100644
--- a/packages/studio/src/visual-controls/VisualControls.tsx
+++ b/packages/studio/src/visual-controls/VisualControls.tsx
@@ -83,18 +83,21 @@ export const VisualControlsProvider: React.FC<{
const setControl = useCallback(
(key: string, value: VisualControlValueWithoutUnsaved) => {
- const currentUnsaved = imperativeHandles.current?.[key]?.unsavedValue;
- const currentSavedState = imperativeHandles.current?.[key]?.valueInCode;
+ const existingHandle = imperativeHandles.current?.[key];
+ const currentSavedState = existingHandle?.valueInCode;
const changedSavedValue = value.valueInCode !== currentSavedState;
const changedUnsavedValue =
- currentUnsaved === undefined && value.valueInCode !== undefined;
+ existingHandle === undefined && value.valueInCode !== undefined;
imperativeHandles.current = {
...imperativeHandles.current,
[key]: {
...value,
- unsavedValue: currentUnsaved ?? value.valueInCode,
+ unsavedValue:
+ existingHandle !== undefined
+ ? existingHandle.unsavedValue
+ : value.valueInCode,
valueInCode: value.valueInCode,
},
};
diff --git a/packages/studio/src/visual-controls/get-current-edited-value.ts b/packages/studio/src/visual-controls/get-current-edited-value.ts
index ca0e0f50e0..c99de73ddc 100644
--- a/packages/studio/src/visual-controls/get-current-edited-value.ts
+++ b/packages/studio/src/visual-controls/get-current-edited-value.ts
@@ -7,6 +7,10 @@ export const getVisualControlEditedValue = ({
handles: Handles;
key: string;
}): unknown => {
- // TODO: What if z.null()
- return handles?.[key]?.unsavedValue ?? null;
+ const handle = handles?.[key];
+ if (handle === undefined) {
+ return null;
+ }
+
+ return handle.unsavedValue;
};