🎥 Make videos programmatically with React
`@remotion/studio-server`: Support `staticFile()` and `new Date()` in defaultProps extraction (#8286)
Jonny Burgeraafa9e11023b
diff --git a/packages/docs/docs/troubleshooting/cannot-save-default-props.mdx b/packages/docs/docs/troubleshooting/cannot-save-default-props.mdxindex 93429b1cc2..d4a6cf9d51 100644--- a/packages/docs/docs/troubleshooting/cannot-save-default-props.mdx+++ b/packages/docs/docs/troubleshooting/cannot-save-default-props.mdx@@ -55,6 +55,8 @@ export const RemotionRoot = () => {};```+Inside the object literal, [`staticFile()`](/docs/staticfile) calls and `new Date()` values with a string literal argument are also supported<AvailableFrom v="4.0.475" />.+Avoid values that are not written in the required JSX shape:```tsx title="Root.tsx"diff --git a/packages/studio-server/src/preview-server/routes/can-update-default-props.ts b/packages/studio-server/src/preview-server/routes/can-update-default-props.tsindex f7b5b24a0f..9ed0084e28 100644--- a/packages/studio-server/src/preview-server/routes/can-update-default-props.ts+++ b/packages/studio-server/src/preview-server/routes/can-update-default-props.ts@@ -97,8 +97,14 @@ const extractDefaultPropsFromSource = (return;}- if (isStaticValue(expression as unknown as Expression)) {- const value = extractStaticValue(expression as unknown as Expression);+ if (+ isStaticValue(expression as unknown as Expression, {+ allowSpecialValues: true,+ })+ ) {+ const value = extractStaticValue(expression as unknown as Expression, {+ allowSpecialValues: true,+ });if (value !== null &&typeof value === 'object' &&diff --git a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.tsindex 52c3b4f6f4..e699fa17d1 100644--- a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts+++ b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts@@ -5,6 +5,7 @@ import type {File,JSXAttribute,JSXOpeningElement,+ NewExpression,ObjectExpression,ObjectProperty,TSAsExpression,@@ -21,6 +22,7 @@ import type {LogLevel,SequenceNodePath,} from 'remotion';+import {NoReactInternals} from 'remotion/no-react';import {parseAst} from '../../codemods/parse-ast';import {getAstNodePath} from '../../helpers/get-ast-node-path';import {toImportAgnosticNodePath} from '../../helpers/import-agnostic-node-path';@@ -45,7 +47,65 @@ const computedStatus = (): CanUpdatePropStatus => ({status: 'computed',});-export const isStaticValue = (node: Expression): boolean => {+// Mirrors the encoding that staticFile() from "remotion" applies at runtime+const encodeStaticFilePath = (path: string): string => {+ return path.split('/').map(encodeURIComponent).join('/');+};++type SpecialValueCall =+ | {type: 'static-file'; value: string}+ | {type: 'date'; value: string};++// Detects calls that the Studio knows how to serialize back to source:+// staticFile("...") and new Date("...")+const getSpecialValueCall = (node: Expression): SpecialValueCall | null => {+ if (node.type === 'CallExpression') {+ const call = node as CallExpression;+ if (+ call.callee.type === 'Identifier' &&+ call.callee.name === 'staticFile' &&+ call.arguments.length === 1 &&+ call.arguments[0].type === 'StringLiteral'+ ) {+ return {type: 'static-file', value: call.arguments[0].value};+ }++ return null;+ }++ if (node.type === 'NewExpression') {+ const newExpr = node as NewExpression;+ if (+ newExpr.callee.type === 'Identifier' &&+ newExpr.callee.name === 'Date' &&+ newExpr.arguments.length === 1 &&+ newExpr.arguments[0].type === 'StringLiteral'+ ) {+ return {type: 'date', value: newExpr.arguments[0].value};+ }++ return null;+ }++ return null;+};++type StaticValueOptions = {+ allowSpecialValues: boolean;+};++const defaultStaticValueOptions: StaticValueOptions = {+ allowSpecialValues: false,+};++export const isStaticValue = (+ node: Expression,+ options: StaticValueOptions = defaultStaticValueOptions,+): boolean => {+ if (options.allowSpecialValues && getSpecialValueCall(node) !== null) {+ return true;+ }+switch (node.type) {case 'NumericLiteral':case 'StringLiteral':@@ -59,25 +119,45 @@ export const isStaticValue = (node: Expression): boolean => {(node as UnaryExpression).argument.type === 'NumericLiteral');case 'TSAsExpression':- return isStaticValue((node as TSAsExpression).expression as Expression);+ return isStaticValue(+ (node as TSAsExpression).expression as Expression,+ options,+ );case 'ArrayExpression':return (node as Extract<Expression, {type: 'ArrayExpression'}>).elements.every(- (el) => el !== null && el.type !== 'SpreadElement' && isStaticValue(el),+ (el) =>+ el !== null &&+ el.type !== 'SpreadElement' &&+ isStaticValue(el, options),);case 'ObjectExpression':return (node as ObjectExpression).properties.every((prop) =>prop.type === 'ObjectProperty' &&- isStaticValue((prop as ObjectProperty).value as Expression),+ isStaticValue((prop as ObjectProperty).value as Expression, options),);default:return false;}};-export const extractStaticValue = (node: Expression): unknown => {+export const extractStaticValue = (+ node: Expression,+ options: StaticValueOptions = defaultStaticValueOptions,+): unknown => {+ if (options.allowSpecialValues) {+ const specialValue = getSpecialValueCall(node);+ if (specialValue !== null) {+ if (specialValue.type === 'static-file') {+ return `${NoReactInternals.FILE_TOKEN}${encodeStaticFilePath(specialValue.value)}`;+ }++ return `${NoReactInternals.DATE_TOKEN}${specialValue.value}`;+ }+ }+switch (node.type) {case 'NumericLiteral':case 'StringLiteral':@@ -98,6 +178,7 @@ export const extractStaticValue = (node: Expression): unknown => {case 'TSAsExpression':return extractStaticValue((node as TSAsExpression).expression as Expression,+ options,);case 'ArrayExpression':return (@@ -107,7 +188,7 @@ export const extractStaticValue = (node: Expression): unknown => {return undefined;}- return extractStaticValue(el);+ return extractStaticValue(el, options);});case 'ObjectExpression': {const obj = node as ObjectExpression;@@ -123,7 +204,7 @@ export const extractStaticValue = (node: Expression): unknown => {? String((p.key as {value: unknown}).value): undefined;if (key !== undefined) {- result[key] = extractStaticValue(p.value as Expression);+ result[key] = extractStaticValue(p.value as Expression, options);}}}diff --git a/packages/studio-server/src/test/extract-default-props.test.ts b/packages/studio-server/src/test/extract-default-props.test.tsindex 994fea5893..56cd927ff1 100644--- a/packages/studio-server/src/test/extract-default-props.test.ts+++ b/packages/studio-server/src/test/extract-default-props.test.ts@@ -1,4 +1,6 @@import {expect, test} from 'bun:test';+import {NoReactInternals} from 'remotion/no-react';+import {computeCanUpdateDefaultPropsFromContent} from '../preview-server/routes/can-update-default-props';import {extractStaticValue,isStaticValue,@@ -75,3 +77,123 @@ test('Nested TSAsExpression inside complex defaultProps should work', () => {tuple: ['foo', 42, {a: 'hi'}],});});++test('staticFile() should not be static by default', () => {+ expect(isStaticValue(parseExpression("staticFile('dialogue.wav')"))).toBe(+ false,+ );+});++test('staticFile() should be static when special values are allowed', () => {+ expect(+ isStaticValue(parseExpression("staticFile('dialogue.wav')"), {+ allowSpecialValues: true,+ }),+ ).toBe(true);+ expect(+ extractStaticValue(parseExpression("staticFile('dialogue.wav')"), {+ allowSpecialValues: true,+ }),+ ).toBe(`${NoReactInternals.FILE_TOKEN}dialogue.wav`);+});++test('staticFile() with special characters should be encoded like staticFile() at runtime', () => {+ expect(+ extractStaticValue(+ parseExpression("staticFile('my folder/voice #1.wav')"),+ {+ allowSpecialValues: true,+ },+ ),+ ).toBe(`${NoReactInternals.FILE_TOKEN}my%20folder/voice%20%231.wav`);+});++test('staticFile() with non-literal argument should not be static', () => {+ expect(+ isStaticValue(parseExpression('staticFile(myVariable)'), {+ allowSpecialValues: true,+ }),+ ).toBe(false);+});++test('new Date() should be static when special values are allowed', () => {+ expect(+ isStaticValue(parseExpression("new Date('2024-01-01T00:00:00.000Z')"), {+ allowSpecialValues: true,+ }),+ ).toBe(true);+ expect(+ extractStaticValue(+ parseExpression("new Date('2024-01-01T00:00:00.000Z')"),+ {+ allowSpecialValues: true,+ },+ ),+ ).toBe(`${NoReactInternals.DATE_TOKEN}2024-01-01T00:00:00.000Z`);+});++test('Objects containing staticFile() should be extracted', () => {+ const code = `{+audioFileUrl: staticFile("dialogue.wav"),+titleText: "Ep 550",+numberOfSamples: "64" as const,+}`;+ expect(isStaticValue(parseExpression(code), {allowSpecialValues: true})).toBe(+ true,+ );+ expect(+ extractStaticValue(parseExpression(code), {allowSpecialValues: true}),+ ).toEqual({+ audioFileUrl: `${NoReactInternals.FILE_TOKEN}dialogue.wav`,+ titleText: 'Ep 550',+ numberOfSamples: '64',+ });+});++test('Audiogram-like root file should be extractable', () => {+ const content = `+import { Composition, staticFile } from "remotion";+import { Audiogram } from "./Audiogram/Main";++export const RemotionRoot: React.FC = () => {+ return (+ <Composition+ id="Audiogram"+ component={Audiogram}+ width={1080}+ height={1080}+ defaultProps={{+ audioOffsetInSeconds: 0,+ audioFileUrl: staticFile("dialogue.wav"),+ coverImageUrl: staticFile("podcast-cover.jpeg"),+ titleText: "Ep 550 - Supper Club × Remotion React",+ captions: null,+ onlyDisplayCurrentSentence: true,+ visualizer: {+ type: "oscilloscope",+ numberOfSamples: "64" as const,+ windowInSeconds: 0.1,+ },+ }}+ />+ );+};+`;+ const result = computeCanUpdateDefaultPropsFromContent(content, 'Audiogram');+ expect(result).toEqual({+ canUpdate: true,+ currentDefaultProps: {+ audioOffsetInSeconds: 0,+ audioFileUrl: `${NoReactInternals.FILE_TOKEN}dialogue.wav`,+ coverImageUrl: `${NoReactInternals.FILE_TOKEN}podcast-cover.jpeg`,+ titleText: 'Ep 550 - Supper Club × Remotion React',+ captions: null,+ onlyDisplayCurrentSentence: true,+ visualizer: {+ type: 'oscilloscope',+ numberOfSamples: '64',+ windowInSeconds: 0.1,+ },+ },+ });+});diff --git a/packages/studio/src/components/ObserveDefaultPropsContext.tsx b/packages/studio/src/components/ObserveDefaultPropsContext.tsxindex d5e520b542..8440e7b9ca 100644--- a/packages/studio/src/components/ObserveDefaultPropsContext.tsx+++ b/packages/studio/src/components/ObserveDefaultPropsContext.tsx@@ -6,6 +6,7 @@ import React, {useState,} from 'react';import {Internals} from 'remotion';+import {NoReactInternals} from 'remotion/no-react';import {StudioServerConnectionCtx} from '../helpers/client-id';import {callApi} from './call-api';import type {TypeCanSaveState} from './RenderModal/get-render-modal-warnings';@@ -59,10 +60,15 @@ export const ObserveDefaultProps: React.FC<{...prevState,[compId]: {canUpdate: true},}));+ // Resolve `remotion-file:` and `remotion-date:` tokens that the+ // server emits for staticFile() and new Date() values+ const deserialized = NoReactInternals.deserializeJSONWithSpecialTypes<+ Record<string, unknown>+ >(JSON.stringify(result.currentDefaultProps));updateProps({id: compId,- defaultProps: result.currentDefaultProps,- newProps: result.currentDefaultProps,+ defaultProps: deserialized,+ newProps: deserialized,});} else {setCanSaveDefaultProps((prevState) => ({diff --git a/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsx b/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsxindex f9c45c2b2f..00cabca4e8 100644--- a/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsx+++ b/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsx@@ -98,7 +98,10 @@ export const RenderModalJSONPropsEditor: React.FC<{const {result} = e;if (result.canUpdate) {- const nextState = parseJS(result.currentDefaultProps, schema);+ const deserialized = NoReactInternals.deserializeJSONWithSpecialTypes<+ Record<string, unknown>+ >(JSON.stringify(result.currentDefaultProps));+ const nextState = parseJS(deserialized, schema);setLocalValue(nextState);}});