Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Add seconds and timecode input for composition duration

Jonny Burgerb83f3b53b4d0
diff --git a/packages/studio/src/components/InspectorPanel/CompositionMetadata.tsx b/packages/studio/src/components/InspectorPanel/CompositionMetadata.tsx
index 2d1142bfbf..84f2d14348 100644
--- a/packages/studio/src/components/InspectorPanel/CompositionMetadata.tsx
+++ b/packages/studio/src/components/InspectorPanel/CompositionMetadata.tsx
@@ -17,7 +17,7 @@ import {ContextMenu} from '../ContextMenu';
import {InlineDropdown} from '../InlineDropdown';
import type {ComboboxValue} from '../NewComposition/ComboBox';
import {
- InputDragger,
+ InputDraggerWithTextEditing,
inputDraggerContainerStyle,
} from '../NewComposition/InputDragger';
import {showNotification} from '../Notifications/NotificationCenter';
@@ -33,6 +33,7 @@ import {
type PendingCompositionMetadataValue,
reconcilePendingCompositionMetadata,
} from './optimistic-composition-metadata';
+import {parseCompositionDuration} from './parse-composition-duration';
import {detailsContainer} from './styles';
const compositionMetadataContainer: React.CSSProperties = {
@@ -270,6 +271,22 @@ const CompositionMetadataValue: React.FC<{
],
[setShowFrames, showFrames],
);
+ const textEditing = useMemo(() => {
+ if (field !== 'durationInFrames') {
+ return null;
+ }
+
+ return {
+ format: (newValue: number | string) =>
+ showFrames || fps === null
+ ? String(Math.round(Number(newValue)))
+ : formatValue(newValue),
+ parse: (text: string) => parseCompositionDuration(text, fps),
+ hint: '5s · 1:30 · 150f\nTimecode: minutes:seconds.frames',
+ invalidMessage: 'Enter a duration such as 5s, 1:30, or 150f.',
+ onCancel: () => setDragValue(null),
+ };
+ }, [field, formatValue, fps, showFrames]);
const content =
computed || disabled ? (
@@ -277,10 +294,11 @@ const CompositionMetadataValue: React.FC<{
<span style={computedValueStyle}>{formatValue(value)}</span>
</span>
) : (
- <InputDragger
+ <InputDraggerWithTextEditing
aria-label={fieldLabels[field]}
buttonStyle={metadataDraggerStyles[field]}
type="number"
+ textEditing={textEditing}
value={dragValue ?? pendingValue?.value ?? value}
disabled={pendingValue !== null}
status="ok"
diff --git a/packages/studio/src/components/InspectorPanel/parse-composition-duration.ts b/packages/studio/src/components/InspectorPanel/parse-composition-duration.ts
new file mode 100644
index 0000000000..fda5c3f2a1
--- /dev/null
+++ b/packages/studio/src/components/InspectorPanel/parse-composition-duration.ts
@@ -0,0 +1,56 @@
+import {parseInputDraggerNumber} from '../NewComposition/InputDragger';
+
+export const parseCompositionDuration = (
+ input: string,
+ fps: number | null,
+): number | null => {
+ const text = input.trim().toLowerCase();
+ const frameValue = parseInputDraggerNumber(
+ text.replace(/\s*f(?:rames?)?$/, ''),
+ );
+ if (frameValue !== null) {
+ return frameValue;
+ }
+
+ if (fps === null || !Number.isFinite(fps) || fps <= 0) {
+ return null;
+ }
+
+ const timecode = text.match(/^(?:(\d+):)?(\d+):(\d{1,2})(?:\.(\d+))?$/);
+ if (timecode) {
+ const hours = Number(timecode[1] ?? 0);
+ const minutes = Number(timecode[2]);
+ const timecodeSeconds = Number(timecode[3]);
+ const frames = Number(timecode[4] ?? 0);
+ if (timecodeSeconds >= 60 || (timecode[1] !== undefined && minutes >= 60)) {
+ return null;
+ }
+
+ const timecodeDuration = Math.round(
+ (hours * 3600 + minutes * 60 + timecodeSeconds) * fps + frames,
+ );
+ return Number.isFinite(timecodeDuration) ? timecodeDuration : null;
+ }
+
+ const units = text.matchAll(/(\d+(?:\.\d*)?|\.\d+)\s*([hms])\s*/g);
+ let consumed = 0;
+ let previousUnit = -1;
+ let seconds = 0;
+ for (const match of units) {
+ const unit = 'hms'.indexOf(match[2]);
+ if (match.index !== consumed || unit <= previousUnit) {
+ return null;
+ }
+
+ seconds += Number(match[1]) * [3600, 60, 1][unit];
+ consumed += match[0].length;
+ previousUnit = unit;
+ }
+
+ if (consumed === 0 || consumed !== text.length) {
+ return null;
+ }
+
+ const duration = Math.round(seconds * fps);
+ return Number.isFinite(duration) ? duration : null;
+};
diff --git a/packages/studio/src/components/NewComposition/InputDragger.tsx b/packages/studio/src/components/NewComposition/InputDragger.tsx
index 7be4743f8c..ef11569b32 100644
--- a/packages/studio/src/components/NewComposition/InputDragger.tsx
+++ b/packages/studio/src/components/NewComposition/InputDragger.tsx
@@ -13,6 +13,7 @@ import {
} from '../../helpers/pointer-session';
import {getClickLock, setClickLock} from '../../state/input-dragger-click-lock';
import {HigherZIndex} from '../../state/z-index';
+import {ActionTooltip} from '../ActionTooltip';
import {
forceSpecificCursor,
stopForcingSpecificCursor,
@@ -42,6 +43,14 @@ type Props = Omit<InputHTMLAttributes<HTMLInputElement>, 'title'> & {
readonly dragSensitivity?: number;
};
+type TextEditing = {
+ readonly format: (value: number | string) => string;
+ readonly parse: (text: string) => number | null;
+ readonly hint: string | null;
+ readonly invalidMessage: string;
+ readonly onCancel: () => void;
+};
+
type InputDraggerValidationResult =
| {
readonly valid: true;
@@ -498,7 +507,7 @@ export const deriveInputDraggerValueDiff = ({
const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
HTMLButtonElement,
- Props
+ Props & {readonly textEditing: TextEditing | null}
> = (
{
onValueChange,
@@ -523,6 +532,7 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
dragDecimalPlaces,
dragSensitivity = 1,
type: _type,
+ textEditing,
...props
},
ref,
@@ -531,6 +541,33 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
const [dragging, setDragging] = useState(false);
const fallbackRef = useRef<HTMLInputElement>(null);
const pointerDownRef = useRef(false);
+ const formattedInputValueRef = useRef<{text: string; value: number} | null>(
+ null,
+ );
+ const startEditing = useCallback(() => {
+ formattedInputValueRef.current = {
+ text:
+ textEditing?.format(value as number | string) ?? String(value ?? ''),
+ value: deriveInputDraggerDragStartValue({min: _min, value}),
+ };
+ setInputFallback(true);
+ }, [_min, textEditing, value]);
+ const parseText = useCallback(
+ (text: string) => {
+ // Preserve the exact value when a rounded display is left untouched.
+ if (
+ textEditing !== null &&
+ text === formattedInputValueRef.current?.text
+ ) {
+ return formattedInputValueRef.current.value;
+ }
+
+ return textEditing === null
+ ? parseInputDraggerNumber(text)
+ : textEditing.parse(text);
+ },
+ [textEditing],
+ );
const deriveStep = useMemo(() => {
return deriveInputDraggerStep({
min: _min,
@@ -561,21 +598,24 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
const wasActivatedByInputDragger = consumeInputDraggerActivationRequest();
if (small || wasActivatedByInputDragger) {
- setInputFallback(true);
+ startEditing();
}
- }, [small]);
+ }, [small, startEditing]);
- const onClick: MouseEventHandler<HTMLButtonElement> = useCallback((e) => {
- if (!getClickLock()) {
- e.stopPropagation();
- }
+ const onClick: MouseEventHandler<HTMLButtonElement> = useCallback(
+ (e) => {
+ if (!getClickLock()) {
+ e.stopPropagation();
+ }
- if (getClickLock()) {
- return;
- }
+ if (getClickLock()) {
+ return;
+ }
- setInputFallback(true);
- }, []);
+ startEditing();
+ },
+ [startEditing],
+ );
const onKeyDown: React.KeyboardEventHandler<HTMLButtonElement> = useCallback(
(e) => {
@@ -585,19 +625,20 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
e.preventDefault();
e.stopPropagation();
- setInputFallback(true);
+ startEditing();
},
- [],
+ [startEditing],
);
const onEscape = useCallback(() => {
+ textEditing?.onCancel();
setInputFallback(false);
- }, []);
+ }, [textEditing]);
const onInputChange: React.ChangeEventHandler<HTMLInputElement> = useCallback(
(e) => {
e.target.setCustomValidity('');
- const parsed = parseInputDraggerNumber(e.target.value);
+ const parsed = parseText(e.target.value);
if (
parsed !== null &&
(!integerOnly || Number.isInteger(parsed)) &&
@@ -610,7 +651,7 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
onValueChange(parsed, 'input');
}
},
- [_max, _min, integerOnly, onValueChange],
+ [_max, _min, integerOnly, onValueChange, parseText],
);
const onBlur = useCallback(() => {
@@ -624,11 +665,12 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
return;
}
+ const parsed = parseText(newValue);
const validation = validateInputDraggerValue({
max: _max,
min: _min,
step: validationStep,
- value: newValue,
+ value: parsed === null ? '' : String(parsed),
integerOnly,
});
@@ -638,10 +680,23 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
setInputFallback(false);
} else {
- fallbackRef.current.setCustomValidity(validation.message);
+ fallbackRef.current.setCustomValidity(
+ parsed === null && textEditing !== null
+ ? textEditing.invalidMessage
+ : validation.message,
+ );
fallbackRef.current.reportValidity();
}
- }, [_max, _min, integerOnly, onEscape, onValueChangeEnd, validationStep]);
+ }, [
+ _max,
+ _min,
+ integerOnly,
+ onEscape,
+ onValueChangeEnd,
+ parseText,
+ textEditing,
+ validationStep,
+ ]);
const onInputKeyDown: React.KeyboardEventHandler<HTMLInputElement> =
useCallback(
@@ -661,7 +716,7 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
}
e.preventDefault();
- const parsedInputValue = parseInputDraggerNumber(e.currentTarget.value);
+ const parsedInputValue = parseText(e.currentTarget.value);
const currentValue =
parsedInputValue ??
deriveInputDraggerDragStartValue({
@@ -683,11 +738,25 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
return;
}
- e.currentTarget.value = String(nextValue);
+ e.currentTarget.value =
+ textEditing?.format(nextValue) ?? String(nextValue);
+ formattedInputValueRef.current = {
+ text: e.currentTarget.value,
+ value: nextValue,
+ };
e.currentTarget.setCustomValidity('');
onValueChange(nextValue, 'input');
},
- [_max, _min, deriveStep, integerOnly, onValueChange, value],
+ [
+ _max,
+ _min,
+ deriveStep,
+ integerOnly,
+ onValueChange,
+ parseText,
+ textEditing,
+ value,
+ ],
);
const roundToStep = (val: number, stepSize: number) => {
@@ -790,33 +859,49 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
}, [inputFallback]);
if (inputFallback) {
+ const input = (
+ <RemotionInput
+ ref={fallbackRef}
+ autoFocus
+ onKeyDown={onInputKeyDown}
+ onBlur={onBlur}
+ onChange={onInputChange}
+ min={_min}
+ max={_max}
+ step={validationStep}
+ defaultValue={formattedInputValueRef.current?.text ?? value}
+ status={status}
+ rightAlign={rightAlign}
+ small={small}
+ {...props}
+ aria-description={textEditing?.hint ?? props['aria-description']}
+ style={
+ small
+ ? {
+ ...compactInputDraggerStyle,
+ display: 'block',
+ ...inputStyle,
+ }
+ : inputStyle
+ }
+ type="text"
+ />
+ );
return (
<HigherZIndex onEscape={onEscape} onOutsideClick={noop}>
- <RemotionInput
- ref={fallbackRef}
- autoFocus
- onKeyDown={onInputKeyDown}
- onBlur={onBlur}
- onChange={onInputChange}
- min={_min}
- max={_max}
- step={validationStep}
- defaultValue={value}
- status={status}
- rightAlign={rightAlign}
- small={small}
- {...props}
- style={
- small
- ? {
- ...compactInputDraggerStyle,
- display: 'block',
- ...inputStyle,
- }
- : inputStyle
- }
- type="text"
- />
+ {textEditing?.hint ? (
+ <ActionTooltip
+ label={textEditing.hint}
+ shortcut={null}
+ delay={null}
+ dismissOnClick={false}
+ triggerStyle={{display: 'block'}}
+ >
+ {input}
+ </ActionTooltip>
+ ) : (
+ input
+ )}
</HigherZIndex>
);
}
@@ -854,4 +939,15 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<
);
};
-export const InputDragger = React.forwardRef(InputDraggerForwardRefFn);
+export const InputDraggerWithTextEditing = React.forwardRef(
+ InputDraggerForwardRefFn,
+);
+
+const InputDraggerWithoutTextEditing: React.ForwardRefRenderFunction<
+ HTMLButtonElement,
+ Props
+> = (props, ref) => (
+ <InputDraggerWithTextEditing {...props} ref={ref} textEditing={null} />
+);
+
+export const InputDragger = React.forwardRef(InputDraggerWithoutTextEditing);