Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/studio`: Add easing editor modal (#8253)

Jonny Burger9926745a3cc5
diff --git a/packages/studio-server/src/preview-server/routes/log-updates/formatting.ts b/packages/studio-server/src/preview-server/routes/log-updates/formatting.ts
index 6dd5bd47b8..a7ed84be75 100644
--- a/packages/studio-server/src/preview-server/routes/log-updates/formatting.ts
+++ b/packages/studio-server/src/preview-server/routes/log-updates/formatting.ts
@@ -67,10 +67,13 @@ const formatValueDelta = ({
oldValueString: string;
newValueString: string;
}) => {
- const shortened = shortenUnchangedInterpolateOptions({
+ const withoutUnchangedOptions = shortenUnchangedInterpolateOptions({
oldValueString,
newValueString,
});
+ const shortened = removeUnchangedInterpolateOptionProperties(
+ withoutUnchangedOptions,
+ );
return `${colorValue(shortened.oldValueString)} ${punctuation('β†’')} ${colorValue(shortened.newValueString)}`;
};
@@ -153,6 +156,11 @@ const normalizeArg = (arg: string) => {
.trim();
};
+const shortenUnchangedOptionProperties = new Set([
+ 'extrapolateLeft',
+ 'extrapolateRight',
+]);
+
const splitTopLevelArgs = (argsSource: string) => {
const args: string[] = [];
let depth = 0;
@@ -196,6 +204,60 @@ const splitTopLevelArgs = (argsSource: string) => {
return args;
};
+const getObjectPropertyKey = (propertySource: string): string | null => {
+ const colonIndex = propertySource.indexOf(':');
+ if (colonIndex === -1) {
+ return null;
+ }
+
+ const key = propertySource.slice(0, colonIndex).trim();
+ if (/^[A-Za-z_$][\w$]*$/.test(key)) {
+ return key;
+ }
+
+ if (
+ (key.startsWith("'") && key.endsWith("'")) ||
+ (key.startsWith('"') && key.endsWith('"'))
+ ) {
+ return key.slice(1, -1);
+ }
+
+ return null;
+};
+
+const parseTopLevelObjectProperties = (objectSource: string) => {
+ const trimmed = objectSource.trim();
+ if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) {
+ return null;
+ }
+
+ const properties = splitTopLevelArgs(trimmed.slice(1, -1))
+ .filter(Boolean)
+ .map((propertySource) => {
+ const key = getObjectPropertyKey(propertySource);
+ if (key === null) {
+ return null;
+ }
+
+ const colonIndex = propertySource.indexOf(':');
+ return {
+ key,
+ value: normalizeArg(propertySource.slice(colonIndex + 1)),
+ source: propertySource.trim(),
+ };
+ });
+
+ if (properties.some((property) => property === null)) {
+ return null;
+ }
+
+ return properties as {
+ key: string;
+ value: string;
+ source: string;
+ }[];
+};
+
const parseInterpolateCall = (valueString: string): InterpolateCall | null => {
const trimmed = valueString.trim();
if (!trimmed.startsWith(callStart) || !trimmed.endsWith(')')) {
@@ -277,3 +339,74 @@ const shortenUnchangedInterpolateOptions = ({
newValueString: `interpolate(${newCall.args.slice(0, 3).join(', ')})`,
};
};
+
+const removeUnchangedInterpolateOptionProperties = ({
+ oldValueString,
+ newValueString,
+}: {
+ oldValueString: string;
+ newValueString: string;
+}) => {
+ const oldCall = parseInterpolateCall(oldValueString);
+ const newCall = parseInterpolateCall(newValueString);
+
+ if (
+ !oldCall ||
+ !newCall ||
+ oldCall.args.length <= 3 ||
+ newCall.args.length <= 3
+ ) {
+ return {oldValueString, newValueString};
+ }
+
+ const oldProperties = parseTopLevelObjectProperties(oldCall.args[3]);
+ const newProperties = parseTopLevelObjectProperties(newCall.args[3]);
+ if (!oldProperties || !newProperties) {
+ return {oldValueString, newValueString};
+ }
+
+ const propertiesToRemove = [...shortenUnchangedOptionProperties].filter(
+ (propertyName) => {
+ const oldProperty = oldProperties.find(
+ (property) => property.key === propertyName,
+ );
+ const newProperty = newProperties.find(
+ (property) => property.key === propertyName,
+ );
+
+ return (
+ oldProperty !== undefined &&
+ newProperty !== undefined &&
+ oldProperty.value === newProperty.value
+ );
+ },
+ );
+
+ if (propertiesToRemove.length === 0) {
+ return {oldValueString, newValueString};
+ }
+
+ const removeProperties = (
+ call: InterpolateCall,
+ properties: typeof oldProperties,
+ ) => {
+ const nextOptions = properties.filter(
+ (property) => !propertiesToRemove.includes(property.key),
+ );
+ const nextArgs =
+ nextOptions.length === 0
+ ? [...call.args.slice(0, 3), ...call.args.slice(4)]
+ : [
+ ...call.args.slice(0, 3),
+ `{${nextOptions.map((property) => property.source).join(', ')}}`,
+ ...call.args.slice(4),
+ ];
+
+ return `interpolate(${nextArgs.join(', ')})`;
+ };
+
+ return {
+ oldValueString: removeProperties(oldCall, oldProperties),
+ newValueString: removeProperties(newCall, newProperties),
+ };
+};
diff --git a/packages/studio-server/src/test/log-update.test.ts b/packages/studio-server/src/test/log-update.test.ts
index fcafe759f6..5d6f11a6cb 100644
--- a/packages/studio-server/src/test/log-update.test.ts
+++ b/packages/studio-server/src/test/log-update.test.ts
@@ -118,6 +118,36 @@ test('formatPropChange condenses unchanged interpolate options', () => {
expect(formatted).not.toContain('extrapolateRight');
});
+test('formatPropChange omits unchanged interpolate clamping when easing changes', () => {
+ const formatted = formatPropChange({
+ key: 'scale',
+ oldValueString: `interpolate(frame, [68, 78, 88], [0, 1, 1], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ easing: [
+ Easing.bezier(0.5526, 3.9109, 0.6487, 4.8024),
+ Easing.bezier(0.5526, 3.9109, 0.995, 5),
+ ],
+})`,
+ newValueString: `interpolate(frame, [68, 78, 88], [0, 1, 1], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ easing: [
+ Easing.bezier(0.5526, 3.9109, 0.6487, 4.8024),
+ Easing.bezier(0.5526, 3.9109, 0.6487, 4.8024),
+ ],
+})`,
+ defaultValueString: null,
+ removedProps: [],
+ addedProps: [],
+ });
+
+ expect(formatted).not.toContain('extrapolateLeft');
+ expect(formatted).not.toContain('extrapolateRight');
+ expect(formatted).toContain('Easing.bezier(0.5526, 3.9109, 0.995, 5)');
+ expect(formatted).toContain('Easing.bezier(0.5526, 3.9109, 0.6487, 4.8024)');
+});
+
test('logUpdate emits change-from-default output for discriminated union enum change', async () => {
const fixture = readFileSync(
path.join(__dirname, 'snapshots', 'discriminated-union-with-style.tsx'),
diff --git a/packages/studio/src/components/Modals.tsx b/packages/studio/src/components/Modals.tsx
index 99cc212ad1..a347194493 100644
--- a/packages/studio/src/components/Modals.tsx
+++ b/packages/studio/src/components/Modals.tsx
@@ -15,6 +15,7 @@ import QuickSwitcher from './QuickSwitcher/QuickSwitcher';
import {RenderStatusModal} from './RenderModal/RenderStatusModal';
import {RenderModalWithLoader} from './RenderModal/ServerRenderModal';
import {WebRenderModalWithLoader} from './RenderModal/WebRenderModal';
+import {EasingEditorModal} from './Timeline/EasingEditorModal';
import {KeyframeSettingsModal} from './Timeline/KeyframeSettingsModal';
import {UpdateModal} from './UpdateModal/UpdateModal';
@@ -63,6 +64,9 @@ export const Modals: React.FC<{
{modalContextType && modalContextType.type === 'keyframe-settings' && (
<KeyframeSettingsModal state={modalContextType} />
)}
+ {modalContextType && modalContextType.type === 'easing-editor' && (
+ <EasingEditorModal state={modalContextType} />
+ )}
{modalContextType && modalContextType.type === 'web-render' && (
<WebRenderModalWithLoader {...modalContextType} />
diff --git a/packages/studio/src/components/Timeline/EasingEditorModal.tsx b/packages/studio/src/components/Timeline/EasingEditorModal.tsx
new file mode 100644
index 0000000000..62adc177e9
--- /dev/null
+++ b/packages/studio/src/components/Timeline/EasingEditorModal.tsx
@@ -0,0 +1,508 @@
+import React, {
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import {Internals} from 'remotion';
+import {StudioServerConnectionCtx} from '../../helpers/client-id';
+import {
+ BLUE,
+ INPUT_BACKGROUND,
+ INPUT_BORDER_COLOR_HOVERED,
+ LIGHT_TEXT,
+} from '../../helpers/colors';
+import {ModalsContext} from '../../state/modals';
+import {Button} from '../Button';
+import {Row, Spacing} from '../layout';
+import {ModalButton} from '../ModalButton';
+import {ModalFooterContainer} from '../ModalFooter';
+import {ModalHeader} from '../ModalHeader';
+import {DismissableModal} from '../NewComposition/DismissableModal';
+import {InputDragger} from '../NewComposition/InputDragger';
+import type {TimelineSelection} from './TimelineSelection';
+import type {TimelineEasingValue} from './update-selected-easing';
+import {updateSelectedTimelineEasings} from './update-selected-easing';
+
+type CubicBezier = [number, number, number, number];
+type HandleIndex = 0 | 1;
+type Coordinate = 'x' | 'y';
+
+const SVG_WIDTH = 560;
+const SVG_HEIGHT = 320;
+const PLOT_LEFT = 42;
+const PLOT_TOP = 8;
+const PLOT_WIDTH = 500;
+const PLOT_HEIGHT = 304;
+const Y_MIN = -2;
+const Y_MAX = 3;
+const LINEAR_BEZIER: CubicBezier = [0.25, 0.25, 0.75, 0.75];
+
+const container: React.CSSProperties = {
+ width: 600,
+};
+
+const coordinatesGrid: React.CSSProperties = {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
+ gap: 10,
+ marginTop: 12,
+ padding: '0 16px 16px',
+};
+
+const coordinateRow: React.CSSProperties = {
+ gap: 4,
+};
+
+const coordinateLabel: React.CSSProperties = {
+ fontSize: 13,
+ color: 'rgba(255, 255, 255, 0.72)',
+ paddingLeft: 6,
+};
+
+const coordinateInputWrapper: React.CSSProperties = {
+ height: 34,
+ display: 'flex',
+ alignItems: 'center',
+};
+
+const numberInputStyle: React.CSSProperties = {
+ backgroundColor: INPUT_BACKGROUND,
+ borderRadius: 4,
+ width: '100%',
+};
+
+const svgStyle: React.CSSProperties = {
+ display: 'block',
+ width: '100%',
+};
+
+const hiddenSubmit: React.CSSProperties = {
+ display: 'none',
+};
+
+const clamp = (value: number, min: number, max: number) => {
+ return Math.min(max, Math.max(min, value));
+};
+
+const sanitizeBezier = (bezier: CubicBezier): CubicBezier => [
+ clamp(bezier[0], 0, 1),
+ clamp(bezier[1], Y_MIN, Y_MAX),
+ clamp(bezier[2], 0, 1),
+ clamp(bezier[3], Y_MIN, Y_MAX),
+];
+
+const easingToBezier = (easing: TimelineEasingValue): CubicBezier => {
+ return easing === 'linear' ? LINEAR_BEZIER : sanitizeBezier(easing);
+};
+
+const roundCoordinate = (value: number) => Math.round(value * 10000) / 10000;
+
+const serializeBezier = (bezier: CubicBezier): TimelineEasingValue => {
+ const rounded = sanitizeBezier(bezier).map(roundCoordinate) as CubicBezier;
+ if (rounded[0] === rounded[1] && rounded[2] === rounded[3]) {
+ return 'linear';
+ }
+
+ return rounded;
+};
+
+const formatNumber = (value: number | string) => {
+ const numericValue = Number(value);
+ if (!Number.isFinite(numericValue)) {
+ return String(value);
+ }
+
+ return String(roundCoordinate(numericValue));
+};
+
+const xToSvg = (value: number) => PLOT_LEFT + value * PLOT_WIDTH;
+const yToSvg = (value: number) =>
+ PLOT_TOP + ((Y_MAX - value) / (Y_MAX - Y_MIN)) * PLOT_HEIGHT;
+
+const pointFromBezier = (bezier: CubicBezier, handle: HandleIndex) => {
+ const x = handle === 0 ? bezier[0] : bezier[2];
+ const y = handle === 0 ? bezier[1] : bezier[3];
+ return {x: xToSvg(x), y: yToSvg(y)};
+};
+
+const startPoint = {x: xToSvg(0), y: yToSvg(0)};
+const endPoint = {x: xToSvg(1), y: yToSvg(1)};
+
+export type EasingEditorModalState = {
+ type: 'easing-editor';
+ initialEasing: TimelineEasingValue;
+ selections: TimelineSelection[];
+};
+
+export const EasingEditorModal: React.FC<{
+ readonly state: EasingEditorModalState;
+}> = ({state}) => {
+ const {setSelectedModal} = useContext(ModalsContext);
+ const {previewServerState} = useContext(StudioServerConnectionCtx);
+ const sequencesRef = useContext(Internals.SequenceManagerRefContext);
+ const propStatusesRef = useContext(
+ Internals.VisualModePropStatusesRefContext,
+ );
+ const {setPropStatuses} = useContext(Internals.VisualModeSettersContext);
+ const {overrideIdToNodePathMappings} = useContext(
+ Internals.OverrideIdsToNodePathsGettersContext,
+ );
+ const svgRef = useRef<SVGSVGElement>(null);
+ const [bezier, setBezier] = useState(() =>
+ easingToBezier(state.initialEasing),
+ );
+ const [saving, setSaving] = useState(false);
+ const [activeHandle, setActiveHandle] = useState<HandleIndex | null>(null);
+
+ const close = useCallback(() => {
+ setSelectedModal(null);
+ }, [setSelectedModal]);
+
+ const setCoordinate = useCallback(
+ (handle: HandleIndex, coordinate: Coordinate, value: number) => {
+ setBezier((previous) => {
+ const next = [...previous] as CubicBezier;
+ const index =
+ handle === 0
+ ? coordinate === 'x'
+ ? 0
+ : 1
+ : coordinate === 'x'
+ ? 2
+ : 3;
+ next[index] =
+ coordinate === 'x' ? clamp(value, 0, 1) : clamp(value, Y_MIN, Y_MAX);
+ return next;
+ });
+ },
+ [],
+ );
+
+ const getValueFromPointer = useCallback(
+ (event: {clientX: number; clientY: number}) => {
+ const svg = svgRef.current;
+ if (!svg) {
+ return null;
+ }
+
+ const rect = svg.getBoundingClientRect();
+ const svgX = ((event.clientX - rect.left) / rect.width) * SVG_WIDTH;
+ const svgY = ((event.clientY - rect.top) / rect.height) * SVG_HEIGHT;
+ const x = clamp((svgX - PLOT_LEFT) / PLOT_WIDTH, 0, 1);
+ const y = clamp(
+ Y_MAX - ((svgY - PLOT_TOP) / PLOT_HEIGHT) * (Y_MAX - Y_MIN),
+ Y_MIN,
+ Y_MAX,
+ );
+
+ return {x, y};
+ },
+ [],
+ );
+
+ const updateHandleFromPointer = useCallback(
+ (handle: HandleIndex, event: {clientX: number; clientY: number}) => {
+ const value = getValueFromPointer(event);
+ if (!value) {
+ return;
+ }
+
+ setBezier((previous) => {
+ const next = [...previous] as CubicBezier;
+ if (handle === 0) {
+ next[0] = value.x;
+ next[1] = value.y;
+ } else {
+ next[2] = value.x;
+ next[3] = value.y;
+ }
+
+ return next;
+ });
+ },
+ [getValueFromPointer],
+ );
+
+ useEffect(() => {
+ if (activeHandle === null) {
+ return;
+ }
+
+ const onPointerMove = (event: PointerEvent) => {
+ updateHandleFromPointer(activeHandle, event);
+ };
+
+ const onPointerUp = () => {
+ setActiveHandle(null);
+ };
+
+ window.addEventListener('pointermove', onPointerMove);
+ window.addEventListener('pointerup', onPointerUp, {once: true});
+
+ return () => {
+ window.removeEventListener('pointermove', onPointerMove);
+ window.removeEventListener('pointerup', onPointerUp);
+ };
+ }, [activeHandle, updateHandleFromPointer]);
+
+ const onHandlePointerDown = useCallback(
+ (handle: HandleIndex, event: React.PointerEvent<SVGCircleElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setActiveHandle(handle);
+ updateHandleFromPointer(handle, event);
+ },
+ [updateHandleFromPointer],
+ );
+
+ const onSave = useCallback(() => {
+ if (previewServerState.type !== 'connected' || saving) {
+ return;
+ }
+
+ setSaving(true);
+ const promise = updateSelectedTimelineEasings({
+ selections: state.selections,
+ sequences: sequencesRef.current,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ propStatuses: propStatusesRef.current,
+ setPropStatuses,
+ clientId: previewServerState.clientId,
+ easing: serializeBezier(bezier),
+ });
+
+ if (promise === null) {
+ setSaving(false);
+ return;
+ }
+
+ promise.catch(() => undefined);
+ close();
+ }, [
+ bezier,
+ close,
+ overrideIdToNodePathMappings,
+ previewServerState,
+ propStatusesRef,
+ saving,
+ sequencesRef,
+ setPropStatuses,
+ state.selections,
+ ]);
+
+ const onSubmit: React.FormEventHandler<HTMLFormElement> = useCallback(
+ (event) => {
+ event.preventDefault();
+ onSave();
+ },
+ [onSave],
+ );
+
+ const path = useMemo(() => {
+ const curveFirstHandle = pointFromBezier(bezier, 0);
+ const curveSecondHandle = pointFromBezier(bezier, 1);
+ return `M ${startPoint.x} ${startPoint.y} C ${curveFirstHandle.x} ${curveFirstHandle.y}, ${curveSecondHandle.x} ${curveSecondHandle.y}, ${endPoint.x} ${endPoint.y}`;
+ }, [bezier]);
+
+ const firstHandle = pointFromBezier(bezier, 0);
+ const secondHandle = pointFromBezier(bezier, 1);
+ const yZero = yToSvg(0);
+ const yOne = yToSvg(1);
+ const saveDisabled = saving || previewServerState.type !== 'connected';
+
+ return (
+ <DismissableModal>
+ <ModalHeader title="Edit easing" />
+ <form onSubmit={onSubmit}>
+ <div style={container}>
+ <svg
+ ref={svgRef}
+ width={SVG_WIDTH}
+ height={SVG_HEIGHT}
+ viewBox={`0 0 ${SVG_WIDTH} ${SVG_HEIGHT}`}
+ style={svgStyle}
+ aria-label="Bezier curve editor"
+ >
+ <line
+ x1={PLOT_LEFT}
+ y1={yZero}
+ x2={PLOT_LEFT + PLOT_WIDTH}
+ y2={yZero}
+ stroke={INPUT_BORDER_COLOR_HOVERED}
+ strokeWidth={1}
+ />
+ <line
+ x1={PLOT_LEFT}
+ y1={yOne}
+ x2={PLOT_LEFT + PLOT_WIDTH}
+ y2={yOne}
+ stroke={INPUT_BORDER_COLOR_HOVERED}
+ strokeWidth={1}
+ />
+
+ <line
+ x1={startPoint.x}
+ y1={startPoint.y}
+ x2={firstHandle.x}
+ y2={firstHandle.y}
+ stroke="rgba(255, 255, 255, 0.35)"
+ strokeWidth={1}
+ />
+ <line
+ x1={endPoint.x}
+ y1={endPoint.y}
+ x2={secondHandle.x}
+ y2={secondHandle.y}
+ stroke="rgba(255, 255, 255, 0.35)"
+ strokeWidth={1}
+ />
+ <path d={path} fill="none" stroke={BLUE} strokeWidth={3} />
+ <circle cx={startPoint.x} cy={startPoint.y} r={4} fill="white" />
+ <circle cx={endPoint.x} cy={endPoint.y} r={4} fill="white" />
+ <circle
+ cx={firstHandle.x}
+ cy={firstHandle.y}
+ r={6}
+ fill="white"
+ stroke={BLUE}
+ strokeWidth={2}
+ vectorEffect="non-scaling-stroke"
+ pointerEvents="all"
+ cursor={activeHandle === 0 ? 'grabbing' : 'default'}
+ onPointerDown={(event) => onHandlePointerDown(0, event)}
+ />
+ <circle
+ cx={secondHandle.x}
+ cy={secondHandle.y}
+ r={6}
+ fill="white"
+ stroke={BLUE}
+ strokeWidth={2}
+ vectorEffect="non-scaling-stroke"
+ pointerEvents="all"
+ cursor={activeHandle === 1 ? 'grabbing' : 'default'}
+ onPointerDown={(event) => onHandlePointerDown(1, event)}
+ />
+ <text
+ x={PLOT_LEFT - 22}
+ y={yZero + 3}
+ fill={LIGHT_TEXT}
+ fontSize={9}
+ >
+ 0
+ </text>
+ <text
+ x={PLOT_LEFT - 22}
+ y={yOne + 3}
+ fill={LIGHT_TEXT}
+ fontSize={9}
+ >
+ 1
+ </text>
+ </svg>
+ <div style={coordinatesGrid}>
+ <div style={coordinateRow}>
+ <div style={coordinateLabel}>X1</div>
+ <div style={coordinateInputWrapper}>
+ <InputDragger
+ type="number"
+ value={bezier[0]}
+ status="ok"
+ onValueChange={(value) => setCoordinate(0, 'x', value)}
+ onValueChangeEnd={(value) => setCoordinate(0, 'x', value)}
+ onTextChange={() => undefined}
+ min={0}
+ max={1}
+ step={0.01}
+ formatter={formatNumber}
+ rightAlign={false}
+ style={numberInputStyle}
+ snapToStep={false}
+ />
+ </div>
+ </div>
+ <div style={coordinateRow}>
+ <div style={coordinateLabel}>Y1</div>
+ <div style={coordinateInputWrapper}>
+ <InputDragger
+ type="number"
+ value={bezier[1]}
+ status="ok"
+ onValueChange={(value) => setCoordinate(0, 'y', value)}
+ onValueChangeEnd={(value) => setCoordinate(0, 'y', value)}
+ onTextChange={() => undefined}
+ min={Y_MIN}
+ max={Y_MAX}
+ step={0.01}
+ formatter={formatNumber}
+ rightAlign={false}
+ style={numberInputStyle}
+ snapToStep={false}
+ />
+ </div>
+ </div>
+ <div style={coordinateRow}>
+ <div style={coordinateLabel}>X2</div>
+ <div style={coordinateInputWrapper}>
+ <InputDragger
+ type="number"
+ value={bezier[2]}
+ status="ok"
+ onValueChange={(value) => setCoordinate(1, 'x', value)}
+ onValueChangeEnd={(value) => setCoordinate(1, 'x', value)}
+ onTextChange={() => undefined}
+ min={0}
+ max={1}
+ step={0.01}
+ formatter={formatNumber}
+ rightAlign={false}
+ style={numberInputStyle}
+ snapToStep={false}
+ />
+ </div>
+ </div>
+ <div style={coordinateRow}>
+ <div style={coordinateLabel}>Y2</div>
+ <div style={coordinateInputWrapper}>
+ <InputDragger
+ type="number"
+ value={bezier[3]}
+ status="ok"
+ onValueChange={(value) => setCoordinate(1, 'y', value)}
+ onValueChangeEnd={(value) => setCoordinate(1, 'y', value)}
+ onTextChange={() => undefined}
+ min={Y_MIN}
+ max={Y_MAX}
+ step={0.01}
+ formatter={formatNumber}
+ rightAlign={false}
+ style={numberInputStyle}
+ snapToStep={false}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ <ModalFooterContainer>
+ <Row justify="flex-end" align="center">
+ <Button onClick={close}>Discard</Button>
+ <Spacing x={1} />
+ <ModalButton onClick={onSave} disabled={saveDisabled}>
+ Save
+ </ModalButton>
+ </Row>
+ </ModalFooterContainer>
+ <button
+ type="submit"
+ style={hiddenSubmit}
+ disabled={saveDisabled}
+ aria-hidden
+ tabIndex={-1}
+ />
+ </form>
+ </DismissableModal>
+ );
+};
diff --git a/packages/studio/src/components/Timeline/TimelineKeyframeEasingLine.tsx b/packages/studio/src/components/Timeline/TimelineKeyframeEasingLine.tsx
index 8d9f759c98..9758fff094 100644
--- a/packages/studio/src/components/Timeline/TimelineKeyframeEasingLine.tsx
+++ b/packages/studio/src/components/Timeline/TimelineKeyframeEasingLine.tsx
@@ -2,10 +2,11 @@ import {KEYFRAME_EASING_PRESETS} from '@remotion/studio-shared';
import React, {useCallback, useContext, useMemo, useRef} from 'react';
import {Internals, useVideoConfig} from 'remotion';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
-import {BLUE, LINE_COLOR} from '../../helpers/colors';
+import {BLUE} from '../../helpers/colors';
import {getXPositionOfItemInTimelineImperatively} from '../../helpers/get-left-of-timeline-slider';
import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';
import {TIMELINE_PADDING} from '../../helpers/timeline-layout';
+import {ModalsContext} from '../../state/modals';
import {ContextMenuForTarget} from '../ContextMenu';
import type {ComboboxValue} from '../NewComposition/ComboBox';
import {
@@ -15,6 +16,8 @@ import {
import {TimelineWidthContext} from './TimelineWidthProvider';
import {
getEasingSelections,
+ getTimelineEasingValueForSelection,
+ type TimelineEasingValue,
updateSelectedTimelineEasings,
} from './update-selected-easing';
@@ -31,7 +34,7 @@ const easingLineButton: React.CSSProperties = {
};
const easingLine: React.CSSProperties = {
- backgroundColor: LINE_COLOR,
+ backgroundColor: 'rgba(255, 255, 255, 0.1)',
borderRadius: lineHeight / 2,
height: lineHeight,
left: 0,
@@ -68,19 +71,23 @@ const TimelineKeyframeEasingLineUnmemoized: React.FC<{
Internals.OverrideIdsToNodePathsGettersContext,
);
const currentSelection = useCurrentTimelineSelectionStateAsRef();
+ const {setSelectedModal} = useContext(ModalsContext);
+
+ const getTargetSelections = useCallback(() => {
+ const selectedEasings = getEasingSelections(
+ currentSelection.current.selectedItems,
+ );
+ return selected ? selectedEasings : [selectionItem];
+ }, [currentSelection, selected, selectionItem]);
const updateEasing = useCallback(
- (easing: (typeof KEYFRAME_EASING_PRESETS)[number]['easing']) => {
+ (easing: TimelineEasingValue) => {
if (previewServerState.type !== 'connected') {
return;
}
- const selectedEasings = getEasingSelections(
- currentSelection.current.selectedItems,
- );
- const selections = selected ? selectedEasings : [selectionItem];
const promise = updateSelectedTimelineEasings({
- selections,
+ selections: getTargetSelections(),
sequences: sequencesRef.current,
overrideIdsToNodePaths: overrideIdToNodePathMappings,
propStatuses: propStatusesRef.current,
@@ -91,31 +98,90 @@ const TimelineKeyframeEasingLineUnmemoized: React.FC<{
promise?.catch(() => undefined);
},
[
- currentSelection,
+ getTargetSelections,
overrideIdToNodePathMappings,
previewServerState,
propStatusesRef,
- selected,
- selectionItem,
sequencesRef,
setPropStatuses,
],
);
+ const onOpenEasingEditor = useCallback(() => {
+ if (previewServerState.type !== 'connected') {
+ return;
+ }
+
+ const initialEasing = getTimelineEasingValueForSelection({
+ selection: selectionItem,
+ sequences: sequencesRef.current,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ propStatuses: propStatusesRef.current,
+ });
+
+ if (initialEasing === null) {
+ return;
+ }
+
+ setSelectedModal({
+ type: 'easing-editor',
+ initialEasing,
+ selections: getTargetSelections(),
+ });
+ }, [
+ getTargetSelections,
+ overrideIdToNodePathMappings,
+ previewServerState,
+ propStatusesRef,
+ selectionItem,
+ sequencesRef,
+ setSelectedModal,
+ ]);
+
const contextMenuValues = useMemo((): ComboboxValue[] => {
- return KEYFRAME_EASING_PRESETS.map((preset) => ({
- type: 'item',
- id: preset.id,
- keyHint: null,
- label: preset.label,
- leftItem: null,
- disabled: previewServerState.type !== 'connected',
- onClick: () => updateEasing(preset.easing),
- quickSwitcherLabel: null,
- subMenu: null,
- value: preset.id,
- }));
- }, [previewServerState.type, updateEasing]);
+ return [
+ {
+ type: 'item',
+ id: 'linear',
+ keyHint: null,
+ label: 'Linear',
+ leftItem: null,
+ disabled: previewServerState.type !== 'connected',
+ onClick: () => updateEasing('linear'),
+ quickSwitcherLabel: null,
+ subMenu: null,
+ value: 'linear',
+ },
+ ...KEYFRAME_EASING_PRESETS.map((preset) => ({
+ type: 'item' as const,
+ id: preset.id,
+ keyHint: null,
+ label: preset.label,
+ leftItem: null,
+ disabled: previewServerState.type !== 'connected',
+ onClick: () => updateEasing(preset.easing),
+ quickSwitcherLabel: null,
+ subMenu: null,
+ value: preset.id,
+ })),
+ {
+ type: 'divider' as const,
+ id: 'edit-easing-divider',
+ },
+ {
+ type: 'item',
+ id: 'edit-easing',
+ keyHint: null,
+ label: 'Edit...',
+ leftItem: null,
+ disabled: previewServerState.type !== 'connected',
+ onClick: onOpenEasingEditor,
+ quickSwitcherLabel: null,
+ subMenu: null,
+ value: 'edit-easing',
+ },
+ ];
+ }, [onOpenEasingEditor, previewServerState.type, updateEasing]);
const onOpenContextMenu = useCallback(
(event: MouseEvent) => {
diff --git a/packages/studio/src/components/Timeline/TimelineSelection.tsx b/packages/studio/src/components/Timeline/TimelineSelection.tsx
index 42399b8cd9..4a1a0b850a 100644
--- a/packages/studio/src/components/Timeline/TimelineSelection.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSelection.tsx
@@ -100,6 +100,11 @@ export type TimelineSelection =
readonly segmentIndex: number;
});
+export type TimelineEasingSelection = Extract<
+ TimelineSelection,
+ {type: 'easing'}
+>;
+
export type TimelineSelectionInteraction = {
readonly shiftKey: boolean;
readonly toggleKey: boolean;
@@ -740,7 +745,7 @@ export const useTimelineEasingSelection = ({
const {canSelectEasing, isSelected, selectItem, registerSelectableItem} =
useTimelineSelection();
const selectionItem = useMemo(
- (): TimelineSelection => ({
+ (): TimelineEasingSelection => ({
type: 'easing',
nodePathInfo,
fromFrame,
diff --git a/packages/studio/src/components/Timeline/update-selected-easing.ts b/packages/studio/src/components/Timeline/update-selected-easing.ts
index ac252f9efb..8ea474748d 100644
--- a/packages/studio/src/components/Timeline/update-selected-easing.ts
+++ b/packages/studio/src/components/Timeline/update-selected-easing.ts
@@ -7,9 +7,12 @@ import {
import {findTrackForNodePathInfo} from './find-track-for-node-path-info';
import {parseKeyframeFieldFromNodePath} from './parse-keyframe-field-from-node-path';
import type {SetPropStatuses} from './save-sequence-prop';
-import type {TimelineSelection} from './TimelineSelection';
+import type {
+ TimelineEasingSelection,
+ TimelineSelection,
+} from './TimelineSelection';
-type EasingSelection = TimelineSelection & {type: 'easing'};
+export type EasingSelection = TimelineEasingSelection;
export type TimelineEasingValue = 'linear' | [number, number, number, number];
const canEditEasingForInterpolationFunction = (
@@ -78,6 +81,8 @@ const getSelectedEasingUpdate = ({
fieldKey: field.fieldKey,
schema: sequence.controls.schema,
segmentIndex: selection.segmentIndex,
+ currentEasing:
+ sequencePropStatus.easing[selection.segmentIndex] ?? 'linear',
};
}
@@ -112,6 +117,7 @@ const getSelectedEasingUpdate = ({
fieldKey: field.fieldKey,
schema: effect.schema,
segmentIndex: selection.segmentIndex,
+ currentEasing: effectPropStatus.easing[selection.segmentIndex] ?? 'linear',
};
};
@@ -119,6 +125,27 @@ export const getEasingSelections = (
selections: readonly TimelineSelection[],
): EasingSelection[] => selections.filter(isEasingSelection);
+export const getTimelineEasingValueForSelection = ({
+ selection,
+ sequences,
+ overrideIdsToNodePaths,
+ propStatuses,
+}: {
+ selection: EasingSelection;
+ sequences: TSequence[];
+ overrideIdsToNodePaths: OverrideIdToNodePaths;
+ propStatuses: PropStatuses;
+}): TimelineEasingValue | null => {
+ return (
+ getSelectedEasingUpdate({
+ selection,
+ sequences,
+ overrideIdsToNodePaths,
+ propStatuses,
+ })?.currentEasing ?? null
+ );
+};
+
export const updateSelectedTimelineEasings = ({
selections,
sequences,
diff --git a/packages/studio/src/state/modals.ts b/packages/studio/src/state/modals.ts
index 68bebb2e87..20975def9a 100644
--- a/packages/studio/src/state/modals.ts
+++ b/packages/studio/src/state/modals.ts
@@ -26,6 +26,7 @@ import type {_InternalTypes} from 'remotion';
import type {CompType} from '../components/NewComposition/DuplicateComposition';
import type {QuickSwitcherMode} from '../components/QuickSwitcher/NoResults';
import type {RenderType} from '../components/RenderModal/RenderModalAdvanced';
+import type {EasingEditorModalState} from '../components/Timeline/EasingEditorModal';
import type {KeyframeSettingsModalState} from '../components/Timeline/KeyframeSettingsModal';
import type {Bug, UpdateInfo} from '../components/UpdateCheck';
@@ -153,6 +154,7 @@ export type ModalState =
| {
type: 'input-props-override';
}
+ | EasingEditorModalState
| KeyframeSettingsModalState
| RenderModalState
| WebRenderModalState