Skip to content

🎥 Make videos programmatically with React

serialize once

Jonny Burgera9769159cdf9
diff --git a/packages/core/src/ResolveCompositionConfig.tsx b/packages/core/src/ResolveCompositionConfig.tsx
index 15ae0cae23..60b5fe062c 100644
--- a/packages/core/src/ResolveCompositionConfig.tsx
+++ b/packages/core/src/ResolveCompositionConfig.tsx
@@ -18,7 +18,7 @@ import {getInputProps} from './config/input-props.js';
import {getRemotionEnvironment} from './get-remotion-environment.js';
import {NonceContext} from './nonce.js';
import type {InferProps} from './props-if-has-props.js';
-import {resolveVideoConfig} from './resolve-video-config.js';
+import {resolveVideoConfigOrCatch} from './resolve-video-config.js';
import {validateDimension} from './validation/validate-dimensions.js';
import {validateDurationInFrames} from './validation/validate-duration-in-frames.js';
import {validateFps} from './validation/validate-fps.js';
@@ -137,7 +137,7 @@ export const ResolveCompositionConfig: React.FC<
const {signal} = controller;
- const promOrNot = resolveVideoConfig({
+ const result = resolveVideoConfigOrCatch({
compositionId,
calculateMetadata,
originalProps: combinedProps,
@@ -148,6 +148,19 @@ export const ResolveCompositionConfig: React.FC<
compositionHeight,
compositionWidth,
});
+ if (result.type === 'error') {
+ setResolvedConfigs((r) => ({
+ ...r,
+ [compositionId]: {
+ type: 'error',
+ error: result.error,
+ },
+ }));
+
+ return controller;
+ }
+
+ const promOrNot = result.result;
if (typeof promOrNot === 'object' && 'then' in promOrNot) {
setResolvedConfigs((r) => {
diff --git a/packages/core/src/input-props-serialization.ts b/packages/core/src/input-props-serialization.ts
index bdc20752d7..0fe363c165 100644
--- a/packages/core/src/input-props-serialization.ts
+++ b/packages/core/src/input-props-serialization.ts
@@ -27,40 +27,46 @@ export const serializeJSONWithDate = ({
let mapUsed = false;
let setUsed = false;
- const serializedString = JSON.stringify(
- data,
- function (key, value) {
- const item = (this as Record<string, unknown>)[key];
- if (item instanceof Date) {
- customDateUsed = true;
- return `${DATE_TOKEN}${item.toISOString()}`;
- }
+ try {
+ const serializedString = JSON.stringify(
+ data,
+ function (key, value) {
+ const item = (this as Record<string, unknown>)[key];
+ if (item instanceof Date) {
+ customDateUsed = true;
+ return `${DATE_TOKEN}${item.toISOString()}`;
+ }
- if (item instanceof Map) {
- mapUsed = true;
- return value;
- }
-
- if (item instanceof Set) {
- setUsed = true;
- return value;
- }
+ if (item instanceof Map) {
+ mapUsed = true;
+ return value;
+ }
- if (
- typeof item === 'string' &&
- staticBase !== null &&
- item.startsWith(staticBase)
- ) {
- customFileUsed = true;
- return `${FILE_TOKEN}${item.replace(staticBase + '/', '')}`;
- }
+ if (item instanceof Set) {
+ setUsed = true;
+ return value;
+ }
- return value;
- },
- indent,
- );
+ if (
+ typeof item === 'string' &&
+ staticBase !== null &&
+ item.startsWith(staticBase)
+ ) {
+ customFileUsed = true;
+ return `${FILE_TOKEN}${item.replace(staticBase + '/', '')}`;
+ }
- return {serializedString, customDateUsed, customFileUsed, mapUsed, setUsed};
+ return value;
+ },
+ indent,
+ );
+ return {serializedString, customDateUsed, customFileUsed, mapUsed, setUsed};
+ } catch (err) {
+ throw new Error(
+ 'Could not serialize the passed input props to JSON: ' +
+ (err as Error).message,
+ );
+ }
};
export const deserializeJSONWithCustomFields = <T = Record<string, unknown>>(
diff --git a/packages/core/src/resolve-video-config.ts b/packages/core/src/resolve-video-config.ts
index ff1cb40a3d..2d2ba73d67 100644
--- a/packages/core/src/resolve-video-config.ts
+++ b/packages/core/src/resolve-video-config.ts
@@ -3,6 +3,11 @@ import type {
CalcMetadataReturnType,
CalculateMetadataFunction,
} from './Composition.js';
+import {getRemotionEnvironment} from './get-remotion-environment.js';
+import {
+ deserializeJSONWithCustomFields,
+ serializeJSONWithDate,
+} from './input-props-serialization.js';
import type {InferProps} from './props-if-has-props.js';
import {validateDefaultCodec} from './validation/validate-default-codec.js';
import {validateDimension} from './validation/validate-dimensions.js';
@@ -66,17 +71,23 @@ const validateCalculated = ({
return {width, height, fps, durationInFrames, defaultCodec};
};
-export const resolveVideoConfig = ({
- calculateMetadata,
- signal,
- defaultProps,
- originalProps,
- compositionId,
- compositionDurationInFrames,
- compositionFps,
- compositionHeight,
- compositionWidth,
-}: {
+const serializeThenDeserializeInStudio = (props: Record<string, unknown>) => {
+ // Serializing once in the Studio, to catch potential serialization errors before
+ // you only get them during rendering
+ if (getRemotionEnvironment().isStudio) {
+ return deserializeJSONWithCustomFields(
+ serializeJSONWithDate({
+ data: props,
+ indent: 2,
+ staticBase: window.remotion_staticBase,
+ }).serializedString,
+ );
+ }
+
+ return props;
+};
+
+type ResolveVideoConfigParams = {
compositionId: string;
compositionWidth: number | null;
compositionHeight: number | null;
@@ -88,7 +99,19 @@ export const resolveVideoConfig = ({
signal: AbortSignal;
defaultProps: Record<string, unknown>;
originalProps: Record<string, unknown>;
-}): VideoConfig | Promise<VideoConfig> => {
+};
+
+export const resolveVideoConfig = ({
+ calculateMetadata,
+ signal,
+ defaultProps,
+ originalProps,
+ compositionId,
+ compositionDurationInFrames,
+ compositionFps,
+ compositionHeight,
+ compositionWidth,
+}: ResolveVideoConfigParams): VideoConfig | Promise<VideoConfig> => {
const calculatedProm = calculateMetadata
? calculateMetadata({
defaultProps,
@@ -119,8 +142,8 @@ export const resolveVideoConfig = ({
fps,
durationInFrames,
id: compositionId,
- defaultProps,
- props: c.props ?? originalProps,
+ defaultProps: serializeThenDeserializeInStudio(defaultProps),
+ props: serializeThenDeserializeInStudio(c.props ?? originalProps),
defaultCodec: defaultCodec ?? null,
};
});
@@ -139,8 +162,8 @@ export const resolveVideoConfig = ({
return {
...data,
id: compositionId,
- defaultProps: defaultProps ?? {},
- props: originalProps,
+ defaultProps: serializeThenDeserializeInStudio(defaultProps ?? {}),
+ props: serializeThenDeserializeInStudio(originalProps),
defaultCodec: null,
};
}
@@ -148,8 +171,35 @@ export const resolveVideoConfig = ({
return {
...data,
id: compositionId,
- defaultProps: defaultProps ?? {},
- props: calculatedProm.props ?? originalProps,
+ defaultProps: serializeThenDeserializeInStudio(defaultProps ?? {}),
+ props: serializeThenDeserializeInStudio(
+ calculatedProm.props ?? originalProps,
+ ),
defaultCodec: calculatedProm.defaultCodec ?? null,
};
};
+
+export const resolveVideoConfigOrCatch = (
+ params: ResolveVideoConfigParams,
+):
+ | {
+ type: 'success';
+ result: VideoConfig | Promise<VideoConfig>;
+ }
+ | {
+ type: 'error';
+ error: Error;
+ } => {
+ try {
+ const promiseOrReturnValue = resolveVideoConfig(params);
+ return {
+ type: 'success',
+ result: promiseOrReturnValue,
+ };
+ } catch (err) {
+ return {
+ type: 'error',
+ error: err as Error,
+ };
+ }
+};
diff --git a/packages/docs/docs/calculate-metadata.mdx b/packages/docs/docs/calculate-metadata.mdx
index 0bc861e116..e73b9bab66 100644
--- a/packages/docs/docs/calculate-metadata.mdx
+++ b/packages/docs/docs/calculate-metadata.mdx
@@ -85,7 +85,7 @@ As argument, you get an object with the following properties:
The function must return an pure JSON-serializable object, which can contain the following properties:
-- `props` _optional_: The [final props](/docs/props-resolution) the component receives. It must have the [same shape](/docs/data-fetching#usage) as the `props` received by this function. The props must be a plain object and must not contain any non-JSON-serializable values, except `Date`.
+- `props` _optional_: The [final props](/docs/props-resolution) the component receives. It must have the [same shape](/docs/data-fetching#usage) as the `props` received by this function. The props must be a plain object and must not contain any non-JSON-serializable values, except `Date`, `Map`, `Set` and [`staticFile()`](/docs/staticfile).
- `durationInFrames` _optional_: The duration of the composition in frames
- `width` _optional_: The width of the composition in pixels
- `height` _optional_: The height of the composition in pixels
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index ee5ed32611..62139c681f 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -432,6 +432,31 @@ export const Index: React.FC = () => {
height={720}
/>
</MyCtx.Provider>
+ <Composition
+ id="circular-structure"
+ component={Framer}
+ width={1080}
+ height={1080}
+ durationInFrames={30}
+ fps={30}
+ calculateMetadata={() => {
+ const objectA = {
+ name: 'Object A',
+ };
+
+ const objectB = {
+ name: 'Object B',
+ linkedObject: objectA, // ObjectB links to objectA
+ };
+
+ // @ts-expect-error linked object
+ objectA.linkedObject = objectB;
+
+ return {
+ props: objectA,
+ };
+ }}
+ />
</Folder>
<Folder name="creatives">
<Composition
diff --git a/packages/studio/src/components/CanvasOrLoading.tsx b/packages/studio/src/components/CanvasOrLoading.tsx
index f5bf5812e2..57eb083645 100644
--- a/packages/studio/src/components/CanvasOrLoading.tsx
+++ b/packages/studio/src/components/CanvasOrLoading.tsx
@@ -6,6 +6,7 @@ import {BACKGROUND} from '../helpers/colors';
import {TimelineZoomCtx} from '../state/timeline-zoom';
import {Canvas} from './Canvas';
import {FramePersistor} from './FramePersistor';
+import {VERTICAL_SCROLLBAR_CLASSNAME} from './Menu/is-menu-item';
import {RefreshCompositionOverlay} from './RefreshCompositionOverlay';
import {
RunningCalculateMetadata,
@@ -114,7 +115,7 @@ const ErrorLoading: React.FC<{
readonly error: Error;
}> = ({error}) => {
return (
- <div style={loaderContainer}>
+ <div style={loaderContainer} className={VERTICAL_SCROLLBAR_CLASSNAME}>
<ErrorLoader
key={error.stack}
canHaveDismissButton={false}