🎥 Make videos programmatically with React
move things around
Jonny Burger310ea4c74d54
diff --git a/packages/studio-server/src/codemods/update-sequence-props.ts b/packages/studio-server/src/codemods/update-sequence-props.tsindex b0c3c97b1c..2e51fe3fb9 100644--- a/packages/studio-server/src/codemods/update-sequence-props.ts+++ b/packages/studio-server/src/codemods/update-sequence-props.ts@@ -15,37 +15,29 @@ import {parseValueExpression, updateNestedProp} from './update-nested-prop';const b = recast.types.builders;+export type SequencePropUpdate = {+ key: string;+ value: unknown;+ defaultValue: unknown | null;+};+export const updateSequenceProps = async ({input,nodePath,- key,- value,- defaultValue,+ updates,prettierConfigOverride,}: {input: string;nodePath: SequenceNodePath;- key: string;- value: unknown;- defaultValue: unknown | null;+ updates: SequencePropUpdate[];prettierConfigOverride?: Record<string, unknown> | null;}): Promise<{output: string;- oldValueString: string;+ oldValueStrings: string[];formatted: boolean;logLine: number;}> => {const ast = parseAst(input);- let oldValueString = '';-- const isDefault =- defaultValue !== null &&- JSON.stringify(value) === JSON.stringify(defaultValue);-- const dotIndex = key.indexOf('.');- const isNested = dotIndex !== -1;- const parentKey = isNested ? key.slice(0, dotIndex) : key;- const childKey = isNested ? key.slice(dotIndex + 1) : '';const node = findJsxElementAtNodePath(ast, nodePath);if (!node) {@@ -56,74 +48,92 @@ export const updateSequenceProps = async ({const logLine = node.loc?.start.line ?? 1;- if (isNested) {- oldValueString = updateNestedProp({- node,- parentKey,- childKey,- value,- defaultValue,- isDefault,- });- } else {- const attrIndex = node.attributes?.findIndex((a) => {- if (a.type === 'JSXSpreadAttribute') {- return false;- }-- if (a.name.type === 'JSXNamespacedName') {- return false;- }-- return a.name.name === key;- });-- const attr =- attrIndex !== undefined && attrIndex !== -1- ? node.attributes?.[attrIndex]- : undefined;-- if (attr && attr.type !== 'JSXSpreadAttribute' && attr.value) {- const printed = recast.print(attr.value).code;- // Strip JSX expression container braces, e.g. "{30}" -> "30"- oldValueString =- printed.startsWith('{') && printed.endsWith('}')- ? printed.slice(1, -1)- : printed;- } else if (attr && attr.type !== 'JSXSpreadAttribute' && !attr.value) {- // JSX shorthand like `loop` (no value) is implicitly `true`- oldValueString = 'true';- } else if (!attr && defaultValue !== null) {- oldValueString = JSON.stringify(defaultValue);- }-- if (isDefault) {- if (attr && attr.type !== 'JSXSpreadAttribute' && node.attributes) {- node.attributes.splice(attrIndex!, 1);- }+ const oldValueStrings: string[] = [];++ for (const {key, value, defaultValue} of updates) {+ let oldValueString = '';++ const isDefault =+ defaultValue !== null &&+ JSON.stringify(value) === JSON.stringify(defaultValue);++ const dotIndex = key.indexOf('.');+ const isNested = dotIndex !== -1;+ const parentKey = isNested ? key.slice(0, dotIndex) : key;+ const childKey = isNested ? key.slice(dotIndex + 1) : '';++ if (isNested) {+ oldValueString = updateNestedProp({+ node,+ parentKey,+ childKey,+ value,+ defaultValue,+ isDefault,+ });} else {- const parsed = parseValueExpression(value);+ const attrIndex = node.attributes?.findIndex((a) => {+ if (a.type === 'JSXSpreadAttribute') {+ return false;+ }- const newValue = value === true ? null : b.jsxExpressionContainer(parsed);+ if (a.name.type === 'JSXNamespacedName') {+ return false;+ }- if (!attr || attr.type === 'JSXSpreadAttribute') {- const newAttr = b.jsxAttribute(b.jsxIdentifier(key), newValue);+ return a.name.name === key;+ });++ const attr =+ attrIndex !== undefined && attrIndex !== -1+ ? node.attributes?.[attrIndex]+ : undefined;++ if (attr && attr.type !== 'JSXSpreadAttribute' && attr.value) {+ const printed = recast.print(attr.value).code;+ // Strip JSX expression container braces, e.g. "{30}" -> "30"+ oldValueString =+ printed.startsWith('{') && printed.endsWith('}')+ ? printed.slice(1, -1)+ : printed;+ } else if (attr && attr.type !== 'JSXSpreadAttribute' && !attr.value) {+ // JSX shorthand like `loop` (no value) is implicitly `true`+ oldValueString = 'true';+ } else if (!attr && defaultValue !== null) {+ oldValueString = JSON.stringify(defaultValue);+ }- if (!node.attributes) {- node.attributes = [];+ if (isDefault) {+ if (attr && attr.type !== 'JSXSpreadAttribute' && node.attributes) {+ node.attributes.splice(attrIndex!, 1);}-- node.attributes.push(newAttr as JSXAttribute | JSXSpreadAttribute);} else {- attr.value = newValue as- | JSXElement- | JSXExpressionContainer- | JSXFragment- | StringLiteral- | null- | undefined;+ const parsed = parseValueExpression(value);++ const newValue =+ value === true ? null : b.jsxExpressionContainer(parsed);++ if (!attr || attr.type === 'JSXSpreadAttribute') {+ const newAttr = b.jsxAttribute(b.jsxIdentifier(key), newValue);++ if (!node.attributes) {+ node.attributes = [];+ }++ node.attributes.push(newAttr as JSXAttribute | JSXSpreadAttribute);+ } else {+ attr.value = newValue as+ | JSXElement+ | JSXExpressionContainer+ | JSXFragment+ | StringLiteral+ | null+ | undefined;+ }}}++ oldValueStrings.push(oldValueString);}const finalFile = serializeAst(ast);@@ -134,7 +144,7 @@ export const updateSequenceProps = async ({return {output,- oldValueString,+ oldValueStrings,formatted,logLine,};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 2a6425f70c..1f2c9a6b91 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@@ -38,14 +38,20 @@ export const saveSequencePropsHandler: ApiHandler<const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, oldValueString, formatted, logLine} =+ const {output, oldValueStrings, formatted, logLine} =await updateSequenceProps({input: fileContents,nodePath,- key,- value: JSON.parse(value),- defaultValue: defaultValue !== null ? JSON.parse(defaultValue) : null,+ updates: [+ {+ key,+ value: JSON.parse(value),+ defaultValue:+ defaultValue !== null ? JSON.parse(defaultValue) : null,+ },+ ],});+ const oldValueString = oldValueStrings[0];const newValueString = JSON.stringify(JSON.parse(value));const parsedDefault =diff --git a/packages/studio-server/src/preview-server/sequence-props-watchers.ts b/packages/studio-server/src/preview-server/sequence-props-watchers.tsindex c0c46ae592..09379f0f97 100644--- a/packages/studio-server/src/preview-server/sequence-props-watchers.ts+++ b/packages/studio-server/src/preview-server/sequence-props-watchers.ts@@ -29,23 +29,19 @@ const makeWatcherKey = ({return `${absolutePath}:${JSON.stringify(nodePath)}`;};-export const subscribeToSequencePropsWatchers = ({+const getInitialResult = ({fileName,line,column,keys,remotionRoot,- clientId,}: {fileName: string;line: number;column: number;keys: string[];remotionRoot: string;- clientId: string;}): CanUpdateSequencePropsResponse => {- const absolutePath = path.resolve(remotionRoot, fileName);-// Try cached nodePath first (handles stale source maps after suppressed rebuilds)const cachedNodePath = getCachedNodePath(fileName, line, column);let initialResult: CanUpdateSequencePropsResponse;@@ -77,10 +73,38 @@ export const subscribeToSequencePropsWatchers = ({});}+ return initialResult;+};++export const subscribeToSequencePropsWatchers = ({+ fileName,+ line,+ column,+ keys,+ remotionRoot,+ clientId,+}: {+ fileName: string;+ line: number;+ column: number;+ keys: string[];+ remotionRoot: string;+ clientId: string;+}): CanUpdateSequencePropsResponse => {+ const initialResult = getInitialResult({+ fileName,+ line,+ column,+ keys,+ remotionRoot,+ });+if (!initialResult.canUpdate) {return initialResult;}+ const absolutePath = path.resolve(remotionRoot, fileName);+// Cache the resolved nodePath for future lookups with stale source mapssetCachedNodePath(fileName, line, column, initialResult.nodePath);diff --git a/packages/studio-server/src/test/code-shift.test.ts b/packages/studio-server/src/test/code-shift.test.tsindex 210caae94a..c8ae0b7df1 100644--- a/packages/studio-server/src/test/code-shift.test.ts+++ b/packages/studio-server/src/test/code-shift.test.ts@@ -12,18 +12,17 @@ export const Component = () => {`;test('Should add style.scale to a Video component and format with prettier', async () => {- const {output, oldValueString, formatted} = await updateSequenceProps({+ const {output, oldValueStrings, formatted} = await updateSequenceProps({input: componentInput,nodePath: lineColumnToNodePath(componentInput, 6),- key: 'style.scale',- value: 2,- defaultValue: null,+ updates: [{key: 'style.scale', value: 2, defaultValue: null}],prettierConfigOverride: {singleQuote: true,bracketSpacing: false,useTabs: true,},});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('');expect(formatted).toBe(true);diff --git a/packages/studio-server/src/test/discriminated-union-update.test.ts b/packages/studio-server/src/test/discriminated-union-update.test.tsindex 2d5bd24cf5..ab4193d191 100644--- a/packages/studio-server/src/test/discriminated-union-update.test.ts+++ b/packages/studio-server/src/test/discriminated-union-update.test.ts@@ -37,9 +37,13 @@ test('Should be able to update a discriminated union', async () => {const update = await updateSequenceProps({input: file,nodePath,- key: 'layout',- value: 'none',- defaultValue: field.fieldSchema.default,+ updates: [+ {+ key: 'layout',+ value: 'none',+ defaultValue: field.fieldSchema.default,+ },+ ],});const expected = readFileSync(diff --git a/packages/studio-server/src/test/update-nested-sequence-props.test.ts b/packages/studio-server/src/test/update-nested-sequence-props.test.tsindex 30f092990c..541358e2a0 100644--- a/packages/studio-server/src/test/update-nested-sequence-props.test.ts+++ b/packages/studio-server/src/test/update-nested-sequence-props.test.ts@@ -16,13 +16,12 @@ export const Example: React.FC = () => {`;test('updateSequenceProps should update a nested style property', async () => {- const {output, oldValueString} = await updateSequenceProps({+ const {output, oldValueStrings} = await updateSequenceProps({input: nestedInput,nodePath: lineColumnToNodePath(nestedInput, 7),- key: 'style.opacity',- value: 0.8,- defaultValue: null,+ updates: [{key: 'style.opacity', value: 0.8, defaultValue: null}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('0.5');expect(output).toContain('opacity: 0.8');@@ -30,13 +29,12 @@ test('updateSequenceProps should update a nested style property', async () => {});test('updateSequenceProps should add a nested property to existing object', async () => {- const {output, oldValueString} = await updateSequenceProps({+ const {output, oldValueStrings} = await updateSequenceProps({input: nestedInput,nodePath: lineColumnToNodePath(nestedInput, 7),- key: 'style.rotate',- value: 45,- defaultValue: null,+ updates: [{key: 'style.rotate', value: 45, defaultValue: null}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('');expect(output).toContain('rotate: 45');@@ -46,13 +44,12 @@ test('updateSequenceProps should add a nested property to existing object', asyn});test('updateSequenceProps should create style attribute when it does not exist', async () => {- const {output, oldValueString} = await updateSequenceProps({+ const {output, oldValueStrings} = await updateSequenceProps({input: nestedInput,nodePath: lineColumnToNodePath(nestedInput, 8),- key: 'style.opacity',- value: 0.3,- defaultValue: null,+ updates: [{key: 'style.opacity', value: 0.3, defaultValue: null}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('');expect(output).toContain('style={{');@@ -60,13 +57,12 @@ test('updateSequenceProps should create style attribute when it does not exist',});test('updateSequenceProps should remove nested property when value equals default', async () => {- const {output, oldValueString} = await updateSequenceProps({+ const {output, oldValueStrings} = await updateSequenceProps({input: nestedInput,nodePath: lineColumnToNodePath(nestedInput, 7),- key: 'style.opacity',- value: 1,- defaultValue: 1,+ updates: [{key: 'style.opacity', value: 1, defaultValue: 1}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('0.5');expect(output).not.toContain('opacity');@@ -83,26 +79,24 @@ export const Example: React.FC = () => {};`;- const {output, oldValueString} = await updateSequenceProps({+ const {output, oldValueStrings} = await updateSequenceProps({input: singlePropInput,nodePath: lineColumnToNodePath(singlePropInput, 4),- key: 'style.opacity',- value: 1,- defaultValue: 1,+ updates: [{key: 'style.opacity', value: 1, defaultValue: 1}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('0.5');expect(output).not.toContain('style');});test('updateSequenceProps should report default as oldValueString for missing nested property', async () => {- const {oldValueString} = await updateSequenceProps({+ const {oldValueStrings} = await updateSequenceProps({input: nestedInput,nodePath: lineColumnToNodePath(nestedInput, 8),- key: 'style.opacity',- value: 0.5,- defaultValue: 1,+ updates: [{key: 'style.opacity', value: 0.5, defaultValue: 1}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('1');});diff --git a/packages/studio-server/src/test/update-sequence-props.test.ts b/packages/studio-server/src/test/update-sequence-props.test.tsindex 869772526e..42c6b0fdff 100644--- a/packages/studio-server/src/test/update-sequence-props.test.ts+++ b/packages/studio-server/src/test/update-sequence-props.test.ts@@ -17,13 +17,12 @@ export const LightLeakExample: React.FC = () => {`;test('updateSequenceProps should update a number value', async () => {- const {output, oldValueString} = await updateSequenceProps({+ const {output, oldValueStrings} = await updateSequenceProps({input: lightLeakInput,nodePath: lineColumnToNodePath(lightLeakInput, 8),- key: 'hueShift',- value: 90,- defaultValue: null,+ updates: [{key: 'hueShift', value: 90, defaultValue: null}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('30');expect(output).toContain('hueShift={90}');@@ -32,13 +31,12 @@ test('updateSequenceProps should update a number value', async () => {});test('updateSequenceProps should update durationInFrames', async () => {- const {output, oldValueString} = await updateSequenceProps({+ const {output, oldValueStrings} = await updateSequenceProps({input: lightLeakInput,nodePath: lineColumnToNodePath(lightLeakInput, 9),- key: 'durationInFrames',- value: 120,- defaultValue: null,+ updates: [{key: 'durationInFrames', value: 120, defaultValue: null}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('60');expect(output.split('\n')[8]).toContain('durationInFrames={120}');@@ -47,26 +45,24 @@ test('updateSequenceProps should update durationInFrames', async () => {});test('updateSequenceProps should add a new attribute', async () => {- const {output, oldValueString} = await updateSequenceProps({+ const {output, oldValueStrings} = await updateSequenceProps({input: lightLeakInput,nodePath: lineColumnToNodePath(lightLeakInput, 9),- key: 'speed',- value: 2,- defaultValue: null,+ updates: [{key: 'speed', value: 2, defaultValue: null}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('');expect(output.split('\n')[8]).toContain('speed={2}');});test('updateSequenceProps should remove attribute when value equals default', async () => {- const {output, oldValueString} = await updateSequenceProps({+ const {output, oldValueStrings} = await updateSequenceProps({input: lightLeakInput,nodePath: lineColumnToNodePath(lightLeakInput, 9),- key: 'hueShift',- value: 0,- defaultValue: 0,+ updates: [{key: 'hueShift', value: 0, defaultValue: 0}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('30');expect(output.split('\n')[8]).not.toContain('hueShift');@@ -78,9 +74,7 @@ test('updateSequenceProps should set boolean true as shorthand', async () => {const {output} = await updateSequenceProps({input: lightLeakInput,nodePath: lineColumnToNodePath(lightLeakInput, 8),- key: 'loop',- value: true,- defaultValue: false,+ updates: [{key: 'loop', value: true, defaultValue: false}],});// true booleans become shorthand: `loop` not `loop={true}`@@ -89,25 +83,23 @@ test('updateSequenceProps should set boolean true as shorthand', async () => {});test('updateSequenceProps should report oldValueString for computed expressions', async () => {- const {oldValueString} = await updateSequenceProps({+ const {oldValueStrings} = await updateSequenceProps({input: lightLeakInput,nodePath: lineColumnToNodePath(lightLeakInput, 8),- key: 'seed',- value: 5,- defaultValue: null,+ updates: [{key: 'seed', value: 5, defaultValue: null}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('1 + 2');});test('updateSequenceProps should report default as oldValueString for missing attribute', async () => {- const {oldValueString} = await updateSequenceProps({+ const {oldValueStrings} = await updateSequenceProps({input: lightLeakInput,nodePath: lineColumnToNodePath(lightLeakInput, 8),- key: 'speed',- value: 2,- defaultValue: 1,+ updates: [{key: 'speed', value: 2, defaultValue: 1}],});+ const oldValueString = oldValueStrings[0];expect(oldValueString).toBe('1');});@@ -117,9 +109,7 @@ test('updateSequenceProps should throw for non-existent nodePath', async () => {updateSequenceProps({input: lightLeakInput,nodePath: ['program', 'body', 999],- key: 'hueShift',- value: 90,- defaultValue: null,+ updates: [{key: 'hueShift', value: 90, defaultValue: null}],}),).rejects.toThrow('Could not find a JSX element at the specified line to update',diff --git a/packages/studio-server/tsconfig.json b/packages/studio-server/tsconfig.jsonindex 8348716ea1..4d86dc110f 100644--- a/packages/studio-server/tsconfig.json+++ b/packages/studio-server/tsconfig.json@@ -7,6 +7,7 @@"skipLibCheck": true},"include": ["src"],+ "exclude": ["src/test/snapshots"],"references": [{"path": "../bundler"