🎥 Make videos programmatically with React
refactor validation logic
Jonny Burger06abf989fa22
diff --git a/packages/cli/src/editor/components/NewComposition/InputDragger.tsx b/packages/cli/src/editor/components/NewComposition/InputDragger.tsxindex c3d196e9b7..8088463de0 100644--- a/packages/cli/src/editor/components/NewComposition/InputDragger.tsx+++ b/packages/cli/src/editor/components/NewComposition/InputDragger.tsx@@ -158,6 +158,7 @@ export const InputDragger: React.FC<Props> = ({min={_min}step={_step}defaultValue={value}+ status="ok"{...props}/></HigherZIndex>diff --git a/packages/cli/src/editor/components/NewComposition/NewComposition.tsx b/packages/cli/src/editor/components/NewComposition/NewComposition.tsxindex 1e97232d70..31f4e4c524 100644--- a/packages/cli/src/editor/components/NewComposition/NewComposition.tsx+++ b/packages/cli/src/editor/components/NewComposition/NewComposition.tsx@@ -269,6 +269,7 @@ const NewComposition: React.FC<{initialCompType: CompType}> = (props) => {onChange={onNameChange}type="text"placeholder="Composition name"+ status="ok"/>{compNameErrMessage ? (<ValidationMessagediff --git a/packages/cli/src/editor/components/NewComposition/RemInput.tsx b/packages/cli/src/editor/components/NewComposition/RemInput.tsxindex 71672d3e32..794787e78d 100644--- a/packages/cli/src/editor/components/NewComposition/RemInput.tsx+++ b/packages/cli/src/editor/components/NewComposition/RemInput.tsx@@ -21,8 +21,7 @@ type Props = React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>,HTMLInputElement> & {- warning?: boolean;- disabled?: boolean;+ status: 'error' | 'warning' | 'ok';};export const INPUT_HORIZONTAL_PADDING = 8;@@ -46,7 +45,7 @@ export const inputBaseStyle: React.CSSProperties = {const RemInputForwardRef: React.ForwardRefRenderFunction<HTMLInputElement,Props-> = ({warning, disabled, ...props}, ref) => {+> = ({status, ...props}, ref) => {const [isFocused, setIsFocused] = useState(false);const [isHovered, setIsHovered] = useState(false);const inputRef = useRef<HTMLInputElement>(null);@@ -57,18 +56,19 @@ const RemInputForwardRef: React.ForwardRefRenderFunction<backgroundColor: INPUT_BACKGROUND,...inputBaseStyle,width: '100%',- borderColor: warning- ? WARNING_COLOR- : disabled- ? FAIL_COLOR- : isFocused- ? SELECTED_BACKGROUND- : isHovered- ? INPUT_BORDER_COLOR_HOVERED- : INPUT_BORDER_COLOR_UNHOVERED,+ borderColor:+ status === 'warning'+ ? WARNING_COLOR+ : status === 'error'+ ? FAIL_COLOR+ : isFocused+ ? SELECTED_BACKGROUND+ : isHovered+ ? INPUT_BORDER_COLOR_HOVERED+ : INPUT_BORDER_COLOR_UNHOVERED,...(props.style ?? {}),};- }, [disabled, isFocused, isHovered, props.style, warning]);+ }, [isFocused, isHovered, props.style, status]);useImperativeHandle(ref,diff --git a/packages/cli/src/editor/components/NewComposition/ValidationMessage.tsx b/packages/cli/src/editor/components/NewComposition/ValidationMessage.tsxindex b0c4f5b410..117e0d7408 100644--- a/packages/cli/src/editor/components/NewComposition/ValidationMessage.tsx+++ b/packages/cli/src/editor/components/NewComposition/ValidationMessage.tsx@@ -18,6 +18,7 @@ const style: React.CSSProperties = {const container: React.CSSProperties = {marginTop: 5,+ maxWidth: 500,};const label: React.CSSProperties = {@@ -35,6 +36,7 @@ export const ValidationMessage: React.FC<{<WarningTrianglestyle={{...style,+ flexShrink: 0,fill: type === 'warning' ? WARNING_COLOR : FAIL_COLOR,}}/>diff --git a/packages/cli/src/editor/components/RenderModal/RenderModal.tsx b/packages/cli/src/editor/components/RenderModal/RenderModal.tsxindex 9e068e3607..06fe0eda2d 100644--- a/packages/cli/src/editor/components/RenderModal/RenderModal.tsx+++ b/packages/cli/src/editor/components/RenderModal/RenderModal.tsx@@ -36,7 +36,7 @@ import {SegmentedControl} from '../SegmentedControl';import {leftSidebarTabs} from '../SidebarContent';import {Tab} from '../Tabs';import {useCrfState} from './CrfSetting';-import {isValidOutName} from './out-name-checker';+import {validateOutnameGui} from './out-name-checker';import type {RenderType} from './RenderModalAdvanced';import {RenderModalAdvanced} from './RenderModalAdvanced';import {RenderModalAudio} from './RenderModalAudio';@@ -730,7 +730,7 @@ export const RenderModal: React.FC<{];}, [currentComposition?.durationInFrames, renderMode, setRenderMode]);- const renderDisabled = !isValidOutName({+ const outnameValidation = validateOutnameGui({outName,codec,audioCodec,@@ -749,13 +749,13 @@ export const RenderModal: React.FC<{<ButtonautoFocusonClick={renderMode === 'still' ? onClickStill : onClickVideo}- disabled={state.type === 'load' || renderDisabled}+ disabled={state.type === 'load' || !outnameValidation.valid}style={{...buttonStyle,- backgroundColor: renderDisabled- ? 'var(--blue-disabled)'- : 'var(--blue)',- opacity: renderDisabled ? 0.7 : 1,+ backgroundColor: outnameValidation.valid+ ? 'var(--blue)'+ : 'var(--blue-disabled)',+ opacity: outnameValidation.valid ? 1 : 0.7,}}>{state.type === 'idle' ? `Render ${renderMode}` : 'Rendering...'}@@ -843,9 +843,9 @@ export const RenderModal: React.FC<{setEndFrame={setEndFrame}setStartFrame={setStartFrame}startFrame={startFrame}- audioCodec={audioCodec}- renderDisabled={renderDisabled}- stillImageFormat={stillImageFormat}+ validationMessage={+ outnameValidation.valid ? null : outnameValidation.error.message+ }/>) : tab === 'picture' ? (<RenderModalPicturediff --git a/packages/cli/src/editor/components/RenderModal/RenderModalAudio.tsx b/packages/cli/src/editor/components/RenderModal/RenderModalAudio.tsxindex cec0055420..f00eb0aa00 100644--- a/packages/cli/src/editor/components/RenderModal/RenderModalAudio.tsx+++ b/packages/cli/src/editor/components/RenderModal/RenderModalAudio.tsx@@ -143,6 +143,7 @@ export const RenderModalAudio: React.FC<{style={input}value={customTargetAudioBitrate}onChange={onTargetAudioBitrateChanged}+ status="ok"/></div></div>diff --git a/packages/cli/src/editor/components/RenderModal/RenderModalBasic.tsx b/packages/cli/src/editor/components/RenderModal/RenderModalBasic.tsxindex 9cc429a38c..5f3d932286 100644--- a/packages/cli/src/editor/components/RenderModal/RenderModalBasic.tsx+++ b/packages/cli/src/editor/components/RenderModal/RenderModalBasic.tsx@@ -1,9 +1,4 @@-import type {- AudioCodec,- Codec,- ProResProfile,- StillImageFormat,-} from '@remotion/renderer';+import type {Codec, ProResProfile} from '@remotion/renderer';import {BrowserSafeApis} from '@remotion/renderer/client';import React, {useCallback, useMemo} from 'react';import type {TComposition} from 'remotion';@@ -28,7 +23,6 @@ export const RenderModalBasic: React.FC<{renderMode: RenderType;imageFormatOptions: SegmentedControlItem[];codec: Codec;- audioCodec: AudioCodec;setVideoCodec: (newCodec: Codec) => void;outName: string;proResProfile: ProResProfile | null;@@ -41,14 +35,12 @@ export const RenderModalBasic: React.FC<{startFrame: number;endFrame: number;setStartFrame: React.Dispatch<React.SetStateAction<number | null>>;- renderDisabled: boolean;- stillImageFormat: StillImageFormat;+ validationMessage: string | null;}> = ({renderMode,imageFormatOptions,outName,codec,- audioCodec,setVideoCodec: setCodec,proResProfile,setProResProfile,@@ -60,8 +52,7 @@ export const RenderModalBasic: React.FC<{endFrame,setStartFrame,startFrame,- renderDisabled,- stillImageFormat,+ validationMessage,}) => {const existence = useFileExistence(outName);const videoCodecOptions = useMemo((): ComboboxValue[] => {@@ -205,11 +196,7 @@ export const RenderModalBasic: React.FC<{inputStyle={input}outName={outName}onValueChange={onValueChange}- codec={codec}- audioCodec={audioCodec}- renderDisabled={renderDisabled}- renderMode={renderMode}- stillImageFormat={stillImageFormat}+ validationMessage={validationMessage}/></div>);diff --git a/packages/cli/src/editor/components/RenderModal/RenderModalInput.tsx b/packages/cli/src/editor/components/RenderModal/RenderModalInput.tsxindex 18b2cbec64..ab34461e4d 100644--- a/packages/cli/src/editor/components/RenderModal/RenderModalInput.tsx+++ b/packages/cli/src/editor/components/RenderModal/RenderModalInput.tsx@@ -1,162 +1,24 @@-import type {AudioCodec, Codec, StillImageFormat} from '@remotion/renderer';-import {BrowserSafeApis} from '@remotion/renderer/client';-import React, {useMemo} from 'react';+import React from 'react';import {RemotionInput} from '../NewComposition/RemInput';import {ValidationMessage} from '../NewComposition/ValidationMessage';import {label, optionRow, rightRow} from './layout';-import {invalidCharacters} from './out-name-checker';-import type {RenderType} from './RenderModalAdvanced';-type Props<T extends Codec> = {+type Props = {existence: boolean;inputStyle: React.CSSProperties;outName: string;- codec: T;- audioCodec: AudioCodec;onValueChange: React.ChangeEventHandler<HTMLInputElement>;- renderDisabled: boolean;- renderMode: RenderType;- stillImageFormat: StillImageFormat;+ validationMessage: string | null;};// eslint-disable-next-line react/function-component-definition-export function RenderModalInput<T extends Codec>({+export function RenderModalInput({existence,inputStyle,outName,onValueChange,- codec,- audioCodec,- renderDisabled,- renderMode,- stillImageFormat,-}: Props<T>) {- const generateWarnings = useMemo(() => {- const extension = outName.substring(outName.lastIndexOf('.') + 1);- const prefix = outName.substring(0, outName.lastIndexOf('.'));-- const map = BrowserSafeApis.defaultFileExtensionMap[codec];-- const hasInvalidChar = () => {- return prefix.split('').some((char) => invalidCharacters.includes(char));- };-- if (renderMode === 'video') {- if (!(audioCodec in map.forAudioCodec)) {- throw new Error(- `Audio codec ${audioCodec} is not supported for codec ${codec}`- );- }-- const acceptableExtensions =- map.forAudioCodec[audioCodec as keyof typeof map.forAudioCodec]- .possible;-- try {- BrowserSafeApis.validateOutputFilename({- codec,- audioCodec: audioCodec ?? null,- extension,- preferLossless: false,- });- } catch (e) {- const errorMessage =- 'Invalid file extension. Valid extensions are: ' +- acceptableExtensions;- return (- <ValidationMessage- align="flex-end"- message={errorMessage}- type={'error'}- />- );- }- }-- if (renderMode === 'audio') {- if (audioCodec === 'pcm-16') {- if (extension !== 'wav' && extension !== 'wave')- return (- <ValidationMessage- align="flex-end"- message={'Extension has to be .wav or .wave'}- type={'error'}- />- );- } else if (extension !== audioCodec) {- return (- <ValidationMessage- align="flex-end"- message={'Extension has to be .' + audioCodec}- type={'error'}- />- );- }- }-- if (renderMode === 'still') {- if (stillImageFormat === 'jpeg') {- if (extension !== 'jpeg' && extension !== 'jpg') {- return (- <ValidationMessage- align="flex-end"- message={'Extension has to be .jpeg or .jpg'}- type={'error'}- />- );- }- } else if (extension !== stillImageFormat) {- return (- <ValidationMessage- align="flex-end"- message={'Extension has to be .' + stillImageFormat}- type={'error'}- />- );- }- }-- if (existence) {- return (- <ValidationMessage- align="flex-end"- message="Will be overwritten"- type={'warning'}- />- );- }-- if (prefix.length < 1) {- return (- <ValidationMessage- align="flex-end"- message="Filename can't be empty"- type={'error'}- />- );- }-- if (prefix[0] === '.') {- return (- <ValidationMessage- align="flex-end"- message="Filename can't start with '.'"- type={'error'}- />- );- }-- if (hasInvalidChar()) {- return (- <ValidationMessage- align="flex-end"- message="Filename can't contain the following characters: ?, *, +, %, :"- type={'error'}- />- );- }- }, [audioCodec, codec, existence, outName, renderMode, stillImageFormat]);-+ validationMessage,+}: Props) {return (<div style={optionRow}><div style={{flexDirection: 'column'}}>@@ -165,21 +27,33 @@ export function RenderModalInput<T extends Codec>({*// TODO improve this*/}- {renderDisabled || existence ? <div style={{height: '25px'}} /> : null}+ {validationMessage || existence ? (+ <div style={{height: '25px'}} />+ ) : null}</div><div style={rightRow}><div><RemotionInput- // TODO: Validate and reject folders or weird file names- warning={existence}- disabled={renderDisabled}+ status={validationMessage ? 'error' : existence ? 'warning' : 'ok'}style={inputStyle}type="text"value={outName}onChange={onValueChange}/>- {generateWarnings}+ {validationMessage ? (+ <ValidationMessage+ align="flex-end"+ message={validationMessage}+ type={'error'}+ />+ ) : existence ? (+ <ValidationMessage+ align="flex-end"+ message="Will be overwritten"+ type={'warning'}+ />+ ) : null}</div></div></div>diff --git a/packages/cli/src/editor/components/RenderModal/RenderModalPicture.tsx b/packages/cli/src/editor/components/RenderModal/RenderModalPicture.tsxindex 2f8bd15be5..d7e698df06 100644--- a/packages/cli/src/editor/components/RenderModal/RenderModalPicture.tsx+++ b/packages/cli/src/editor/components/RenderModal/RenderModalPicture.tsx@@ -154,6 +154,7 @@ export const RenderModalPicture: React.FC<{style={input}value={customTargetVideoBitrate}onChange={onTargetVideoBitrateChanged}+ status="ok"/></div></div>diff --git a/packages/cli/src/editor/components/RenderModal/out-name-checker.ts b/packages/cli/src/editor/components/RenderModal/out-name-checker.tsindex e29ab0db98..dd878b52cf 100644--- a/packages/cli/src/editor/components/RenderModal/out-name-checker.ts+++ b/packages/cli/src/editor/components/RenderModal/out-name-checker.ts@@ -8,16 +8,41 @@ const isValidStillExtension = (extension: string,stillImageFormat: StillImageFormat): boolean => {- if (stillImageFormat === 'jpeg') {- if (extension === 'jpg') {- return true;- }+ if (stillImageFormat === 'jpeg' && extension === 'jpg') {+ return true;}return extension === stillImageFormat;};-export const isValidOutName = ({+export const validateOutnameGui = ({+ outName,+ codec,+ audioCodec,+ renderMode,+ stillImageFormat,+}: {+ outName: string;+ codec: Codec;+ audioCodec: AudioCodec;+ renderMode: RenderType;+ stillImageFormat?: StillImageFormat;+}): {valid: true} | {valid: false; error: Error} => {+ try {+ isValidOutName({+ audioCodec,+ codec,+ outName,+ renderMode,+ stillImageFormat,+ });+ return {valid: true};+ } catch (err) {+ return {valid: false, error: err as Error};+ }+};++const isValidOutName = ({outName,codec,audioCodec,@@ -29,7 +54,7 @@ export const isValidOutName = ({audioCodec: AudioCodec;renderMode: RenderType;stillImageFormat?: StillImageFormat;-}): boolean => {+}): void => {const extension = outName.substring(outName.lastIndexOf('.') + 1);const prefix = outName.substring(0, outName.lastIndexOf('.'));@@ -46,41 +71,51 @@ export const isValidOutName = ({};if (renderMode === 'video') {- try {- BrowserSafeApis.validateOutputFilename({- codec,- audioCodec: audioCodec ?? null,- extension,- preferLossless: false,- });- } catch (e) {- return false;- }+ BrowserSafeApis.validateOutputFilename({+ codec,+ audioCodec: audioCodec ?? null,+ extension,+ preferLossless: false,+ });}if (prefix.length < 1) {- return false;+ throw new Error('The prefix must be at least 1 character long');}if (prefix[0] === '.') {- return false;+ throw new Error('The output name must not start with a dot');}if (hasInvalidChar()) {- return false;+ throw new Error(+ "Filename can't contain the following characters: ?, *, +, %, :"+ );}- if (renderMode === 'still' && stillImageFormat) {- return isValidStillExtension(extension, stillImageFormat);+ if (+ renderMode === 'still' &&+ stillImageFormat &&+ !isValidStillExtension(extension, stillImageFormat)+ ) {+ throw new Error(+ `The extension ${extension} is not supported for still image format ${stillImageFormat}`+ );}if (renderMode === 'audio') {if (audioCodec === 'pcm-16') {- return extension === 'wav' || extension === 'wave';+ if (extension !== 'wav' && extension !== 'wave') {+ throw new Error(+ `The extension ${extension} is not supported for audio codec ${audioCodec}`+ );+ }}- return audioCodec === extension;+ if (audioCodec !== extension) {+ throw new Error(+ `The extension ${extension} is not supported for audio codec ${audioCodec}`+ );+ }}-- return true;};