🎥 Make videos programmatically with React
`@remotion/studio`: Use text inputs for InputDragger (#9559)
Jonny Burger3432125b6a55
diff --git a/packages/example/e2e/visual-controls.test.mts b/packages/example/e2e/visual-controls.test.mtsindex 1c7052903d..b19b9a4c6a 100644--- a/packages/example/e2e/visual-controls.test.mts+++ b/packages/example/e2e/visual-controls.test.mts@@ -149,7 +149,7 @@ test.describe('visual controls', () => {await expect(dragger).toBeVisible({timeout: 10_000});await dragger.click();- const input = fieldset.locator('input[type="number"]');+ const input = fieldset.locator('input[type="text"]');await expect(input).toBeVisible({timeout: 5_000});const newValue = '90';diff --git a/packages/studio/src/components/NewComposition/InputDragger.tsx b/packages/studio/src/components/NewComposition/InputDragger.tsxindex cf64a1d4af..4d5949e4fd 100644--- a/packages/studio/src/components/NewComposition/InputDragger.tsx+++ b/packages/studio/src/components/NewComposition/InputDragger.tsx@@ -29,6 +29,16 @@ type Props = InputHTMLAttributes<HTMLInputElement> & {readonly dragSensitivity?: number;};+type InputDraggerValidationResult =+ | {+ readonly valid: true;+ readonly value: number;+ }+ | {+ readonly valid: false;+ readonly message: string;+ };+export const inputDraggerContainerStyle: React.CSSProperties = {...inputBaseStyle,backgroundColor: TRANSPARENT,@@ -49,6 +59,146 @@ const roundToDecimalPlaces = (val: number, decimalPlaces: number) => {return Object.is(rounded, -0) ? 0 : rounded;};+const validNumberPattern =+ /^[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e[+-]?\d+)?$/i;++export const parseInputDraggerNumber = (value: string) => {+ const trimmedValue = value.trim();+ if (!validNumberPattern.test(trimmedValue)) {+ return null;+ }++ const parsed = Number(trimmedValue);+ return Number.isFinite(parsed) ? parsed : null;+};++const getFiniteAttribute = (+ value: React.InputHTMLAttributes<HTMLInputElement>['min'],+) => {+ const parsed = Number(value);+ return Number.isFinite(parsed) ? parsed : null;+};++const getPositiveStep = (+ step: React.InputHTMLAttributes<HTMLInputElement>['step'],+) => {+ if (step === 'any') {+ return null;+ }++ const parsed = Number(step);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 1;+};++export const isInputDraggerValueAlignedToStep = ({+ min,+ step,+ value,+}: {+ readonly min: React.InputHTMLAttributes<HTMLInputElement>['min'];+ readonly step: React.InputHTMLAttributes<HTMLInputElement>['step'];+ readonly value: number;+}) => {+ const numericStep = getPositiveStep(step);+ if (numericStep === null) {+ return true;+ }++ const stepBase = getFiniteAttribute(min) ?? 0;+ const stepsFromBase = (value - stepBase) / numericStep;+ const tolerance =+ Number.EPSILON *+ 10 *+ Math.max(+ 1,+ Math.abs(value / numericStep),+ Math.abs(stepBase / numericStep),+ );++ return Math.abs(stepsFromBase - Math.round(stepsFromBase)) <= tolerance;+};++export const validateInputDraggerValue = ({+ max,+ min,+ step,+ value,+}: {+ readonly max: React.InputHTMLAttributes<HTMLInputElement>['max'];+ readonly min: React.InputHTMLAttributes<HTMLInputElement>['min'];+ readonly step: React.InputHTMLAttributes<HTMLInputElement>['step'];+ readonly value: string;+}): InputDraggerValidationResult => {+ const parsed = parseInputDraggerNumber(value);+ if (parsed === null) {+ return {+ valid: false,+ message: 'Enter a valid number.',+ };+ }++ const numericMin = getFiniteAttribute(min);+ if (numericMin !== null && parsed < numericMin) {+ return {+ valid: false,+ message: `Value must be greater than or equal to ${numericMin}.`,+ };+ }++ const numericMax = getFiniteAttribute(max);+ if (numericMax !== null && parsed > numericMax) {+ return {+ valid: false,+ message: `Value must be less than or equal to ${numericMax}.`,+ };+ }++ if (!isInputDraggerValueAlignedToStep({min, step, value: parsed})) {+ return {+ valid: false,+ message: `Value must align to a step of ${step}.`,+ };+ }++ return {valid: true, value: parsed};+};++const getDecimalPlaces = (value: number) => {+ const [mantissa, exponentString] = String(value).toLowerCase().split('e');+ const exponent = Number(exponentString ?? 0);+ const fractionLength = mantissa.split('.')[1]?.length ?? 0;+ return Math.max(0, fractionLength - exponent);+};++export const deriveInputDraggerArrowValue = ({+ direction,+ max,+ min,+ step,+ value,+}: {+ readonly direction: 1 | -1;+ readonly max: React.InputHTMLAttributes<HTMLInputElement>['max'];+ readonly min: React.InputHTMLAttributes<HTMLInputElement>['min'];+ readonly step: React.InputHTMLAttributes<HTMLInputElement>['step'];+ readonly value: number;+}) => {+ const numericStep = getPositiveStep(step) ?? 1;+ const decimalPlaces = Math.max(+ getDecimalPlaces(value),+ getDecimalPlaces(numericStep),+ );+ const unroundedValue = value + direction * numericStep;+ const steppedValue =+ decimalPlaces <= 15+ ? roundToDecimalPlaces(unroundedValue, decimalPlaces)+ : Number(unroundedValue.toPrecision(15));+ const numericMin = getFiniteAttribute(min) ?? -Infinity;+ const numericMax = getFiniteAttribute(max) ?? Infinity;++ return Math.min(numericMax, Math.max(numericMin, steppedValue));+};+export const deriveInputDraggerStep = ({min,snapToStep,@@ -146,6 +296,7 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<snapToStep = true,dragDecimalPlaces,dragSensitivity = 1,+ type: _type,...props},ref,@@ -154,6 +305,13 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<const [dragging, setDragging] = useState(false);const fallbackRef = useRef<HTMLInputElement>(null);const pointerDownRef = useRef(false);+ const deriveStep = useMemo(() => {+ return deriveInputDraggerStep({+ min: _min,+ snapToStep,+ step: _step,+ });+ }, [_min, _step, snapToStep]);const span: React.CSSProperties = useMemo(() => ({@@ -206,10 +364,10 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<const onInputChange: React.ChangeEventHandler<HTMLInputElement> = useCallback((e) => {- const parsed = Number(e.target.value);+ e.target.setCustomValidity('');+ const parsed = parseInputDraggerNumber(e.target.value);if (- e.target.value !== '' &&- !Number.isNaN(parsed) &&+ parsed !== null &&isInputDraggerValueInRange({max: _max,min: _min,@@ -233,23 +391,58 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<return;}- if (fallbackRef.current.checkValidity()) {- onValueChangeEnd?.(Number(newValue));+ const validation = validateInputDraggerValue({+ max: _max,+ min: _min,+ step: deriveStep,+ value: newValue,+ });++ if (validation.valid) {+ fallbackRef.current.setCustomValidity('');+ onValueChangeEnd?.(validation.value);setInputFallback(false);} else {+ fallbackRef.current.setCustomValidity(validation.message);fallbackRef.current.reportValidity();}- }, [onEscape, onValueChangeEnd]);+ }, [_max, _min, deriveStep, onEscape, onValueChangeEnd]);++ const onInputKeyDown: React.KeyboardEventHandler<HTMLInputElement> =+ useCallback(+ (e) => {+ if (e.key === 'Enter') {+ fallbackRef.current?.blur();+ return;+ }- const onKeyPress: React.KeyboardEventHandler<HTMLInputElement> = useCallback(- (e) => {- if (e.key === 'Enter') {- fallbackRef.current?.blur();- }- },- [],- );+ if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') {+ return;+ }++ e.preventDefault();+ const parsedInputValue = parseInputDraggerNumber(e.currentTarget.value);+ const currentValue =+ parsedInputValue ??+ deriveInputDraggerDragStartValue({+ min: _min,+ value,+ });+ const nextValue = deriveInputDraggerArrowValue({+ direction: e.key === 'ArrowUp' ? 1 : -1,+ max: _max,+ min: _min,+ step: deriveStep,+ value: currentValue,+ });++ e.currentTarget.value = String(nextValue);+ e.currentTarget.setCustomValidity('');+ onValueChange(nextValue);+ },+ [_max, _min, deriveStep, onValueChange, value],+ );const roundToStep = (val: number, stepSize: number) => {const factor = 1 / stepSize;@@ -356,21 +549,13 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<}}, [inputFallback]);- const deriveStep = useMemo(() => {- return deriveInputDraggerStep({- min: _min,- snapToStep,- step: _step,- });- }, [_min, _step, snapToStep]);-if (inputFallback) {return (<HigherZIndex onEscape={onEscape} onOutsideClick={noop}><RemotionInputref={fallbackRef}autoFocus- onKeyPress={onKeyPress}+ onKeyDown={onInputKeyDown}onBlur={onBlur}onChange={onInputChange}min={_min}@@ -378,10 +563,10 @@ const InputDraggerForwardRefFn: React.ForwardRefRenderFunction<step={deriveStep}defaultValue={value}status={status}- pattern={'[0-9]*[.]?[0-9]*'}rightAlign={rightAlign}small={small}{...props}+ type="text"/></HigherZIndex>);diff --git a/packages/studio/src/test/input-dragger.test.ts b/packages/studio/src/test/input-dragger.test.tsindex 7934afdd01..a7eb02be83 100644--- a/packages/studio/src/test/input-dragger.test.ts+++ b/packages/studio/src/test/input-dragger.test.ts@@ -1,9 +1,13 @@import {expect, test} from 'bun:test';import {+ deriveInputDraggerArrowValue,deriveInputDraggerDragStartValue,deriveInputDraggerStep,deriveInputDraggerValueDiff,+ isInputDraggerValueAlignedToStep,isInputDraggerValueInRange,+ parseInputDraggerNumber,+ validateInputDraggerValue,} from '../components/NewComposition/InputDragger';test('drag sensitivity scales the value change', () => {@@ -89,3 +93,98 @@ test('live input values must be within the configured range', () => {}),).toBe(false);});++test('text input values are parsed as finite decimal numbers', () => {+ expect(parseInputDraggerNumber('-12.5')).toBe(-12.5);+ expect(parseInputDraggerNumber('.5')).toBe(0.5);+ expect(parseInputDraggerNumber('1e3')).toBe(1000);+ expect(parseInputDraggerNumber(' 20 ')).toBe(20);+ expect(parseInputDraggerNumber('')).toBeNull();+ expect(parseInputDraggerNumber('Infinity')).toBeNull();+ expect(parseInputDraggerNumber('0x10')).toBeNull();+ expect(parseInputDraggerNumber('12px')).toBeNull();+});++test('text input values retain range and step validation', () => {+ expect(+ validateInputDraggerValue({+ max: 10,+ min: 0,+ step: 0.5,+ value: '2.5',+ }),+ ).toEqual({valid: true, value: 2.5});+ expect(+ validateInputDraggerValue({+ max: 10,+ min: 0,+ step: 0.5,+ value: '10.5',+ }).valid,+ ).toBe(false);+ expect(+ validateInputDraggerValue({+ max: 10,+ min: 0,+ step: 0.5,+ value: '2.25',+ }).valid,+ ).toBe(false);+ expect(+ validateInputDraggerValue({+ max: Infinity,+ min: -Infinity,+ step: 'any',+ value: '2.25',+ }),+ ).toEqual({valid: true, value: 2.25});+});++test('step validation tolerates floating point imprecision', () => {+ expect(+ isInputDraggerValueAlignedToStep({+ min: 0,+ step: 0.1,+ value: 0.1 + 0.2,+ }),+ ).toBe(true);+});++test('arrow keys step values and respect bounds', () => {+ expect(+ deriveInputDraggerArrowValue({+ direction: 1,+ max: 1,+ min: 0,+ step: 0.1,+ value: 0.2,+ }),+ ).toBe(0.3);+ expect(+ deriveInputDraggerArrowValue({+ direction: -1,+ max: 1,+ min: 0,+ step: 0.1,+ value: 0,+ }),+ ).toBe(0);+ expect(+ deriveInputDraggerArrowValue({+ direction: 1,+ max: 1,+ min: 0,+ step: 'any',+ value: 0.5,+ }),+ ).toBe(1);+ expect(+ deriveInputDraggerArrowValue({+ direction: 1,+ max: Infinity,+ min: -Infinity,+ step: 1e-16,+ value: 0,+ }),+ ).toBe(1e-16);+});