Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Add outline edge scale dragging (#8061)

Jonny Burger3e5e5f24825a
diff --git a/packages/studio-server/src/test/update-keyframes.test.ts b/packages/studio-server/src/test/update-keyframes.test.ts
index 9c100926ac..b054c7d537 100644
--- a/packages/studio-server/src/test/update-keyframes.test.ts
+++ b/packages/studio-server/src/test/update-keyframes.test.ts
@@ -1,5 +1,6 @@
import {expect, test} from 'bun:test';
import type {SequenceSchema} from 'remotion';
+import {NoReactInternals} from 'remotion/no-react';
import {
updateEffectKeyframesAst,
updateSequenceKeyframes,
@@ -188,6 +189,37 @@ test('updateSequenceKeyframes converts a static value to a single-keyframe inter
expect(output).toContain("extrapolateRight: 'clamp'");
});
+test('updateSequenceKeyframes adds a missing nested prop before keyframing it', async () => {
+ const input = `import React from 'react';
+import {AbsoluteFill} from 'remotion';
+
+export const Example: React.FC = () => {
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<div style={{opacity: 0.5}} />
+\t\t</AbsoluteFill>
+\t);
+};
+`;
+ const {output, oldValueStrings} = await updateSequenceKeyframes({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ schema: NoReactInternals.sequenceSchema,
+ updates: [
+ {
+ key: 'style.scale',
+ operation: {type: 'add', frame: 30, value: 2},
+ },
+ ],
+ });
+
+ expect(oldValueStrings).toEqual(['1']);
+ expect(output).toContain('opacity: 0.5');
+ expect(output).toContain('scale: interpolate(frame, [30], [2], {');
+ expect(output).toContain("extrapolateLeft: 'clamp'");
+ expect(output).toContain("extrapolateRight: 'clamp'");
+});
+
test('updateSequenceKeyframes adds a keyframe to an existing color interpolation', async () => {
const {output, oldValueStrings} = await updateSequenceKeyframes({
input: colorInput,
diff --git a/packages/studio/src/components/Editor.tsx b/packages/studio/src/components/Editor.tsx
index 417dfa66e5..5d528692a3 100644
--- a/packages/studio/src/components/Editor.tsx
+++ b/packages/studio/src/components/Editor.tsx
@@ -5,6 +5,7 @@ import {Internals} from 'remotion';
import {BACKGROUND} from '../helpers/colors';
import {noop} from '../helpers/noop';
import {drawRef} from '../state/canvas-ref';
+import {ScaleLockProvider} from '../state/scale-lock';
import {TimelineZoomContext} from '../state/timeline-zoom';
import {HigherZIndex} from '../state/z-index';
import {EditorContent} from './EditorContent';
@@ -85,29 +86,31 @@ export const Editor: React.FC<{
<SequencePropsSubscriptionProvider>
<Internals.CurrentScaleContext.Provider value={value}>
<ForceSpecificCursor />
- <div style={background}>
- <Internals.CompositionRenderErrorContext.Provider
- value={compositionRenderErrorContextValue}
- >
- {canvasMounted ? <MemoRoot /> : null}
- </Internals.CompositionRenderErrorContext.Provider>
- <Internals.CanUseRemotionHooksProvider>
- <RenderErrorContext.Provider value={renderErrorContextValue}>
- <EditorContent readOnlyStudio={readOnlyStudio}>
- <TopPanel
- drawRef={drawRef}
- size={size}
- bufferStateDelayInMilliseconds={
- BUFFER_STATE_DELAY_IN_MILLISECONDS
- }
- onMounted={onMounted}
- readOnlyStudio={readOnlyStudio}
- />
- </EditorContent>
- </RenderErrorContext.Provider>
- <GlobalKeybindings />
- </Internals.CanUseRemotionHooksProvider>
- </div>
+ <ScaleLockProvider>
+ <div style={background}>
+ <Internals.CompositionRenderErrorContext.Provider
+ value={compositionRenderErrorContextValue}
+ >
+ {canvasMounted ? <MemoRoot /> : null}
+ </Internals.CompositionRenderErrorContext.Provider>
+ <Internals.CanUseRemotionHooksProvider>
+ <RenderErrorContext.Provider value={renderErrorContextValue}>
+ <EditorContent readOnlyStudio={readOnlyStudio}>
+ <TopPanel
+ drawRef={drawRef}
+ size={size}
+ bufferStateDelayInMilliseconds={
+ BUFFER_STATE_DELAY_IN_MILLISECONDS
+ }
+ onMounted={onMounted}
+ readOnlyStudio={readOnlyStudio}
+ />
+ </EditorContent>
+ </RenderErrorContext.Provider>
+ <GlobalKeybindings />
+ </Internals.CanUseRemotionHooksProvider>
+ </div>
+ </ScaleLockProvider>
</Internals.CurrentScaleContext.Provider>
<Modals readOnlyStudio={readOnlyStudio} />
<NotificationCenter />
diff --git a/packages/studio/src/components/SelectedOutlineOverlay.tsx b/packages/studio/src/components/SelectedOutlineOverlay.tsx
index 9eec4a97aa..1ffd77f3b3 100644
--- a/packages/studio/src/components/SelectedOutlineOverlay.tsx
+++ b/packages/studio/src/components/SelectedOutlineOverlay.tsx
@@ -10,11 +10,13 @@ import type {
TSequence,
} from 'remotion';
import {Internals} from 'remotion';
+import {NoReactInternals} from 'remotion/no-react';
import {calculateTimeline} from '../helpers/calculate-timeline';
import {StudioServerConnectionCtx} from '../helpers/client-id';
import {BLUE} from '../helpers/colors';
import {getBoxQuadsPonyfill} from '../helpers/get-box-quads-ponyfill';
import type {SequenceNodePathInfo} from '../helpers/get-timeline-sequence-sort-key';
+import {ScaleLockContext} from '../state/scale-lock';
import {showNotification} from './Notifications/NotificationCenter';
import {saveEffectProp} from './Timeline/save-effect-prop';
import {saveSequenceProps} from './Timeline/save-sequence-prop';
@@ -23,6 +25,7 @@ import {
parseTranslate,
serializeTranslate,
} from './Timeline/timeline-translate-utils';
+import {getLinkedScale} from './Timeline/TimelineScaleField';
import {
ENABLE_OUTLINES,
getTimelineSequenceSelectionKey,
@@ -68,6 +71,7 @@ type SelectedOutlineTarget = {
readonly key: string;
readonly ref: React.RefObject<HTMLElement | null>;
readonly drag: SelectedOutlineDragTarget | null;
+ readonly scaleDrag: SelectedOutlineScaleDragTarget | null;
readonly uvHandles: readonly SelectedOutlineUvHandle[];
};
@@ -79,6 +83,18 @@ type SelectedOutlineDragTarget = {
readonly schema: SequenceSchema;
};
+type ScaleFieldSchema = Extract<SequenceFieldSchema, {type: 'scale'}>;
+
+type SelectedOutlineScaleDragTarget = {
+ readonly codeValue: CanUpdateSequencePropStatusStatic;
+ readonly clientId: string;
+ readonly fieldDefault: number | string | undefined;
+ readonly fieldSchema: ScaleFieldSchema;
+ readonly linked: boolean;
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly schema: SequenceSchema;
+};
+
export type SelectedOutlineDragState = {
readonly defaultValue: string | null;
readonly key: string;
@@ -87,6 +103,15 @@ export type SelectedOutlineDragState = {
readonly target: SelectedOutlineDragTarget;
};
+export type SelectedOutlineScaleDragState = {
+ readonly defaultValue: string | null;
+ readonly key: string;
+ readonly startX: number;
+ readonly startY: number;
+ readonly startZ: number;
+ readonly target: SelectedOutlineScaleDragTarget;
+};
+
type SequenceWithSelectedOutline = {
readonly key: string;
readonly nodePathInfo: SequenceNodePathInfo;
@@ -94,6 +119,7 @@ type SequenceWithSelectedOutline = {
};
const translateFieldKey = 'style.translate';
+const scaleFieldKey = 'style.scale';
const outlineContainer: React.CSSProperties = {
position: 'absolute',
@@ -139,6 +165,18 @@ const mixPoint = (
};
};
+const midpoint = (from: OutlinePoint, to: OutlinePoint): OutlinePoint => {
+ return mixPoint(from, to, 0.5);
+};
+
+const dot = (left: OutlinePoint, right: OutlinePoint): number => {
+ return left.x * right.x + left.y * right.y;
+};
+
+const vectorLength = (vector: OutlinePoint): number => {
+ return Math.hypot(vector.x, vector.y);
+};
+
const getBilinearUvHandlePosition = (
points: SelectedOutline['points'],
uv: UvCoordinate,
@@ -697,6 +735,162 @@ export const getSelectedOutlineDragChanges = ({
});
};
+export type SelectedOutlineScaleEdge = 'top' | 'right' | 'bottom' | 'left';
+
+type SelectedOutlineScaleEdgeInfo = {
+ readonly axis: 'x' | 'y';
+ readonly cursor: React.CSSProperties['cursor'];
+ readonly end: OutlinePoint;
+ readonly extent: number;
+ readonly normal: OutlinePoint;
+ readonly start: OutlinePoint;
+};
+
+export const getSelectedOutlineScaleEdgeInfo = (
+ points: SelectedOutline['points'],
+ edge: SelectedOutlineScaleEdge,
+): SelectedOutlineScaleEdgeInfo | null => {
+ const [tl, tr, br, bl] = points;
+ const edgePoints = {
+ top: {start: tl, end: tr, oppositeStart: bl, oppositeEnd: br},
+ right: {start: tr, end: br, oppositeStart: tl, oppositeEnd: bl},
+ bottom: {start: bl, end: br, oppositeStart: tl, oppositeEnd: tr},
+ left: {start: tl, end: bl, oppositeStart: tr, oppositeEnd: br},
+ }[edge];
+ const edgeMidpoint = midpoint(edgePoints.start, edgePoints.end);
+ const oppositeMidpoint = midpoint(
+ edgePoints.oppositeStart,
+ edgePoints.oppositeEnd,
+ );
+ const outward = vectorBetween(oppositeMidpoint, edgeMidpoint);
+ const length = vectorLength(outward);
+
+ if (length < 0.001) {
+ return null;
+ }
+
+ return {
+ axis: edge === 'left' || edge === 'right' ? 'x' : 'y',
+ cursor: edge === 'left' || edge === 'right' ? 'ew-resize' : 'ns-resize',
+ end: edgePoints.end,
+ extent: length,
+ normal: {x: outward.x / length, y: outward.y / length},
+ start: edgePoints.start,
+ };
+};
+
+export const getSelectedOutlineScaleDragStates = ({
+ dragTargets,
+ getDragOverrides,
+}: {
+ readonly dragTargets: readonly SelectedOutlineScaleDragTarget[];
+ readonly getDragOverrides: (
+ nodePath: SequencePropsSubscriptionKey,
+ ) => Record<string, unknown>;
+}): SelectedOutlineScaleDragState[] => {
+ return dragTargets.map((target) => {
+ const dragOverrideValue = (getDragOverrides(target.nodePath) ?? {})[
+ scaleFieldKey
+ ];
+ const effectiveValue = Internals.getEffectiveVisualModeValue({
+ codeValue: target.codeValue,
+ dragOverrideValue,
+ defaultValue: target.fieldDefault,
+ shouldResortToDefaultValueIfUndefined: true,
+ });
+ const [startX, startY, startZ] =
+ NoReactInternals.parseScaleValue(effectiveValue);
+
+ return {
+ defaultValue:
+ target.fieldDefault !== undefined
+ ? JSON.stringify(target.fieldDefault)
+ : null,
+ key: Internals.makeSequencePropsSubscriptionKey(target.nodePath),
+ startX,
+ startY,
+ startZ,
+ target,
+ };
+ });
+};
+
+export const getSelectedOutlineScaleDragValues = ({
+ axis,
+ dragStates,
+ scaleFactor,
+}: {
+ readonly axis: 'x' | 'y';
+ readonly dragStates: readonly SelectedOutlineScaleDragState[];
+ readonly scaleFactor: number;
+}): Map<string, number | string> => {
+ return new Map(
+ dragStates.map((dragState) => {
+ const min = dragState.target.fieldSchema.min ?? -Infinity;
+ const max = dragState.target.fieldSchema.max ?? Infinity;
+ const baseX = dragState.startX;
+ const baseY = dragState.startY;
+ const newValue = (axis === 'x' ? baseX : baseY) * scaleFactor;
+ const [x, y] = dragState.target.linked
+ ? getLinkedScale({
+ axis,
+ newValue,
+ baseX,
+ baseY,
+ min,
+ max,
+ })
+ : axis === 'x'
+ ? [clamp(newValue, min, max), baseY]
+ : [baseX, clamp(newValue, min, max)];
+
+ return [
+ dragState.key,
+ NoReactInternals.serializeScaleValue([x, y, dragState.startZ]),
+ ];
+ }),
+ );
+};
+
+export const getSelectedOutlineScaleDragChanges = ({
+ dragStates,
+ lastValues,
+}: {
+ readonly dragStates: readonly SelectedOutlineScaleDragState[];
+ readonly lastValues: ReadonlyMap<string, number | string>;
+}) => {
+ return dragStates.flatMap((dragState) => {
+ const value = lastValues.get(dragState.key);
+ if (value === undefined) {
+ return [];
+ }
+
+ const stringifiedValue = JSON.stringify(value);
+ const shouldSave =
+ stringifiedValue !==
+ JSON.stringify(dragState.target.codeValue.codeValue) &&
+ !(
+ dragState.defaultValue === stringifiedValue &&
+ dragState.target.codeValue.codeValue === undefined
+ );
+
+ if (!shouldSave) {
+ return [];
+ }
+
+ return [
+ {
+ fileName: dragState.target.nodePath.absolutePath,
+ nodePath: dragState.target.nodePath,
+ fieldKey: scaleFieldKey,
+ value,
+ defaultValue: dragState.defaultValue,
+ schema: dragState.target.schema,
+ },
+ ];
+ });
+};
+
const clearSelectedOutlineDragOverrides = ({
clearDragOverrides,
dragStates,
@@ -709,6 +903,18 @@ const clearSelectedOutlineDragOverrides = ({
}
};
+const clearSelectedOutlineScaleDragOverrides = ({
+ clearDragOverrides,
+ dragStates,
+}: {
+ readonly clearDragOverrides: (nodePath: SequencePropsSubscriptionKey) => void;
+ readonly dragStates: readonly SelectedOutlineScaleDragState[];
+}) => {
+ for (const dragState of dragStates) {
+ clearDragOverrides(dragState.target.nodePath);
+ }
+};
+
const SelectedOutlinePolygon: React.FC<{
readonly allDragTargets: readonly SelectedOutlineDragTarget[];
readonly outline: SelectedOutline;
@@ -825,6 +1031,146 @@ const SelectedOutlinePolygon: React.FC<{
);
};
+const SelectedOutlineScaleEdgeLine: React.FC<{
+ readonly allScaleDragTargets: readonly SelectedOutlineScaleDragTarget[];
+ readonly edge: SelectedOutlineScaleEdge;
+ readonly outline: SelectedOutline;
+ readonly target: SelectedOutlineTarget | undefined;
+}> = ({allScaleDragTargets, edge, outline, target}) => {
+ const {getDragOverrides} = useContext(
+ Internals.VisualModeDragOverridesContext,
+ );
+ const {setCodeValues, setDragOverrides, clearDragOverrides} = useContext(
+ Internals.VisualModeSettersContext,
+ );
+ const scaleDrag = target?.scaleDrag ?? null;
+ const edgeInfo = useMemo(
+ () => getSelectedOutlineScaleEdgeInfo(outline.points, edge),
+ [edge, outline.points],
+ );
+
+ const onPointerDown = React.useCallback(
+ (event: React.PointerEvent<SVGLineElement>) => {
+ if (event.button !== 0 || scaleDrag === null || edgeInfo === null) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ const startPointer = {x: event.clientX, y: event.clientY};
+ const dragStates = getSelectedOutlineScaleDragStates({
+ dragTargets: allScaleDragTargets,
+ getDragOverrides,
+ });
+ let lastValues = new Map<string, number | string>();
+
+ const onPointerMove = (moveEvent: PointerEvent) => {
+ moveEvent.preventDefault();
+
+ const delta = {
+ x: moveEvent.clientX - startPointer.x,
+ y: moveEvent.clientY - startPointer.y,
+ };
+ const projectedDelta = dot(delta, edgeInfo.normal);
+ const scaleFactor = Math.max(
+ 0.001,
+ 1 + projectedDelta / edgeInfo.extent,
+ );
+
+ lastValues = getSelectedOutlineScaleDragValues({
+ dragStates,
+ axis: edgeInfo.axis,
+ scaleFactor,
+ });
+
+ for (const dragState of dragStates) {
+ const value = lastValues.get(dragState.key);
+ if (value === undefined) {
+ throw new Error('Expected scale drag value to be available');
+ }
+
+ setDragOverrides(dragState.target.nodePath, scaleFieldKey, value);
+ }
+ };
+
+ const onPointerUp = () => {
+ window.removeEventListener('pointermove', onPointerMove);
+ window.removeEventListener('pointerup', onPointerUp);
+ window.removeEventListener('pointercancel', onPointerUp);
+
+ const changes = getSelectedOutlineScaleDragChanges({
+ dragStates,
+ lastValues,
+ });
+
+ if (changes.length === 0) {
+ clearSelectedOutlineScaleDragOverrides({
+ clearDragOverrides,
+ dragStates,
+ });
+ return;
+ }
+
+ saveSequenceProps({
+ changes,
+ setCodeValues,
+ clientId: scaleDrag.clientId,
+ undoLabel: changes.length > 1 ? 'Scale selected sequences' : null,
+ redoLabel:
+ changes.length > 1 ? 'Scale selected sequences back' : null,
+ })
+ .catch((err) => {
+ showNotification(
+ `Could not save sequence props: ${
+ err instanceof Error ? err.message : String(err)
+ }`,
+ 4000,
+ );
+ })
+ .finally(() => {
+ clearSelectedOutlineScaleDragOverrides({
+ clearDragOverrides,
+ dragStates,
+ });
+ });
+ };
+
+ window.addEventListener('pointermove', onPointerMove);
+ window.addEventListener('pointerup', onPointerUp);
+ window.addEventListener('pointercancel', onPointerUp);
+ },
+ [
+ allScaleDragTargets,
+ clearDragOverrides,
+ edgeInfo,
+ getDragOverrides,
+ scaleDrag,
+ setCodeValues,
+ setDragOverrides,
+ ],
+ );
+
+ if (scaleDrag === null || edgeInfo === null) {
+ return null;
+ }
+
+ return (
+ <line
+ x1={edgeInfo.start.x}
+ y1={edgeInfo.start.y}
+ x2={edgeInfo.end.x}
+ y2={edgeInfo.end.y}
+ stroke="transparent"
+ strokeWidth={12}
+ vectorEffect="non-scaling-stroke"
+ pointerEvents="stroke"
+ cursor={edgeInfo.cursor}
+ onPointerDown={onPointerDown}
+ />
+ );
+};
+
const getSvgPointFromPointerEvent = ({
event,
rect,
@@ -971,9 +1317,10 @@ export const SelectedOutlineOverlay: React.FC<{
const {overrideIdToNodePathMappings} = useContext(
Internals.OverrideIdsToNodePathsGettersContext,
);
- const {getEffectDragOverrides} = useContext(
+ const {getDragOverrides, getEffectDragOverrides} = useContext(
Internals.VisualModeDragOverridesContext,
);
+ const {getScaleLockState} = useContext(ScaleLockContext);
const [outlines, setOutlines] = useState<readonly SelectedOutline[]>([]);
const overlayRef = useRef<SVGSVGElement>(null);
@@ -1004,11 +1351,20 @@ export const SelectedOutlineOverlay: React.FC<{
const codeValue = Internals.getCodeValuesCtx(codeValues, nodePath)?.[
translateFieldKey
];
+ const scaleFieldSchema = controls?.schema[scaleFieldKey];
+ const scaleCodeValue = Internals.getCodeValuesCtx(codeValues, nodePath)?.[
+ scaleFieldKey
+ ];
const canDrag =
previewServerState.type === 'connected' &&
controls !== null &&
fieldSchema?.type === 'translate' &&
codeValue?.status === 'static';
+ const canScaleDrag =
+ previewServerState.type === 'connected' &&
+ controls !== null &&
+ scaleFieldSchema?.type === 'scale' &&
+ scaleCodeValue?.status === 'static';
return {
key,
@@ -1022,6 +1378,34 @@ export const SelectedOutlineOverlay: React.FC<{
schema: controls.schema,
}
: null,
+ scaleDrag: canScaleDrag
+ ? {
+ codeValue: scaleCodeValue,
+ clientId: previewServerState.clientId,
+ fieldDefault: scaleFieldSchema.default,
+ fieldSchema: scaleFieldSchema,
+ linked: getScaleLockState({
+ nodePath,
+ fieldKey: scaleFieldKey,
+ defaultValue: (() => {
+ const dragOverrideValue = (getDragOverrides(nodePath) ?? {})[
+ scaleFieldKey
+ ];
+ const effectiveValue = Internals.getEffectiveVisualModeValue({
+ codeValue: scaleCodeValue,
+ dragOverrideValue,
+ defaultValue: scaleFieldSchema.default,
+ shouldResortToDefaultValueIfUndefined: true,
+ });
+ const [x, y] =
+ NoReactInternals.parseScaleValue(effectiveValue);
+ return x === y;
+ })(),
+ }),
+ nodePath,
+ schema: controls.schema,
+ }
+ : null,
uvHandles: getSelectedUvHandles({
codeValues,
clientId,
@@ -1034,7 +1418,9 @@ export const SelectedOutlineOverlay: React.FC<{
});
}, [
codeValues,
+ getDragOverrides,
getEffectDragOverrides,
+ getScaleLockState,
overrideIdToNodePathMappings,
previewServerState,
selectedItems,
@@ -1051,6 +1437,11 @@ export const SelectedOutlineOverlay: React.FC<{
target.drag === null ? [] : [target.drag],
);
}, [selectedOutlineTargets]);
+ const allScaleDragTargets = useMemo(() => {
+ return selectedOutlineTargets.flatMap((target) =>
+ target.scaleDrag === null ? [] : [target.scaleDrag],
+ );
+ }, [selectedOutlineTargets]);
useEffect(() => {
if (selectedOutlineTargets.length === 0) {
@@ -1107,6 +1498,15 @@ export const SelectedOutlineOverlay: React.FC<{
scale={scale}
target={targetsByKey.get(outline.key)}
/>
+ {(['top', 'right', 'bottom', 'left'] as const).map((edge) => (
+ <SelectedOutlineScaleEdgeLine
+ key={edge}
+ allScaleDragTargets={allScaleDragTargets}
+ edge={edge}
+ outline={outline}
+ target={targetsByKey.get(outline.key)}
+ />
+ ))}
{targetsByKey.get(outline.key)?.uvHandles.map((handle) => (
<SelectedUvHandleCircle
key={`${handle.effectIndex}-${handle.fieldKey}`}
diff --git a/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx b/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx
index 7d20752455..36708d7103 100644
--- a/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx
@@ -161,6 +161,10 @@ const Value: React.FC<{
],
);
+ if (field.fieldSchema.type === 'scale') {
+ throw new Error(`Effects do not support scale fields: ${field.key}`);
+ }
+
if (effectStatus.type === 'cannot-update-effect') {
if (effectStatus.reason === 'computed') {
return <UnsupportedStatus label="computed" />;
@@ -203,6 +207,7 @@ const Value: React.FC<{
field={field}
propStatus={propStatus}
keyframeDisplayOffset={keyframeDisplayOffset}
+ scaleLockNodePath={nodePath}
/>
);
}
@@ -226,6 +231,7 @@ const Value: React.FC<{
onDragValueChange={onDragValueChange}
onDragEnd={onDragEnd}
effectiveValue={effectiveValue}
+ scaleLockNodePath={null}
/>
);
};
diff --git a/packages/studio/src/components/Timeline/TimelineKeyframedValue.tsx b/packages/studio/src/components/Timeline/TimelineKeyframedValue.tsx
index a673c9d859..b6047a97c3 100644
--- a/packages/studio/src/components/Timeline/TimelineKeyframedValue.tsx
+++ b/packages/studio/src/components/Timeline/TimelineKeyframedValue.tsx
@@ -2,6 +2,7 @@ import React, {useMemo} from 'react';
import type {
CanUpdateSequencePropStatusKeyframed,
CanUpdateSequencePropStatusStatic,
+ SequencePropsSubscriptionKey,
} from 'remotion';
import {Internals} from 'remotion';
import type {SchemaFieldInfo} from '../../helpers/timeline-layout';
@@ -19,7 +20,8 @@ export const TimelineKeyframedValue: React.FC<{
readonly field: SchemaFieldInfo;
readonly propStatus: CanUpdateSequencePropStatusKeyframed;
readonly keyframeDisplayOffset: number;
-}> = ({field, propStatus, keyframeDisplayOffset}) => {
+ readonly scaleLockNodePath: SequencePropsSubscriptionKey;
+}> = ({field, propStatus, keyframeDisplayOffset, scaleLockNodePath}) => {
const timelinePosition = Internals.Timeline.useTimelinePosition();
const jsxFrame = timelinePosition - keyframeDisplayOffset;
@@ -56,6 +58,7 @@ export const TimelineKeyframedValue: React.FC<{
onSave={noopAsync}
onDragValueChange={noop}
onDragEnd={noop}
+ scaleLockNodePath={scaleLockNodePath}
/>
</div>
);
diff --git a/packages/studio/src/components/Timeline/TimelineScaleField.tsx b/packages/studio/src/components/Timeline/TimelineScaleField.tsx
index 4ec59988ca..823835aad4 100644
--- a/packages/studio/src/components/Timeline/TimelineScaleField.tsx
+++ b/packages/studio/src/components/Timeline/TimelineScaleField.tsx
@@ -1,5 +1,8 @@
-import React, {useCallback, useMemo, useRef, useState} from 'react';
-import type {CanUpdateSequencePropStatusStatic} from 'remotion';
+import React, {useCallback, useContext, useMemo, useRef, useState} from 'react';
+import type {
+ CanUpdateSequencePropStatusStatic,
+ SequencePropsSubscriptionKey,
+} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
import {LIGHT_COLOR} from '../../helpers/colors';
import type {
@@ -7,6 +10,7 @@ import type {
TimelineFieldOnDragValueChange,
TimelineFieldOnSave,
} from '../../helpers/timeline-layout';
+import {ScaleLockContext} from '../../state/scale-lock';
import {InputDragger} from '../NewComposition/InputDragger';
import {
getDecimalPlaces,
@@ -52,7 +56,7 @@ const clamp = (value: number, min: number, max: number): number => {
return Math.min(max, Math.max(min, value));
};
-const getLinkedScale = ({
+export const getLinkedScale = ({
axis,
newValue,
baseX,
@@ -146,6 +150,7 @@ export const TimelineScaleField: React.FC<{
readonly onSave: TimelineFieldOnSave;
readonly onDragValueChange: TimelineFieldOnDragValueChange;
readonly onDragEnd: () => void;
+ readonly scaleLockNodePath: SequencePropsSubscriptionKey;
}> = ({
field,
propStatus,
@@ -153,17 +158,24 @@ export const TimelineScaleField: React.FC<{
onSave,
onDragValueChange,
onDragEnd,
+ scaleLockNodePath,
}) => {
const [dragX, setDragX] = useState<number | null>(null);
const [dragY, setDragY] = useState<number | null>(null);
const dragStartRef = useRef<readonly [number, number] | null>(null);
+ const {getScaleLockState, setScaleLockState} = useContext(ScaleLockContext);
const [codeX, codeY, codeZ] = useMemo(
() => NoReactInternals.parseScaleValue(effectiveValue),
[effectiveValue],
);
- const [linked, setLinked] = useState(() => codeX === codeY);
+ const defaultLinked = codeX === codeY;
+ const linked = getScaleLockState({
+ nodePath: scaleLockNodePath,
+ fieldKey: field.key,
+ defaultValue: defaultLinked,
+ });
const step =
field.fieldSchema.type === 'scale'
@@ -417,8 +429,12 @@ export const TimelineScaleField: React.FC<{
);
const onToggleLink = useCallback(() => {
- setLinked((current) => !current);
- }, []);
+ setScaleLockState({
+ nodePath: scaleLockNodePath,
+ fieldKey: field.key,
+ linked: !linked,
+ });
+ }, [field.key, linked, scaleLockNodePath, setScaleLockState]);
return (
<span style={containerStyle}>
diff --git a/packages/studio/src/components/Timeline/TimelineSchemaField.tsx b/packages/studio/src/components/Timeline/TimelineSchemaField.tsx
index e7b1c00172..f60180ecad 100644
--- a/packages/studio/src/components/Timeline/TimelineSchemaField.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSchemaField.tsx
@@ -2,6 +2,7 @@ import React from 'react';
import type {
CanUpdateSequencePropStatusFalse,
CanUpdateSequencePropStatusStatic,
+ SequencePropsSubscriptionKey,
} from 'remotion';
import type {
SchemaFieldInfo,
@@ -53,6 +54,7 @@ export const TimelineFieldValue: React.FC<{
readonly onDragEnd: () => void;
readonly propStatus: CanUpdateSequencePropStatusStatic;
readonly effectiveValue: unknown;
+ readonly scaleLockNodePath: SequencePropsSubscriptionKey | null;
}> = ({
field,
onSave,
@@ -60,6 +62,7 @@ export const TimelineFieldValue: React.FC<{
onDragEnd,
propStatus,
effectiveValue,
+ scaleLockNodePath,
}) => {
if (field.typeName === 'number') {
return (
@@ -110,6 +113,10 @@ export const TimelineFieldValue: React.FC<{
}
if (field.typeName === 'scale') {
+ if (scaleLockNodePath === null) {
+ throw new Error('Expected scale lock node path for scale field');
+ }
+
return (
<span>
<TimelineScaleField
@@ -119,6 +126,7 @@ export const TimelineFieldValue: React.FC<{
onSave={onSave}
onDragValueChange={onDragValueChange}
onDragEnd={onDragEnd}
+ scaleLockNodePath={scaleLockNodePath}
/>
</span>
);
diff --git a/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx b/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
index 3eaaca6a64..1443b28e25 100644
--- a/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
@@ -149,6 +149,7 @@ const Value: React.FC<{
onDragValueChange={onDragValueChange}
onDragEnd={onDragEnd}
effectiveValue={effectiveValue}
+ scaleLockNodePath={nodePath}
/>
);
};
@@ -318,6 +319,7 @@ export const TimelineSequencePropItem: React.FC<{
field={field}
propStatus={codeValue}
keyframeDisplayOffset={keyframeDisplayOffset}
+ scaleLockNodePath={nodePath}
/>
</div>
) : codeValue.status === 'static' ? (
diff --git a/packages/studio/src/state/scale-lock.tsx b/packages/studio/src/state/scale-lock.tsx
new file mode 100644
index 0000000000..659763a08d
--- /dev/null
+++ b/packages/studio/src/state/scale-lock.tsx
@@ -0,0 +1,71 @@
+import React, {useCallback, useMemo, useState} from 'react';
+import type {SequencePropsSubscriptionKey} from 'remotion';
+import {Internals} from 'remotion';
+
+const makeScaleLockKey = ({
+ fieldKey,
+ nodePath,
+}: {
+ readonly fieldKey: string;
+ readonly nodePath: SequencePropsSubscriptionKey;
+}) => `${Internals.makeSequencePropsSubscriptionKey(nodePath)}.${fieldKey}`;
+
+export type ScaleLockContextValue = {
+ readonly getScaleLockState: ({
+ defaultValue,
+ fieldKey,
+ nodePath,
+ }: {
+ readonly defaultValue: boolean;
+ readonly fieldKey: string;
+ readonly nodePath: SequencePropsSubscriptionKey;
+ }) => boolean;
+ readonly setScaleLockState: ({
+ fieldKey,
+ linked,
+ nodePath,
+ }: {
+ readonly fieldKey: string;
+ readonly linked: boolean;
+ readonly nodePath: SequencePropsSubscriptionKey;
+ }) => void;
+};
+
+export const ScaleLockContext = React.createContext<ScaleLockContextValue>({
+ getScaleLockState: ({defaultValue}) => defaultValue,
+ setScaleLockState: () => undefined,
+});
+
+export const ScaleLockProvider: React.FC<{
+ readonly children: React.ReactNode;
+}> = ({children}) => {
+ const [states, setStates] = useState<Record<string, boolean>>({});
+
+ const getScaleLockState = useCallback<
+ ScaleLockContextValue['getScaleLockState']
+ >(
+ ({defaultValue, fieldKey, nodePath}) => {
+ const key = makeScaleLockKey({fieldKey, nodePath});
+ return states[key] ?? defaultValue;
+ },
+ [states],
+ );
+
+ const setScaleLockState = useCallback<
+ ScaleLockContextValue['setScaleLockState']
+ >(({fieldKey, linked, nodePath}) => {
+ const key = makeScaleLockKey({fieldKey, nodePath});
+ setStates((current) => ({...current, [key]: linked}));
+ }, []);
+
+ const value = useMemo(
+ () => ({getScaleLockState, setScaleLockState}),
+ [getScaleLockState, setScaleLockState],
+ );
+
+ return (
+ <ScaleLockContext.Provider value={value}>
+ {children}
+ </ScaleLockContext.Provider>
+ );
+};
diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.ts
index 1c239f69ed..2330078df9 100644
--- a/packages/studio/src/test/timeline-selection.test.ts
+++ b/packages/studio/src/test/timeline-selection.test.ts
@@ -11,9 +11,13 @@ import {
getSelectedEffectFieldsBySequenceKey,
getSelectedOutlineDragChanges,
getSelectedOutlineDragValues,
+ getSelectedOutlineScaleDragChanges,
+ getSelectedOutlineScaleDragValues,
+ getSelectedOutlineScaleEdgeInfo,
getUvCoordinateForPoint,
getUvHandlePosition,
type SelectedOutlineDragState,
+ type SelectedOutlineScaleDragState,
} from '../components/SelectedOutlineOverlay';
import {deleteSelectedTimelineItems} from '../components/Timeline/delete-selected-timeline-item';
import {isDuplicatableSequenceRowSelection} from '../components/Timeline/duplicate-selected-timeline-item';
@@ -714,6 +718,105 @@ test('Selected outline dragging applies the same delta to all selected sequences
]);
});
+test('Selected outline edge dragging scales one axis when scale is unlinked', () => {
+ const schema = {
+ 'style.scale': {type: 'scale', default: 1, min: 0.05, max: 100},
+ } satisfies SequenceSchema;
+ const nodePath = makeKey(['body', 0]);
+ const dragStates = [
+ {
+ defaultValue: JSON.stringify(1),
+ key: Internals.makeSequencePropsSubscriptionKey(nodePath),
+ startX: 2,
+ startY: 3,
+ startZ: 1,
+ target: {
+ clientId: 'client',
+ codeValue: {status: 'static', codeValue: '2 3'},
+ fieldDefault: 1,
+ fieldSchema: schema['style.scale'],
+ linked: false,
+ nodePath,
+ schema,
+ },
+ },
+ ] satisfies SelectedOutlineScaleDragState[];
+
+ const lastValues = getSelectedOutlineScaleDragValues({
+ dragStates,
+ axis: 'x',
+ scaleFactor: 1.25,
+ });
+
+ expect(lastValues.get(dragStates[0].key)).toBe('2.5 3');
+ expect(
+ getSelectedOutlineScaleDragChanges({
+ dragStates,
+ lastValues,
+ }),
+ ).toEqual([
+ {
+ fileName: '/project/src/Comp.tsx',
+ nodePath,
+ fieldKey: 'style.scale',
+ value: '2.5 3',
+ defaultValue: JSON.stringify(1),
+ schema,
+ },
+ ]);
+});
+
+test('Selected outline edge dragging preserves aspect ratio when scale is linked', () => {
+ const schema = {
+ 'style.scale': {type: 'scale', default: 1, min: 0.05, max: 100},
+ } satisfies SequenceSchema;
+ const nodePath = makeKey(['body', 0]);
+ const dragStates = [
+ {
+ defaultValue: JSON.stringify(1),
+ key: Internals.makeSequencePropsSubscriptionKey(nodePath),
+ startX: 2,
+ startY: 3,
+ startZ: 1,
+ target: {
+ clientId: 'client',
+ codeValue: {status: 'static', codeValue: '2 3'},
+ fieldDefault: 1,
+ fieldSchema: schema['style.scale'],
+ linked: true,
+ nodePath,
+ schema,
+ },
+ },
+ ] satisfies SelectedOutlineScaleDragState[];
+
+ const lastValues = getSelectedOutlineScaleDragValues({
+ dragStates,
+ axis: 'x',
+ scaleFactor: 1.25,
+ });
+
+ expect(lastValues.get(dragStates[0].key)).toBe('2.5 3.75');
+});
+
+test('Selected outline scale edges project pointer movement onto the edge normal', () => {
+ const points = [
+ {x: 0, y: 0},
+ {x: 100, y: 0},
+ {x: 100, y: 50},
+ {x: 0, y: 50},
+ ] as const;
+ const right = getSelectedOutlineScaleEdgeInfo(points, 'right');
+ const top = getSelectedOutlineScaleEdgeInfo(points, 'top');
+
+ expect(right?.axis).toBe('x');
+ expect(right?.extent).toBe(100);
+ expect(right?.normal).toEqual({x: 1, y: 0});
+ expect(top?.axis).toBe('y');
+ expect(top?.extent).toBe(50);
+ expect(top?.normal).toEqual({x: 0, y: -1});
+});
+
test('Backspace reset targets selected effect props', () => {
const schema = {} satisfies SequenceSchema;
const effectSchema = {