Skip to content

πŸŽ₯ Make videos programmatically with React

cleanly handle invalid input in json editor

Jonny Burger98979cebb439
diff --git a/packages/example/e2e/json-editor.test.mts b/packages/example/e2e/json-editor.test.mts
index d9979c33e6..ce7a36b2a1 100644
--- a/packages/example/e2e/json-editor.test.mts
+++ b/packages/example/e2e/json-editor.test.mts
@@ -56,14 +56,35 @@ test.describe('visual mode', () => {
await textarea.fill('{invalid json');
- await expect(
- page.locator('[data-testid="json-props-error"]'),
- ).not.toBeEmpty({timeout: 5_000});
+ const errorDiv = page.locator('[data-testid="json-props-error"]');
+
+ await expect(errorDiv).not.toBeEmpty({timeout: 5_000});
await textarea.blur();
await page.waitForTimeout(500);
expect(fs.readFileSync(rootFile, 'utf-8')).toBe(contentBefore);
+
+ // Update the root file on disk β€” the textarea should auto-update and the error should clear
+ const updatedTitle = 'disk-update-clears-error';
+ const updatedContent = contentBefore.replace(
+ /title: '[^']*'/,
+ `title: '${updatedTitle}'`,
+ );
+ fs.writeFileSync(rootFile, updatedContent);
+
+ await expect(textarea).toHaveValue(new RegExp(updatedTitle), {
+ timeout: 10_000,
+ });
+
+ await expect(errorDiv).toBeEmpty({timeout: 5_000});
+
+ // Restore original file
+ fs.writeFileSync(rootFile, contentBefore);
+
+ await expect(textarea).not.toHaveValue(new RegExp(updatedTitle), {
+ timeout: 10_000,
+ });
});
test('should show error and not save on blur when JSON does not match schema', async ({
diff --git a/packages/studio/src/components/RenderModal/DataEditor.tsx b/packages/studio/src/components/RenderModal/DataEditor.tsx
index eb6874f2f8..d5aae107db 100644
--- a/packages/studio/src/components/RenderModal/DataEditor.tsx
+++ b/packages/studio/src/components/RenderModal/DataEditor.tsx
@@ -4,17 +4,14 @@ import {getInputProps} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
import {BACKGROUND, BORDER_COLOR, LIGHT_TEXT} from '../../helpers/colors';
-import {useZodIfPossible, useZodTypesIfPossible} from '../get-zod-if-possible';
+import {useZodIfPossible} from '../get-zod-if-possible';
import {Flex, Spacing} from '../layout';
import {ValidationMessage} from '../NewComposition/ValidationMessage';
-import {showNotification} from '../Notifications/NotificationCenter';
-import {callUpdateDefaultPropsApi} from '../RenderQueue/actions';
import type {SegmentedControlItem} from '../SegmentedControl';
import {SegmentedControl} from '../SegmentedControl';
import type {TypeCanSaveState} from './get-render-modal-warnings';
import {getRenderModalWarnings} from './get-render-modal-warnings';
import {RenderModalJSONPropsEditor} from './RenderModalJSONPropsEditor';
-import {extractEnumJsonPaths} from './SchemaEditor/extract-enum-json-paths';
import {SchemaEditor} from './SchemaEditor/SchemaEditor';
import {
NoDefaultProps,
@@ -130,6 +127,10 @@ export const DataEditor: React.FC<{
[setDefaultProps],
);
+ const onSave = useCallback(() => {
+ setDefaultProps((p) => p, {shouldSave: true});
+ }, [setDefaultProps]);
+
const inJSONEditor = mode === 'json';
const serializedJSON: SerializedJSONWithCustomFields | null = useMemo(() => {
if (!inJSONEditor) {
@@ -147,7 +148,6 @@ export const DataEditor: React.FC<{
const cliProps = getInputProps();
const z = useZodIfPossible();
- const zodTypes = useZodTypesIfPossible();
const schema = useMemo(() => {
if (!z) {
@@ -220,26 +220,6 @@ export const DataEditor: React.FC<{
];
}, [mode]);
- const onUpdate = useCallback(() => {
- if (schema === 'no-zod' || schema === 'no-schema' || z === null) {
- showNotification('Cannot update default props: No Zod schema', 2000);
- return;
- }
-
- callUpdateDefaultPropsApi(
- unresolvedComposition.id,
- defaultProps,
- extractEnumJsonPaths({schema, zodRuntime: z, currentPath: [], zodTypes}),
- ).then((response) => {
- if (!response.success) {
- showNotification(
- `Cannot update default props: ${response.reason}`,
- 2000,
- );
- }
- });
- }, [schema, z, unresolvedComposition.id, defaultProps, zodTypes]);
-
const connectionStatus = previewServerState.type;
const warnings = useMemo(() => {
@@ -336,17 +316,16 @@ export const DataEditor: React.FC<{
value={defaultProps}
setValue={setDefaultProps}
schema={schema}
- zodValidationResult={zodValidationResult}
- savedDefaultProps={unresolvedComposition.defaultProps}
/>
) : (
<RenderModalJSONPropsEditor
value={defaultProps ?? {}}
setValue={jsonEditorSetValue}
- onSave={onUpdate}
+ onSave={onSave}
serializedJSON={serializedJSON}
defaultProps={unresolvedComposition.defaultProps}
schema={schema}
+ compositionId={unresolvedComposition.id}
/>
)}
</div>
diff --git a/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsx b/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsx
index 6c6f75f583..ab3e43cc87 100644
--- a/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsx
+++ b/packages/studio/src/components/RenderModal/RenderModalJSONPropsEditor.tsx
@@ -1,6 +1,8 @@
import React, {useCallback, useEffect, useMemo} from 'react';
+import {useContext} from 'react';
import type {SerializedJSONWithCustomFields} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
+import {StudioServerConnectionCtx} from '../../helpers/client-id';
import {FAIL_COLOR} from '../../helpers/colors';
import {Button} from '../Button';
import {Flex, Row, Spacing} from '../layout';
@@ -24,6 +26,27 @@ const scrollable: React.CSSProperties = {
flex: 1,
};
+const parseJS = (
+ value: Record<string, unknown>,
+ schema: AnyZodSchema,
+): State => {
+ try {
+ const zodValidation = zodSafeParse(schema, value);
+ return {
+ str: JSON.stringify(value, null, 2),
+ value,
+ validJSON: true,
+ zodValidation,
+ };
+ } catch (e) {
+ return {
+ str: JSON.stringify(value, null, 2),
+ validJSON: false,
+ error: (e as Error).message,
+ };
+ }
+};
+
const parseJSON = (str: string, schema: AnyZodSchema): State => {
try {
const value = NoReactInternals.deserializeJSONWithSpecialTypes(str);
@@ -43,15 +66,47 @@ export const RenderModalJSONPropsEditor: React.FC<{
readonly serializedJSON: SerializedJSONWithCustomFields | null;
readonly defaultProps: Record<string, unknown>;
readonly schema: AnyZodSchema;
-}> = ({setValue, value, defaultProps, onSave, serializedJSON, schema}) => {
+ readonly compositionId: string;
+}> = ({
+ setValue,
+ value,
+ defaultProps,
+ onSave,
+ serializedJSON,
+ schema,
+ compositionId,
+}) => {
if (serializedJSON === null) {
throw new Error('expecting serializedJSON to be defined');
}
+ const {subscribeToEvent} = useContext(StudioServerConnectionCtx);
+
const [localValue, setLocalValue] = React.useState<State>(() => {
return parseJSON(serializedJSON.serializedString, schema);
});
+ useEffect(() => {
+ const unsub = subscribeToEvent('default-props-updatable-changed', (e) => {
+ if (e.type !== 'default-props-updatable-changed') {
+ return;
+ }
+
+ if (e.compositionId !== compositionId) {
+ return;
+ }
+
+ const {result} = e;
+ if (result.canUpdate) {
+ setLocalValue(parseJS(result.currentDefaultProps, schema));
+ }
+ });
+
+ return () => {
+ unsub();
+ };
+ }, [subscribeToEvent, compositionId, schema]);
+
const onPretty = useCallback(() => {
if (!localValue.validJSON) {
return;
diff --git a/packages/studio/src/components/RenderModal/SchemaEditor/SchemaEditor.tsx b/packages/studio/src/components/RenderModal/SchemaEditor/SchemaEditor.tsx
index eeabb4faea..c5aa96b648 100644
--- a/packages/studio/src/components/RenderModal/SchemaEditor/SchemaEditor.tsx
+++ b/packages/studio/src/components/RenderModal/SchemaEditor/SchemaEditor.tsx
@@ -1,14 +1,10 @@
import React from 'react';
import {useZodIfPossible} from '../../get-zod-if-possible';
import {VERTICAL_SCROLLBAR_CLASSNAME} from '../../Menu/is-menu-item';
-import {
- InvalidDefaultProps,
- InvalidSchema,
- TopLevelZodValue,
-} from './SchemaErrorMessages';
+import {TopLevelZodValue} from './SchemaErrorMessages';
import {defaultPropsEditorScrollableAreaRef} from './scroll-to-default-props-path';
-import type {AnyZodSchema, ZodSafeParseResult} from './zod-schema-type';
-import {getZodSchemaType, zodSafeParse} from './zod-schema-type';
+import type {AnyZodSchema} from './zod-schema-type';
+import {getZodSchemaType} from './zod-schema-type';
import {ZodObjectEditor} from './ZodObjectEditor';
import type {UpdaterFunction} from './ZodSwitch';
@@ -22,9 +18,7 @@ export const SchemaEditor: React.FC<{
readonly schema: AnyZodSchema;
readonly value: Record<string, unknown>;
readonly setValue: UpdaterFunction<Record<string, unknown>>;
- readonly zodValidationResult: ZodSafeParseResult;
- readonly savedDefaultProps: Record<string, unknown>;
-}> = ({schema, value, setValue, zodValidationResult, savedDefaultProps}) => {
+}> = ({schema, value, setValue}) => {
const z = useZodIfPossible();
if (!z) {
throw new Error('expected zod');
@@ -32,16 +26,6 @@ export const SchemaEditor: React.FC<{
const typeName = getZodSchemaType(schema);
- if (!zodValidationResult.success) {
- const defaultPropsValid = zodSafeParse(schema, savedDefaultProps);
-
- if (!defaultPropsValid.success) {
- return <InvalidDefaultProps zodValidationResult={zodValidationResult} />;
- }
-
- return <InvalidSchema zodValidationResult={zodValidationResult} />;
- }
-
if (typeName !== 'object') {
return <TopLevelZodValue typeReceived={typeName} />;
}