Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Add canvas crop controls (#9704)

Jonny Burger383798e6e9a7
diff --git a/packages/skills/skills/remotion-markup/SKILL.md b/packages/skills/skills/remotion-markup/SKILL.md
index 6dee3d8792..9cc4a7964d 100644
--- a/packages/skills/skills/remotion-markup/SKILL.md
+++ b/packages/skills/skills/remotion-markup/SKILL.md
@@ -10,7 +10,7 @@ If this is not relevant, load [Remotion Best Practices](../remotion-best-practic
## General rules
-Animate properties using `useCurrentFrame()` and `interpolate()`.
+Animate properties using `useCurrentFrame()` and `interpolate()`.
Use `Easing.bezier()` to customize timing, including jumpy or overshooting motion.
Use `Easing.spring()` if you want spring animations.
@@ -99,6 +99,11 @@ export const MyComposition = () => {
};
```
+## Cropping
+
+See [cropping.md](cropping.md) for supported components, crop props, Studio
+controls, animation, and custom component support.
+
To delay content wrap it in `<Sequence>` and use `from`.
To limit the duration of an element, use `durationInFrames` of `<Sequence>`.
`<Sequence>` by default is an absolute fill covering the scene.
@@ -202,8 +207,9 @@ When creating a visual effect, consider whether it is feasible using CSS and HTM
1. Normal Remotion/HTML/CSS/SVG/filter/blend/mask animation
2. An effect applied to the element directly (`<Video>`, `<Img>`), or by wrapping the content in [`<HtmlInCanvas>`](html-in-canvas.md), which also accepts `effects`:
- - A listed effect via [effects.md](effects.md)
- - A custom `createEffect()` via [effects.md](effects.md) when no preset is available.
+
+- A listed effect via [effects.md](effects.md)
+- A custom `createEffect()` via [effects.md](effects.md) when no preset is available.
## 3D content
diff --git a/packages/skills/skills/remotion-markup/cropping.md b/packages/skills/skills/remotion-markup/cropping.md
new file mode 100644
index 0000000000..95f9db2165
--- /dev/null
+++ b/packages/skills/skills/remotion-markup/cropping.md
@@ -0,0 +1,34 @@
+# Cropping
+
+Preferably, the `cropLeft`, `cropRight`, `cropTop` and `cropBottom` props are used to crop content.
+It allows for interactively dragging the components and adapting the outlines in the canvas to the crop.
+
+The following components support `crop*` props:
+
+- `<Sequence>` from `remotion`, when `layout="absolute-fill"`
+- `<CanvasImage>` from `remotion`
+- `<Img>` from `remotion`
+- `<AnimatedImage>` from `remotion`
+- `<HtmlInCanvas>` from `remotion`
+- `<Solid>` from `remotion`
+- `<Video>` from `@remotion/media`
+- `<Gif>` from `@remotion/gif`
+- `<RemotionRiveCanvas>` from `@remotion/rive`
+
+Crop values are ratios between `0` and `1`.
+A value of `0` applies no crop on that edge.
+A value of `1` is a full crop.
+Keep [Interactivity Best Practices](../remotion-interactivity/SKILL.md) also for cropping, to keep it editable and keyframable.
+
+```tsx
+<CanvasImage
+ src={staticFile("photo.png")}
+ cropLeft={interpolate(frame, [0, 30], [0, 0.25], {
+ extrapolateLeft: "clamp",
+ extrapolateRight: "clamp",
+ })}
+ cropBottom={0.1}
+/>
+```
+
+Do not use `clipPath` together with crop props.
diff --git a/packages/studio/src/components/SelectedOutlineCropControls.tsx b/packages/studio/src/components/SelectedOutlineCropControls.tsx
new file mode 100644
index 0000000000..ecb2b3b08d
--- /dev/null
+++ b/packages/studio/src/components/SelectedOutlineCropControls.tsx
@@ -0,0 +1,417 @@
+import React, {useContext, useLayoutEffect, useMemo} from 'react';
+import {Internals} from 'remotion';
+import {
+ BLUE,
+ SELECTED_OUTLINE_DROP_SHADOW,
+ TRANSPARENT,
+} from '../helpers/colors';
+import {
+ forceSpecificCursor,
+ stopForcingSpecificCursor,
+} from './ForceSpecificCursor';
+import {showNotification} from './Notifications/NotificationCenter';
+import {
+ getSelectedOutlineCropDragChanges,
+ getSelectedOutlineCropDragValues,
+ getSelectedOutlineCropFollowingTransformOrigin,
+ type SelectedOutlineCropValues,
+ type SelectedOutlineKeyframedDragChange,
+ type SelectedOutlineStaticDragChange,
+} from './selected-outline-drag';
+import type {OutlinePoint, SelectedOutline} from './selected-outline-geometry';
+import {
+ midpoint,
+ vectorBetween,
+ vectorLength,
+} from './selected-outline-measurement';
+import {
+ cropFieldKeys,
+ transformOriginFieldKey,
+ type SelectedOutlineCropHandle,
+ type SelectedOutlineTarget,
+} from './selected-outline-types';
+import {getUvCoordinateForPoint} from './selected-outline-uv';
+import {callAddKeyframes} from './Timeline/call-add-keyframe';
+import {commitPendingInspectorFields} from './Timeline/focus-inspector-field';
+import {saveSequenceProps} from './Timeline/save-sequence-prop';
+
+const CROP_HANDLE_THICKNESS = 5;
+const CROP_HANDLE_LENGTH = 20;
+const CROP_HANDLE_HIT_WIDTH = 14;
+const CROPPED_AWAY_OPACITY = 0.35;
+
+const cropHandles: readonly SelectedOutlineCropHandle[] = [
+ 'top-left',
+ 'top-right',
+ 'bottom-left',
+ 'bottom-right',
+ 'top',
+ 'right',
+ 'bottom',
+ 'left',
+];
+
+const cursorForHandle = (
+ handle: SelectedOutlineCropHandle,
+): React.CSSProperties['cursor'] => {
+ if (handle === 'top' || handle === 'bottom') {
+ return 'ns-resize';
+ }
+
+ if (handle === 'left' || handle === 'right') {
+ return 'ew-resize';
+ }
+
+ return handle === 'top-left' || handle === 'bottom-right'
+ ? 'nwse-resize'
+ : 'nesw-resize';
+};
+
+const moveTowards = (
+ from: OutlinePoint,
+ to: OutlinePoint,
+ distance: number,
+): OutlinePoint => {
+ const vector = vectorBetween(from, to);
+ const length = vectorLength(vector);
+ if (length === 0) {
+ return from;
+ }
+
+ const progress = Math.min(1, distance / length);
+ return {
+ x: from.x + vector.x * progress,
+ y: from.y + vector.y * progress,
+ };
+};
+
+const pointString = (point: OutlinePoint) => `${point.x} ${point.y}`;
+
+const getCropHandlePath = ({
+ handle,
+ points,
+}: {
+ readonly handle: SelectedOutlineCropHandle;
+ readonly points: SelectedOutline['points'];
+}): string => {
+ const [topLeft, topRight, bottomRight, bottomLeft] = points;
+ const cornerInfo = {
+ 'top-left': {corner: topLeft, first: topRight, second: bottomLeft},
+ 'top-right': {corner: topRight, first: topLeft, second: bottomRight},
+ 'bottom-left': {corner: bottomLeft, first: topLeft, second: bottomRight},
+ 'bottom-right': {corner: bottomRight, first: topRight, second: bottomLeft},
+ } as const;
+
+ if (handle in cornerInfo) {
+ const info = cornerInfo[handle as keyof typeof cornerInfo];
+ const length = Math.min(
+ CROP_HANDLE_LENGTH,
+ vectorLength(vectorBetween(info.corner, info.first)) / 4,
+ vectorLength(vectorBetween(info.corner, info.second)) / 4,
+ );
+ const first = moveTowards(info.corner, info.first, length);
+ const second = moveTowards(info.corner, info.second, length);
+ return `M ${pointString(first)} L ${pointString(info.corner)} L ${pointString(second)}`;
+ }
+
+ const edgeInfo = {
+ top: [topLeft, topRight],
+ right: [topRight, bottomRight],
+ bottom: [bottomLeft, bottomRight],
+ left: [topLeft, bottomLeft],
+ } as const;
+ const [start, end] = edgeInfo[handle as keyof typeof edgeInfo];
+ const center = midpoint(start, end);
+ const halfLength = Math.min(
+ CROP_HANDLE_LENGTH / 2,
+ vectorLength(vectorBetween(start, end)) / 8,
+ );
+ const pathStart = moveTowards(center, start, halfLength);
+ const pathEnd = moveTowards(center, end, halfLength);
+ return `M ${pointString(pathStart)} L ${pointString(pathEnd)}`;
+};
+
+const getCropValues = (
+ target: NonNullable<SelectedOutlineTarget['cropDrag']>,
+): SelectedOutlineCropValues => ({
+ cropLeft: target.fields.cropLeft.value,
+ cropRight: target.fields.cropRight.value,
+ cropTop: target.fields.cropTop.value,
+ cropBottom: target.fields.cropBottom.value,
+});
+
+const makeCropPreviewMask = (crop: SelectedOutlineTarget['crop']): string => {
+ const x = crop.left * 100;
+ const y = crop.top * 100;
+ const width = Math.max(0, 1 - crop.left - crop.right) * 100;
+ const height = Math.max(0, 1 - crop.top - crop.bottom) * 100;
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1" viewBox="0 0 100 100" preserveAspectRatio="none"><rect width="100" height="100" fill="white" fill-opacity="${CROPPED_AWAY_OPACITY}"/><rect x="${x}" y="${y}" width="${width}" height="${height}" fill="white"/></svg>`;
+ return `url("data:image/svg+xml,${encodeURIComponent(svg)}")`;
+};
+
+const cropPreviewAttribute = 'data-remotion-studio-crop-preview';
+let cropPreviewId = 0;
+
+const useCropPreview = (target: SelectedOutlineTarget | undefined) => {
+ useLayoutEffect(() => {
+ if (target === undefined || target.cropDrag === null) {
+ return;
+ }
+
+ const element = target.ref.current;
+ if (!(element instanceof HTMLElement || element instanceof SVGElement)) {
+ return;
+ }
+
+ const mask = makeCropPreviewMask(target.crop);
+ const previewId = String(++cropPreviewId);
+ const styleElement = element.ownerDocument.createElement('style');
+ styleElement.textContent = `
+[${cropPreviewAttribute}="${previewId}"] {
+ clip-path: none !important;
+ mask-image: ${mask} !important;
+ -webkit-mask-image: ${mask} !important;
+ mask-position: 0 0 !important;
+ -webkit-mask-position: 0 0 !important;
+ mask-repeat: no-repeat !important;
+ -webkit-mask-repeat: no-repeat !important;
+ mask-size: 100% 100% !important;
+ -webkit-mask-size: 100% 100% !important;
+}`;
+
+ // Do not mutate the inline crop style: React would still consider its
+ // clipPath prop applied and may not restore it when crop mode is closed.
+ element.setAttribute(cropPreviewAttribute, previewId);
+ (
+ element.ownerDocument.head ?? element.ownerDocument.documentElement
+ ).append(styleElement);
+
+ return () => {
+ if (element.getAttribute(cropPreviewAttribute) === previewId) {
+ element.removeAttribute(cropPreviewAttribute);
+ }
+
+ styleElement.remove();
+ };
+ }, [target]);
+};
+
+const CropHandle: React.FC<{
+ readonly handle: SelectedOutlineCropHandle;
+ readonly outline: SelectedOutline;
+ readonly onDraggingChange: (dragging: boolean) => void;
+ readonly target: SelectedOutlineTarget;
+}> = ({handle, outline, onDraggingChange, target}) => {
+ const {setPropStatuses, setDragOverrides, clearDragOverrides} = useContext(
+ Internals.VisualModeSettersContext,
+ );
+ const {cropDrag} = target;
+ const cursor = cursorForHandle(handle);
+ const path = useMemo(
+ () => getCropHandlePath({handle, points: outline.points}),
+ [handle, outline.points],
+ );
+
+ const onPointerDown = React.useCallback(
+ (event: React.PointerEvent<SVGPathElement>) => {
+ if (event.button !== 0 || cropDrag === null) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ if (commitPendingInspectorFields()) {
+ return;
+ }
+
+ const svg = event.currentTarget.ownerSVGElement;
+ if (svg === null) {
+ return;
+ }
+
+ const svgRect = svg.getBoundingClientRect();
+ const uncroppedPoints = outline.uncroppedPoints ?? outline.points;
+ const initialValues = getCropValues(cropDrag);
+ let lastValues = initialValues;
+ let dragStarted = false;
+
+ const onPointerMove = (moveEvent: PointerEvent) => {
+ moveEvent.preventDefault();
+ if (!dragStarted) {
+ dragStarted = true;
+ onDraggingChange(true);
+ forceSpecificCursor(cursor ?? 'default');
+ }
+
+ const uv = getUvCoordinateForPoint(uncroppedPoints, {
+ x: moveEvent.clientX - svgRect.left,
+ y: moveEvent.clientY - svgRect.top,
+ });
+ lastValues = getSelectedOutlineCropDragValues({
+ crop: initialValues,
+ dimensions: outline.dimensions,
+ handle,
+ uv,
+ });
+ const transformOrigin = getSelectedOutlineCropFollowingTransformOrigin({
+ dimensions: outline.dimensions,
+ initialCrop: initialValues,
+ nextCrop: lastValues,
+ transformOrigin: cropDrag.transformOrigin,
+ });
+
+ for (const fieldKey of Object.values(cropFieldKeys)) {
+ const field = cropDrag.fields[fieldKey];
+ const value = lastValues[fieldKey];
+ if (value === field.value) {
+ continue;
+ }
+
+ setDragOverrides(
+ cropDrag.nodePath,
+ fieldKey,
+ field.propStatus.status === 'keyframed'
+ ? Internals.makeKeyframedDragOverride({
+ status: field.propStatus,
+ frame: cropDrag.sourceFrame,
+ value,
+ })
+ : Internals.makeStaticDragOverride(value),
+ );
+ }
+
+ if (transformOrigin !== null) {
+ setDragOverrides(
+ cropDrag.nodePath,
+ transformOriginFieldKey,
+ Internals.makeStaticDragOverride(transformOrigin),
+ );
+ }
+ };
+
+ const onPointerUp = () => {
+ window.removeEventListener('pointermove', onPointerMove);
+ window.removeEventListener('pointerup', onPointerUp);
+ window.removeEventListener('pointercancel', onPointerUp);
+ if (dragStarted) {
+ stopForcingSpecificCursor();
+ onDraggingChange(false);
+ }
+
+ const changes = getSelectedOutlineCropDragChanges({
+ dimensions: outline.dimensions,
+ target: cropDrag,
+ values: lastValues,
+ });
+ const staticChanges = changes.filter(
+ (change): change is SelectedOutlineStaticDragChange =>
+ change.type === 'static',
+ );
+ const keyframedChanges = changes.filter(
+ (change): change is SelectedOutlineKeyframedDragChange =>
+ change.type === 'keyframed',
+ );
+
+ const promise =
+ staticChanges.length === 0
+ ? callAddKeyframes({
+ sequenceKeyframes: keyframedChanges,
+ effectKeyframes: [],
+ setPropStatuses,
+ clientId: cropDrag.clientId,
+ })
+ : saveSequenceProps({
+ changes: staticChanges,
+ addedKeyframes: keyframedChanges,
+ movedKeyframes: null,
+ setPropStatuses,
+ clientId: cropDrag.clientId,
+ undoLabel: 'Crop sequence',
+ redoLabel: 'Crop sequence back',
+ });
+
+ promise
+ .catch((err) => {
+ showNotification(
+ `Could not save crop: ${
+ err instanceof Error ? err.message : String(err)
+ }`,
+ 4000,
+ );
+ })
+ .finally(() => {
+ clearDragOverrides(cropDrag.nodePath);
+ });
+ };
+
+ window.addEventListener('pointermove', onPointerMove);
+ window.addEventListener('pointerup', onPointerUp);
+ window.addEventListener('pointercancel', onPointerUp);
+ },
+ [
+ clearDragOverrides,
+ cropDrag,
+ cursor,
+ handle,
+ onDraggingChange,
+ outline.dimensions,
+ outline.points,
+ outline.uncroppedPoints,
+ setDragOverrides,
+ setPropStatuses,
+ ],
+ );
+
+ return (
+ <>
+ <path
+ d={path}
+ fill="none"
+ stroke={TRANSPARENT}
+ strokeWidth={CROP_HANDLE_HIT_WIDTH}
+ strokeLinejoin="miter"
+ vectorEffect="non-scaling-stroke"
+ pointerEvents="stroke"
+ cursor={cursor}
+ onPointerDown={onPointerDown}
+ />
+ <path
+ d={path}
+ fill="none"
+ stroke={BLUE}
+ strokeWidth={CROP_HANDLE_THICKNESS}
+ strokeLinejoin="miter"
+ strokeLinecap="butt"
+ vectorEffect="non-scaling-stroke"
+ pointerEvents="none"
+ style={{filter: SELECTED_OUTLINE_DROP_SHADOW}}
+ />
+ </>
+ );
+};
+
+export const SelectedOutlineCropControls: React.FC<{
+ readonly outline: SelectedOutline;
+ readonly onDraggingChange: (dragging: boolean) => void;
+ readonly target: SelectedOutlineTarget | undefined;
+}> = ({outline, onDraggingChange, target}) => {
+ useCropPreview(target);
+
+ if (target?.cropDrag === null || target?.cropDrag === undefined) {
+ return null;
+ }
+
+ return (
+ <g aria-hidden="true">
+ {cropHandles.map((handle) => (
+ <CropHandle
+ key={handle}
+ handle={handle}
+ outline={outline}
+ onDraggingChange={onDraggingChange}
+ target={target}
+ />
+ ))}
+ </g>
+ );
+};
diff --git a/packages/studio/src/components/SelectedOutlineElement.tsx b/packages/studio/src/components/SelectedOutlineElement.tsx
index c84e0bc782..63c111dfa4 100644
--- a/packages/studio/src/components/SelectedOutlineElement.tsx
+++ b/packages/studio/src/components/SelectedOutlineElement.tsx
@@ -77,6 +77,7 @@ import {
type SelectedOutlineSnapTarget,
} from './selected-outline-snap';
import {
+ cropFieldKeys,
rotateFieldKey,
scaleFieldKey,
transformOriginFieldKey,
@@ -91,6 +92,7 @@ import {
getUvCoordinateForPoint,
getUvHandlePosition,
} from './selected-outline-uv';
+import {SelectedOutlineCropControls} from './SelectedOutlineCropControls';
import {callAddKeyframes} from './Timeline/call-add-keyframe';
import {disableSequenceInteractivity} from './Timeline/disable-sequence-interactivity';
import {duplicateSequencesFromSource} from './Timeline/duplicate-selected-timeline-item';
@@ -126,6 +128,8 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
);
const {editorSnapping} = useContext(EditorSnappingContext);
const transformOriginDrag = target?.transformOriginDrag ?? null;
+ const crop = target?.crop;
+ const transformOriginPoints = outline.uncroppedPoints ?? outline.points;
const parsed = useMemo(
() =>
@@ -146,8 +150,8 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
});
}, [outline.dimensions, parsed]);
const position = useMemo(
- () => (uv === null ? null : getUvHandlePosition(outline.points, uv)),
- [outline.points, uv],
+ () => (uv === null ? null : getUvHandlePosition(transformOriginPoints, uv)),
+ [transformOriginPoints, uv],
);
const onPointerDown = React.useCallback(
@@ -205,7 +209,7 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
x: currentPointerX - svgRect.left,
y: currentPointerY - svgRect.top,
};
- const rawUv = getUvCoordinateForPoint(outline.points, point);
+ const rawUv = getUvCoordinateForPoint(transformOriginPoints, point);
const lockedAxis = getSelectedOutlineTransformOriginLockedAxis({
axisLocked,
dimensions,
@@ -220,11 +224,13 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
const snapPoint =
lockedAxis === null
? point
- : getUvHandlePosition(outline.points, axisLockedUv);
+ : getUvHandlePosition(transformOriginPoints, axisLockedUv);
const snappedUv = editorSnapping
? snapSelectedOutlineTransformOriginUv({
+ crop: crop ?? null,
point: snapPoint,
- points: outline.points,
+ points: transformOriginPoints,
+ thresholdPx: null,
uv: axisLockedUv,
})
: axisLockedUv;
@@ -391,6 +397,7 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
},
[
clearDragOverrides,
+ crop,
editorSnapping,
onDraggingChange,
outline,
@@ -398,6 +405,7 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
setDragOverrides,
setPropStatuses,
transformOriginDrag,
+ transformOriginPoints,
uv,
],
);
@@ -1219,7 +1227,7 @@ const SelectedOutlineRotationCornerHandle: React.FC<{
const center = svgPointToClientPoint(
getSelectedOutlineRotationPivot({
dimensions: outline.dimensions,
- points: outline.points,
+ points: outline.uncroppedPoints ?? outline.points,
transformOriginValue: rotationDrag.transformOriginValue,
}),
svgRect,
@@ -1416,6 +1424,7 @@ const SelectedOutlineRotationCornerHandle: React.FC<{
onDraggingChange,
outline.dimensions,
outline.points,
+ outline.uncroppedPoints,
onSelect,
rotationDrag,
selected,
@@ -1612,6 +1621,7 @@ export const SelectedOutlineElement: React.FC<{
target.nodePathInfo.supportsEffects &&
!sourceEditDisabled &&
previewServerState.type === 'connected';
+ const canCrop = target.canCrop && !sourceEditDisabled;
return getSequenceContextMenuItems({
assetLinkInfo,
@@ -1723,12 +1733,40 @@ export const SelectedOutlineElement: React.FC<{
subMenu: null,
value: 'add-effect',
},
- {
- type: 'divider' as const,
- id: 'add-effect-divider',
- },
]
: []),
+ {
+ type: 'item' as const,
+ id: 'crop',
+ keyHint: null,
+ label: 'Crop',
+ leftItem: null,
+ disabled: !canCrop,
+ onClick: () => {
+ if (!canCrop) {
+ return;
+ }
+
+ onSelect(
+ {
+ type: 'sequence-prop',
+ nodePathInfo: {
+ ...target.nodePathInfo,
+ auxiliaryKeys: ['controls', cropFieldKeys.left],
+ },
+ key: cropFieldKeys.left,
+ },
+ {shiftKey: false, toggleKey: false},
+ );
+ },
+ quickSwitcherLabel: null,
+ subMenu: null,
+ value: 'crop',
+ },
+ {
+ type: 'divider' as const,
+ id: 'crop-divider',
+ },
],
});
}, [
@@ -1761,7 +1799,12 @@ export const SelectedOutlineElement: React.FC<{
snapTargets={snapTargets}
target={target}
/>
- {target?.containsSelection || hovered
+ <SelectedOutlineCropControls
+ outline={outline}
+ onDraggingChange={onDraggingChange}
+ target={target}
+ />
+ {target?.cropDrag === null && (target.containsSelection || hovered)
? (['top', 'right', 'bottom', 'left'] as const).map((edge) => (
<SelectedOutlineScaleEdgeLine
key={edge}
@@ -1778,7 +1821,7 @@ export const SelectedOutlineElement: React.FC<{
/>
))
: null}
- {target?.containsSelection || hovered
+ {target?.cropDrag === null && (target.containsSelection || hovered)
? (
['top-left', 'top-right', 'bottom-right', 'bottom-left'] as const
).map((corner) => (
diff --git a/packages/studio/src/components/SelectedOutlineOverlay.tsx b/packages/studio/src/components/SelectedOutlineOverlay.tsx
index 80991b8b88..0e8b2256dc 100644
--- a/packages/studio/src/components/SelectedOutlineOverlay.tsx
+++ b/packages/studio/src/components/SelectedOutlineOverlay.tsx
@@ -36,6 +36,7 @@ import {
} from './selected-outline-drag';
import {type SelectedOutline} from './selected-outline-geometry';
import {
+ getSelectedCropInfo,
getSelectedEffectFieldsBySequenceKey,
getSelectedSequenceKeys,
getSelectedTransformOriginInfo,
@@ -50,10 +51,14 @@ import {
type SelectedOutlineSnapPoint,
} from './selected-outline-snap';
import {
+ canEditSelectedOutlineCrop,
+ cropFieldKeys,
rotateFieldKey,
scaleFieldKey,
transformOriginFieldKey,
translateFieldKey,
+ type SelectedOutlineCropDragTarget,
+ type SelectedOutlineCropFieldKey,
type SelectedOutlineKeyboardNudgeSession,
type SelectedOutlineTarget,
} from './selected-outline-types';
@@ -81,6 +86,9 @@ export {
applySelectedOutlineTransformOriginAxisLock,
compensateTranslateForTransformOrigin,
getSelectedOutlineActiveSchema,
+ getSelectedOutlineCropDragChanges,
+ getSelectedOutlineCropDragValues,
+ getSelectedOutlineCropFollowingTransformOrigin,
getSelectedOutlineDragChanges,
getSelectedOutlineDragValues,
getSelectedOutlineKeyboardNudgeDelta,
@@ -103,6 +111,7 @@ export {
} from './selected-outline-drag';
export {
getOutlineSelectionInteraction,
+ getSelectedCropInfo,
getSelectedEffectFieldsBySequenceKey,
getSelectedOutlineRotationCornerInfo,
getSelectedOutlineRotationDeltaDegrees,
@@ -113,13 +122,6 @@ export {
} from './selected-outline-measurement';
export {selectedOutlineDragThresholdPx} from './selected-outline-types';
-const cropFieldKeys = {
- left: 'cropLeft',
- right: 'cropRight',
- top: 'cropTop',
- bottom: 'cropBottom',
-} as const;
-
const getEffectiveCropValue = ({
activeSchema,
controls,
@@ -156,6 +158,49 @@ const getEffectiveCropValue = ({
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
};
+const getCropDragFields = ({
+ activeSchema,
+ cropValues,
+ propStatuses,
+}: {
+ readonly activeSchema: InteractivitySchema | null;
+ readonly cropValues: Record<SelectedOutlineCropFieldKey, number>;
+ readonly propStatuses: ReturnType<typeof Internals.getPropStatusesCtx>;
+}): SelectedOutlineCropDragTarget['fields'] | null => {
+ if (
+ !canEditSelectedOutlineCrop({
+ schema: activeSchema,
+ propStatuses,
+ })
+ ) {
+ return null;
+ }
+
+ const fields: Partial<SelectedOutlineCropDragTarget['fields']> = {};
+
+ for (const fieldKey of Object.values(cropFieldKeys)) {
+ const fieldSchema = activeSchema?.[fieldKey];
+ const propStatus = propStatuses?.[fieldKey];
+ const canEditStatus =
+ propStatus?.status === 'static' ||
+ (propStatus?.status === 'keyframed' &&
+ propStatus.interpolationFunction === 'interpolate');
+
+ if (fieldSchema?.type !== 'number' || !canEditStatus) {
+ return null;
+ }
+
+ fields[fieldKey] = {
+ defaultValue: fieldSchema.default,
+ fieldSchema,
+ propStatus,
+ value: cropValues[fieldKey],
+ };
+ }
+
+ return fields as SelectedOutlineCropDragTarget['fields'];
+};
+
export type {
SelectedOutlineDragState,
SelectedOutlineRotationDragState,
@@ -668,6 +713,7 @@ export const SelectedOutlineOverlay: React.FC<{
getSelectedEffectFieldsBySequenceKey(selectedItems);
const selectedTransformOriginInfo =
getSelectedTransformOriginInfo(selectedItems);
+ const selectedCropInfo = getSelectedCropInfo(selectedItems);
const clientId =
previewServerState.type === 'connected'
? previewServerState.clientId
@@ -703,7 +749,7 @@ export const SelectedOutlineOverlay: React.FC<{
frame: sourceFrame,
})
: null;
- const crop = Internals.resolveSequenceCrop({
+ const cropValues = {
cropLeft: getEffectiveCropValue({
activeSchema,
controls,
@@ -736,6 +782,12 @@ export const SelectedOutlineOverlay: React.FC<{
frame: sourceFrame,
propStatuses: nodePropStatuses,
}),
+ };
+ const crop = Internals.resolveSequenceCrop(cropValues);
+ const cropFields = getCropDragFields({
+ activeSchema,
+ cropValues,
+ propStatuses: nodePropStatuses,
});
const fieldSchema = activeSchema?.[translateFieldKey];
const propStatus = nodePropStatuses?.[translateFieldKey];
@@ -811,12 +863,45 @@ export const SelectedOutlineOverlay: React.FC<{
fieldSchema?.type === 'translate' &&
canTransformOriginStatus &&
canTransformOriginTranslateStatus;
+ const selectedForCrop = selectedCropInfo?.sequenceKey === key;
+ const cropSourceFrame =
+ selectedCropInfo?.displayFrame === null ||
+ selectedCropInfo?.displayFrame === undefined
+ ? sourceFrame
+ : selectedCropInfo.displayFrame - keyframeDisplayOffset;
+ const canCropDrag =
+ previewServerState.type === 'connected' &&
+ selectedForCrop &&
+ controls !== null &&
+ cropFields !== null;
const canDropEffect =
previewServerState.type === 'connected' &&
controls?.supportsEffects === true;
return {
key,
+ canCrop:
+ previewServerState.type === 'connected' &&
+ controls !== null &&
+ cropFields !== null,
crop,
+ cropDrag: canCropDrag
+ ? {
+ clientId: previewServerState.clientId,
+ fields: cropFields,
+ nodePath,
+ schema: controls.schema,
+ sourceFrame: cropSourceFrame,
+ transformOrigin:
+ transformOriginFieldSchema?.type === 'transform-origin' &&
+ transformOriginPropStatus !== undefined
+ ? {
+ defaultValue: transformOriginFieldSchema.default,
+ propStatus: transformOriginPropStatus,
+ value: transformOriginValueForRotation,
+ }
+ : null,
+ }
+ : null,
containsSelection,
effectDrop: canDropEffect
? {
diff --git a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
index 32a5633052..fae7ad4209 100644
--- a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
@@ -47,6 +47,10 @@ import {
import {useSelectComposition} from '../InitialCompositionLoader';
import {Spacing} from '../layout';
import {showNotification} from '../Notifications/NotificationCenter';
+import {
+ canEditSelectedOutlineCrop,
+ cropFieldKeys,
+} from '../selected-outline-types';
import {useSelectAsset} from '../use-select-asset';
import {disableSequenceInteractivity} from './disable-sequence-interactivity';
import {duplicateSequencesFromSource} from './duplicate-selected-timeline-item';
@@ -268,7 +272,7 @@ export const TimelineSequenceItem: React.FC<{
const selectComposition = useSelectComposition();
const {onSelect, selectable, selected, selectionItem} =
useTimelineRowSelection(nodePathInfo);
- const {selectedItems} = useTimelineSelection();
+ const {selectItem, selectedItems} = useTimelineSelection();
const containsSelection = useTimelineRowContainsSelection(nodePathInfo);
const [effectDropHovered, setEffectDropHovered] = useState(false);
const [isRenaming, setIsRenaming] = useState(false);
@@ -889,6 +893,32 @@ export const TimelineSequenceItem: React.FC<{
nodePathInfo?.supportsEffects === true &&
previewInteractive &&
Boolean(validatedLocation?.source);
+ const canCrop = useMemo(() => {
+ if (
+ !previewInteractive ||
+ !sequence.controls ||
+ !nodePathInfo ||
+ !propStatusesForOverride ||
+ !validatedLocation?.source
+ ) {
+ return false;
+ }
+
+ const activeSchema = Internals.flattenActiveSchema(
+ sequence.controls.schema,
+ (key) => sequence.controls?.currentRuntimeValueDotNotation[key],
+ );
+ return canEditSelectedOutlineCrop({
+ schema: activeSchema,
+ propStatuses: propStatusesForOverride,
+ });
+ }, [
+ nodePathInfo,
+ previewInteractive,
+ propStatusesForOverride,
+ sequence.controls,
+ validatedLocation?.source,
+ ]);
const onAddEffect = useCallback(() => {
if (
@@ -914,6 +944,26 @@ export const TimelineSequenceItem: React.FC<{
validatedLocation?.source,
]);
+ const onCrop = useCallback(() => {
+ if (!canCrop || !nodePathInfo) {
+ return;
+ }
+
+ selectItem(
+ {
+ type: 'sequence-prop',
+ nodePathInfo: {
+ ...nodePathInfo,
+ auxiliaryKeys: ['controls', cropFieldKeys.left],
+ },
+ key: cropFieldKeys.left,
+ },
+ undefined,
+ undefined,
+ {reveal: true},
+ );
+ }, [canCrop, nodePathInfo, selectItem]);
+
const contextMenuValues = useMemo(() => {
if (!previewConnected) {
return [];
@@ -950,12 +1000,24 @@ export const TimelineSequenceItem: React.FC<{
subMenu: null,
value: 'add-effect',
},
- {
- type: 'divider' as const,
- id: 'add-effect-divider',
- },
]
: []),
+ {
+ type: 'item' as const,
+ id: 'crop',
+ keyHint: null,
+ label: 'Crop',
+ leftItem: null,
+ disabled: !canCrop,
+ onClick: onCrop,
+ quickSwitcherLabel: null,
+ subMenu: null,
+ value: 'crop',
+ },
+ {
+ type: 'divider' as const,
+ id: 'crop-divider',
+ },
{
type: 'item' as const,
id: 'rename-sequence',
@@ -977,6 +1039,7 @@ export const TimelineSequenceItem: React.FC<{
}, [
assetLinkInfo,
canAddEffect,
+ canCrop,
canOpenInEditor,
canRenameThisSequence,
deleteDisabled,
@@ -986,6 +1049,7 @@ export const TimelineSequenceItem: React.FC<{
freezeFrameMenuItem,
nodePathInfo?.supportsEffects,
onAddEffect,
+ onCrop,
onDeleteSequenceFromSource,
onDisableSequenceInteractivity,
onDuplicateSequenceFromSource,
diff --git a/packages/studio/src/components/composition-drop-preview.ts b/packages/studio/src/components/composition-drop-preview.ts
index 295978216f..2fe8b528fa 100644
--- a/packages/studio/src/components/composition-drop-preview.ts
+++ b/packages/studio/src/components/composition-drop-preview.ts
@@ -50,6 +50,7 @@ export const snapCompositionDropPosition = ({
const outline: SelectedOutline = {
key: 'composition-drop-preview',
dimensions: compositionDimensions,
+ uncroppedPoints: null,
points: [
{x: left * scale, y: top * scale},
{x: right * scale, y: top * scale},
diff --git a/packages/studio/src/components/selected-outline-drag.ts b/packages/studio/src/components/selected-outline-drag.ts
index 3d84dbd59c..1a308cef1a 100644
--- a/packages/studio/src/components/selected-outline-drag.ts
+++ b/packages/studio/src/components/selected-outline-drag.ts
@@ -2,8 +2,8 @@ import type {
CanUpdateSequencePropStatus,
DragOverrideValue,
GetDragOverrides,
- SequencePropsSubscriptionKey,
InteractivitySchema,
+ SequencePropsSubscriptionKey,
} from 'remotion';
import {Internals} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
@@ -18,15 +18,20 @@ import {
vectorLength,
} from './selected-outline-measurement';
import type {
+ SelectedOutlineCropDragTarget,
+ SelectedOutlineCropFieldKey,
+ SelectedOutlineCropHandle,
SelectedOutlineDragState,
+ SelectedOutlineDragTarget,
SelectedOutlineRotationDragState,
SelectedOutlineRotationDragTarget,
SelectedOutlineScaleDragState,
SelectedOutlineScaleDragTarget,
- SelectedOutlineDragTarget,
+ SelectedOutlineTarget,
SelectedOutlineTransformOriginDragTarget,
} from './selected-outline-types';
import {
+ cropFieldKeys,
rotateFieldKey,
scaleFieldKey,
selectedOutlineDragThresholdPx,
@@ -49,6 +54,11 @@ import {
serializeTranslate,
} from './Timeline/timeline-translate-utils';
import {getLinkedScale} from './Timeline/TimelineScaleField';
+import {
+ parseTransformOrigin,
+ parsedTransformOriginToUv,
+ serializeTransformOrigin,
+} from './Timeline/transform-origin-utils';
export const getSelectedOutlineActiveSchema = ({
schema,
@@ -240,6 +250,212 @@ export const getSelectedOutlineDragChanges = ({
return changes;
};
+export type SelectedOutlineCropValues = Record<
+ SelectedOutlineCropFieldKey,
+ number
+>;
+
+const getSelectedOutlineCropCenter = (
+ crop: SelectedOutlineCropValues,
+): UvCoordinate => [
+ (crop.cropLeft + 1 - crop.cropRight) / 2,
+ (crop.cropTop + 1 - crop.cropBottom) / 2,
+];
+
+export const getSelectedOutlineCropFollowingTransformOrigin = ({
+ dimensions,
+ initialCrop,
+ nextCrop,
+ transformOrigin,
+}: {
+ readonly dimensions: SelectedOutline['dimensions'];
+ readonly initialCrop: SelectedOutlineCropValues;
+ readonly nextCrop: SelectedOutlineCropValues;
+ readonly transformOrigin: SelectedOutlineCropDragTarget['transformOrigin'];
+}): string | null => {
+ if (
+ dimensions === null ||
+ transformOrigin === null ||
+ transformOrigin.propStatus.status !== 'static'
+ ) {
+ return null;
+ }
+
+ const parsed = parseTransformOrigin(transformOrigin.value);
+ if (parsed === null) {
+ return null;
+ }
+
+ const currentOrigin = parsedTransformOriginToUv({
+ parsed,
+ width: dimensions.width,
+ height: dimensions.height,
+ });
+ if (currentOrigin === null) {
+ return null;
+ }
+
+ const initialCenter = getSelectedOutlineCropCenter(initialCrop);
+ const originIsAbsent = transformOrigin.propStatus.codeValue === undefined;
+ const originIsAtCropCenter =
+ Math.abs(currentOrigin[0] - initialCenter[0]) <= 0.0001 &&
+ Math.abs(currentOrigin[1] - initialCenter[1]) <= 0.0001;
+ if (!originIsAbsent && !originIsAtCropCenter) {
+ return null;
+ }
+
+ return serializeTransformOrigin({
+ uv: getSelectedOutlineCropCenter(nextCrop),
+ z: parsed.z,
+ });
+};
+
+const cropHandleIncludes = (
+ handle: SelectedOutlineCropHandle,
+ edge: 'left' | 'right' | 'top' | 'bottom',
+) => handle === edge || handle.includes(edge);
+
+export const getSelectedOutlineCropDragValues = ({
+ crop,
+ dimensions,
+ handle,
+ uv,
+}: {
+ readonly crop: SelectedOutlineCropValues;
+ readonly dimensions: SelectedOutline['dimensions'];
+ readonly handle: SelectedOutlineCropHandle;
+ readonly uv: readonly [number, number];
+}): SelectedOutlineCropValues => {
+ const minimumVisibleX = dimensions === null ? 0.001 : 1 / dimensions.width;
+ const minimumVisibleY = dimensions === null ? 0.001 : 1 / dimensions.height;
+ const roundCrop = (value: number, max: number) =>
+ clamp(roundToDecimalPlaces(value, 4), 0, Math.max(0, max));
+ const next = {...crop};
+
+ if (cropHandleIncludes(handle, 'left')) {
+ next.cropLeft = roundCrop(uv[0], 1 - crop.cropRight - minimumVisibleX);
+ }
+
+ if (cropHandleIncludes(handle, 'right')) {
+ next.cropRight = roundCrop(1 - uv[0], 1 - crop.cropLeft - minimumVisibleX);
+ }
+
+ if (cropHandleIncludes(handle, 'top')) {
+ next.cropTop = roundCrop(uv[1], 1 - crop.cropBottom - minimumVisibleY);
+ }
+
+ if (cropHandleIncludes(handle, 'bottom')) {
+ next.cropBottom = roundCrop(1 - uv[1], 1 - crop.cropTop - minimumVisibleY);
+ }
+
+ return next;
+};
+
+export const getSelectedOutlineCropDragChanges = ({
+ dimensions,
+ target,
+ values,
+}: {
+ readonly dimensions: SelectedOutline['dimensions'];
+ readonly target: SelectedOutlineCropDragTarget;
+ readonly values: SelectedOutlineCropValues;
+}): SelectedOutlineDragChange[] => {
+ const changes: SelectedOutlineDragChange[] = [];
+
+ for (const fieldKey of Object.values(cropFieldKeys)) {
+ const field = target.fields[fieldKey];
+ const value = values[fieldKey];
+ if (value === field.value) {
+ continue;
+ }
+
+ if (field.propStatus.status === 'keyframed') {
+ changes.push({
+ type: 'keyframed',
+ fileName: target.nodePath.absolutePath,
+ nodePath: target.nodePath,
+ fieldKey,
+ sourceFrame: target.sourceFrame,
+ value,
+ schema: target.schema,
+ clientId: target.clientId,
+ });
+ continue;
+ }
+
+ const defaultValue =
+ field.defaultValue === undefined
+ ? null
+ : JSON.stringify(field.defaultValue);
+ const stringifiedValue = JSON.stringify(value);
+ const shouldSave =
+ value !== field.propStatus.codeValue &&
+ !(
+ defaultValue === stringifiedValue &&
+ field.propStatus.codeValue === undefined
+ );
+
+ if (shouldSave) {
+ changes.push({
+ type: 'static',
+ fileName: target.nodePath.absolutePath,
+ nodePath: target.nodePath,
+ fieldKey,
+ value,
+ defaultValue,
+ schema: target.schema,
+ });
+ }
+ }
+
+ if (
+ changes.length === 0 ||
+ target.transformOrigin === null ||
+ target.transformOrigin.propStatus.status !== 'static'
+ ) {
+ return changes;
+ }
+
+ const transformOrigin = getSelectedOutlineCropFollowingTransformOrigin({
+ dimensions,
+ initialCrop: {
+ cropLeft: target.fields.cropLeft.value,
+ cropRight: target.fields.cropRight.value,
+ cropTop: target.fields.cropTop.value,
+ cropBottom: target.fields.cropBottom.value,
+ },
+ nextCrop: values,
+ transformOrigin: target.transformOrigin,
+ });
+ if (transformOrigin === null) {
+ return changes;
+ }
+
+ const transformOriginDefaultValue =
+ target.transformOrigin.defaultValue === undefined
+ ? null
+ : JSON.stringify(target.transformOrigin.defaultValue);
+ const shouldSaveTransformOrigin =
+ transformOrigin !== target.transformOrigin.propStatus.codeValue &&
+ !(
+ transformOriginDefaultValue === JSON.stringify(transformOrigin) &&
+ target.transformOrigin.propStatus.codeValue === undefined
+ );
+ if (shouldSaveTransformOrigin) {
+ changes.push({
+ type: 'static',
+ fileName: target.nodePath.absolutePath,
+ nodePath: target.nodePath,
+ fieldKey: transformOriginFieldKey,
+ value: transformOrigin,
+ defaultValue: transformOriginDefaultValue,
+ schema: target.schema,
+ });
+ }
+
+ return changes;
+};
+
export type SelectedOutlineKeyboardNudgeDirection =
| 'left'
| 'right'
@@ -946,4 +1162,68 @@ export const snapSelectedOutlineUv = ({
export const selectedOutlineTransformOriginSnapThresholdPx =
selectedOutlineUvSnapThresholdPx;
-export const snapSelectedOutlineTransformOriginUv = snapSelectedOutlineUv;
+const getCroppedOutlineUvSnapTargets = (
+ crop: SelectedOutlineTarget['crop'],
+): readonly UvCoordinate[] => {
+ const {left, top} = crop;
+ const right = 1 - crop.right;
+ const bottom = 1 - crop.bottom;
+ const centerX = (left + right) / 2;
+ const centerY = (top + bottom) / 2;
+
+ return [
+ [left, top],
+ [centerX, top],
+ [right, top],
+ [right, centerY],
+ [right, bottom],
+ [centerX, bottom],
+ [left, bottom],
+ [left, centerY],
+ [centerX, centerY],
+ ];
+};
+
+export const snapSelectedOutlineTransformOriginUv = ({
+ crop,
+ point,
+ points,
+ thresholdPx,
+ uv,
+}: {
+ readonly crop: SelectedOutlineTarget['crop'] | null;
+ readonly point: OutlinePoint;
+ readonly points: SelectedOutline['points'];
+ readonly thresholdPx: number | null;
+ readonly uv: UvCoordinate;
+}): UvCoordinate => {
+ const threshold =
+ thresholdPx ?? selectedOutlineTransformOriginSnapThresholdPx;
+
+ if (crop === null) {
+ return snapSelectedOutlineUv({point, points, thresholdPx: threshold, uv});
+ }
+
+ let best: {
+ readonly distance: number;
+ readonly uv: UvCoordinate;
+ } | null = null;
+ const snapTargets = [
+ ...selectedOutlineUvSnapTargets,
+ ...getCroppedOutlineUvSnapTargets(crop),
+ ];
+
+ for (const snapUv of snapTargets) {
+ const snapPoint = getUvHandlePosition(points, snapUv);
+ const distance = Math.hypot(point.x - snapPoint.x, point.y - snapPoint.y);
+ if (distance > threshold) {
+ continue;
+ }
+
+ if (best === null || distance < best.distance) {
+ best = {distance, uv: snapUv};
+ }
+ }
+
+ return best?.uv ?? uv;
+};
diff --git a/packages/studio/src/components/selected-outline-geometry.ts b/packages/studio/src/components/selected-outline-geometry.ts
index c6990ef27b..504f10bec5 100644
--- a/packages/studio/src/components/selected-outline-geometry.ts
+++ b/packages/studio/src/components/selected-outline-geometry.ts
@@ -9,6 +9,9 @@ export type SelectedOutline = {
readonly width: number;
readonly height: number;
} | null;
+ readonly uncroppedPoints:
+ | readonly [OutlinePoint, OutlinePoint, OutlinePoint, OutlinePoint]
+ | null;
readonly points: readonly [
OutlinePoint,
OutlinePoint,
diff --git a/packages/studio/src/components/selected-outline-measurement.ts b/packages/studio/src/components/selected-outline-measurement.ts
index 298a51bbd2..1801953083 100644
--- a/packages/studio/src/components/selected-outline-measurement.ts
+++ b/packages/studio/src/components/selected-outline-measurement.ts
@@ -8,7 +8,7 @@ import type {
SelectedOutlineTarget,
SequenceWithSelectedOutline,
} from './selected-outline-types';
-import {transformOriginFieldKey} from './selected-outline-types';
+import {cropFieldKeys, transformOriginFieldKey} from './selected-outline-types';
import {getUvHandlePosition} from './selected-outline-uv';
import {parseKeyframeFieldFromNodePath} from './Timeline/parse-keyframe-field-from-node-path';
import {
@@ -17,8 +17,8 @@ import {
type TimelineSelectionInteraction,
} from './Timeline/TimelineSelection';
import {
- parseTransformOrigin,
parsedTransformOriginToUv,
+ parseTransformOrigin,
} from './Timeline/transform-origin-utils';
export const pointToString = (point: OutlinePoint) => `${point.x},${point.y}`;
@@ -456,6 +456,50 @@ type SelectedTransformOriginInfo = {
readonly displayFrame: number | null;
};
+export type SelectedCropInfo = {
+ readonly sequenceKey: string;
+ readonly displayFrame: number | null;
+};
+
+const isCropFieldKey = (key: string): boolean =>
+ Object.values(cropFieldKeys).some((cropFieldKey) => cropFieldKey === key);
+
+export const getSelectedCropInfo = (
+ selectedItems: readonly TimelineSelection[],
+): SelectedCropInfo | null => {
+ if (selectedItems.length !== 1) {
+ return null;
+ }
+
+ const [selectedItem] = selectedItems;
+ if (
+ selectedItem.type === 'sequence-prop' &&
+ isCropFieldKey(selectedItem.key)
+ ) {
+ return {
+ sequenceKey: getTimelineSequenceSelectionKey(selectedItem.nodePathInfo),
+ displayFrame: null,
+ };
+ }
+
+ if (selectedItem.type !== 'keyframe' && selectedItem.type !== 'easing') {
+ return null;
+ }
+
+ const field = getKeyframeOrEasingField(selectedItem);
+ if (field?.type !== 'sequence' || !isCropFieldKey(field.fieldKey)) {
+ return null;
+ }
+
+ return {
+ sequenceKey: getTimelineSequenceSelectionKey(selectedItem.nodePathInfo),
+ displayFrame:
+ selectedItem.type === 'keyframe'
+ ? selectedItem.frame
+ : selectedItem.fromFrame,
+ };
+};
+
export const getSelectedTransformOriginInfo = (
selectedItems: readonly TimelineSelection[],
): SelectedTransformOriginInfo | null => {
@@ -574,6 +618,7 @@ export const measureOutlines = (
height: element.height.baseVal.value,
}
: null,
+ uncroppedPoints,
points,
});
}
@@ -601,6 +646,23 @@ export const outlinesAreEqual = (
return false;
}
+ const aUncropped = a[i].uncroppedPoints;
+ const bUncropped = b[i].uncroppedPoints;
+ if ((aUncropped === null) !== (bUncropped === null)) {
+ return false;
+ }
+
+ if (aUncropped !== null && bUncropped !== null) {
+ for (let j = 0; j < aUncropped.length; j++) {
+ if (
+ Math.abs(aUncropped[j].x - bUncropped[j].x) > 0.01 ||
+ Math.abs(aUncropped[j].y - bUncropped[j].y) > 0.01
+ ) {
+ return false;
+ }
+ }
+ }
+
for (let j = 0; j < a[i].points.length; j++) {
if (
Math.abs(a[i].points[j].x - b[i].points[j].x) > 0.01 ||
diff --git a/packages/studio/src/components/selected-outline-types.ts b/packages/studio/src/components/selected-outline-types.ts
index 68592887b5..5969576094 100644
--- a/packages/studio/src/components/selected-outline-types.ts
+++ b/packages/studio/src/components/selected-outline-types.ts
@@ -1,4 +1,5 @@
import type {
+ CanUpdateSequencePropStatus,
CanUpdateSequencePropStatusKeyframed,
CanUpdateSequencePropStatusStatic,
InteractivitySchema,
@@ -22,6 +23,7 @@ export type SelectedOutlineContextMenuOpenHandler = () =>
export type SelectedOutlineTarget = {
readonly key: string;
+ readonly canCrop: boolean;
readonly containsSelection: boolean;
readonly effectDrop: SelectedOutlineEffectDropTarget | null;
readonly nodePathInfo: SequenceNodePathInfo;
@@ -35,6 +37,7 @@ export type SelectedOutlineTarget = {
readonly top: number;
readonly bottom: number;
};
+ readonly cropDrag: SelectedOutlineCropDragTarget | null;
readonly drag: SelectedOutlineDragTarget | null;
readonly scaleDrag: SelectedOutlineScaleDragTarget | null;
readonly rotationDrag: SelectedOutlineRotationDragTarget | null;
@@ -42,6 +45,82 @@ export type SelectedOutlineTarget = {
readonly uvHandles: readonly SelectedOutlineUvHandle[];
};
+export const cropFieldKeys = {
+ left: 'cropLeft',
+ right: 'cropRight',
+ top: 'cropTop',
+ bottom: 'cropBottom',
+} as const;
+
+export type SelectedOutlineCropEdge = keyof typeof cropFieldKeys;
+export type SelectedOutlineCropFieldKey =
+ (typeof cropFieldKeys)[SelectedOutlineCropEdge];
+
+export const canEditSelectedOutlineCrop = ({
+ schema,
+ propStatuses,
+}: {
+ readonly schema: InteractivitySchema | null;
+ readonly propStatuses:
+ | Record<string, CanUpdateSequencePropStatus>
+ | undefined;
+}): boolean => {
+ for (const fieldKey of Object.values(cropFieldKeys)) {
+ const fieldSchema = schema?.[fieldKey];
+ const propStatus = propStatuses?.[fieldKey];
+ const canEditStatus =
+ propStatus?.status === 'static' ||
+ (propStatus?.status === 'keyframed' &&
+ propStatus.interpolationFunction === 'interpolate');
+
+ if (fieldSchema?.type !== 'number' || !canEditStatus) {
+ return false;
+ }
+ }
+
+ return true;
+};
+
+export type SelectedOutlineCropHandle =
+ | 'top-left'
+ | 'top-right'
+ | 'bottom-left'
+ | 'bottom-right'
+ | 'top'
+ | 'right'
+ | 'bottom'
+ | 'left';
+
+type CropNumberFieldSchema = Extract<
+ InteractivitySchemaField,
+ {type: 'number'}
+>;
+
+export type SelectedOutlineCropField = {
+ readonly defaultValue: number | null | undefined;
+ readonly fieldSchema: CropNumberFieldSchema;
+ readonly propStatus:
+ | CanUpdateSequencePropStatusStatic
+ | CanUpdateSequencePropStatusKeyframed;
+ readonly value: number;
+};
+
+export type SelectedOutlineCropDragTarget = {
+ readonly clientId: string;
+ readonly fields: Record<
+ SelectedOutlineCropFieldKey,
+ SelectedOutlineCropField
+ >;
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly schema: InteractivitySchema;
+ readonly sourceFrame: number;
+ readonly transformOrigin: {
+ readonly defaultValue: string | undefined;
+ readonly propStatus: CanUpdateSequencePropStatus;
+ readonly value: string;
+ } | null;
+};
+
export type SelectedOutlineEffectDropTarget = {
readonly clientId: string;
readonly fileName: string;
diff --git a/packages/studio/src/test/selected-outline-snap.test.ts b/packages/studio/src/test/selected-outline-snap.test.ts
index b73237642d..cf5e8126a7 100644
--- a/packages/studio/src/test/selected-outline-snap.test.ts
+++ b/packages/studio/src/test/selected-outline-snap.test.ts
@@ -26,6 +26,7 @@ const makeOutline = ({
return {
key: 'outline',
dimensions: {width, height},
+ uncroppedPoints: null,
points: [
{x: left * scale, y: top * scale},
{x: right * scale, y: top * scale},
diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.ts
index 9b3c4a8ae7..eaf170baa6 100644
--- a/packages/studio/src/test/timeline-selection.test.ts
+++ b/packages/studio/src/test/timeline-selection.test.ts
@@ -14,12 +14,15 @@ import {getInspectorSelectableItems} from '../components/InspectorSequenceSectio
import type {SelectedOutline} from '../components/selected-outline-geometry';
import {
cropOutlinePoints,
+ getSelectedCropInfo,
getSelectedTransformOriginInfo,
} from '../components/selected-outline-measurement';
import type {
+ SelectedOutlineCropDragTarget,
SelectedOutlineTarget,
SelectedOutlineTransformOriginDragTarget,
} from '../components/selected-outline-types';
+import {canEditSelectedOutlineCrop} from '../components/selected-outline-types';
import {
constrainUv,
getSelectedUvHandles,
@@ -38,6 +41,9 @@ import {
getOutlineSelectionInteraction,
getSelectedEffectFieldsBySequenceKey,
getSelectedOutlineActiveSchema,
+ getSelectedOutlineCropDragChanges,
+ getSelectedOutlineCropDragValues,
+ getSelectedOutlineCropFollowingTransformOrigin,
getSelectedOutlineDragChanges,
getSelectedOutlineDragValues,
getSelectedOutlineKeyboardNudgeDelta,
@@ -85,8 +91,8 @@ import {getTimelinePropResetTargets} from '../components/Timeline/reset-selected
import {shouldSubscribeToSequenceProps} from '../components/Timeline/should-subscribe-to-sequence-props';
import {
getEasingClipboardDataFromSelection,
- getEffectsClipboardEnvelopeFromSelections,
getEffectPropClipboardDataFromSelection,
+ getEffectsClipboardEnvelopeFromSelections,
getPasteEffectPropTarget,
getPasteEffectsTarget,
getSnapshotsFromSelection,
@@ -2964,6 +2970,7 @@ test('Canvas outline rendering preserves unconstrained outline order', () => {
const makeOutline = (key: string): SelectedOutline => ({
key,
dimensions: null,
+ uncroppedPoints: null,
points: [
{x: 0, y: 0},
{x: 10, y: 0},
@@ -3010,6 +3017,7 @@ const makeTestOutline = ({
}): SelectedOutline => ({
key,
dimensions: {width, height},
+ uncroppedPoints: null,
points: [
{x: left, y: top},
{x: left + width, y: top},
@@ -3577,6 +3585,314 @@ test('Sequence crops are projected through perspective transforms', () => {
expect(cropped[3]).toEqual({x: 10, y: 60});
});
+test('Crop handles update normalized crop values and keep one pixel visible', () => {
+ expect(
+ getSelectedOutlineCropDragValues({
+ crop: {
+ cropLeft: 0.1,
+ cropRight: 0.2,
+ cropTop: 0.15,
+ cropBottom: 0.25,
+ },
+ dimensions: {width: 100, height: 200},
+ handle: 'top-right',
+ uv: [0.65, 0.3],
+ }),
+ ).toEqual({
+ cropLeft: 0.1,
+ cropRight: 0.35,
+ cropTop: 0.3,
+ cropBottom: 0.25,
+ });
+
+ expect(
+ getSelectedOutlineCropDragValues({
+ crop: {
+ cropLeft: 0.1,
+ cropRight: 0.2,
+ cropTop: 0.15,
+ cropBottom: 0.25,
+ },
+ dimensions: {width: 100, height: 200},
+ handle: 'left',
+ uv: [1, 0.5],
+ }),
+ ).toEqual({
+ cropLeft: 0.79,
+ cropRight: 0.2,
+ cropTop: 0.15,
+ cropBottom: 0.25,
+ });
+});
+
+test('Crop is only available when all crop fields can be edited', () => {
+ const numberField = {
+ type: 'number' as const,
+ default: 0,
+ hiddenFromList: false,
+ keyframable: true,
+ };
+ const schema = {
+ cropLeft: numberField,
+ cropRight: numberField,
+ cropTop: numberField,
+ cropBottom: numberField,
+ } satisfies InteractivitySchema;
+ const propStatuses = {
+ cropLeft: {status: 'static' as const, codeValue: 0},
+ cropRight: {status: 'static' as const, codeValue: 0},
+ cropTop: {status: 'static' as const, codeValue: 0},
+ cropBottom: {status: 'static' as const, codeValue: 0},
+ };
+
+ expect(canEditSelectedOutlineCrop({schema, propStatuses})).toBe(true);
+ expect(
+ canEditSelectedOutlineCrop({
+ schema,
+ propStatuses: {
+ ...propStatuses,
+ cropRight: {status: 'computed'},
+ },
+ }),
+ ).toBe(false);
+ expect(
+ canEditSelectedOutlineCrop({
+ schema: {
+ cropLeft: numberField,
+ cropRight: numberField,
+ cropTop: numberField,
+ },
+ propStatuses,
+ }),
+ ).toBe(false);
+});
+
+test('Crop handle changes preserve static and keyframed field behavior', () => {
+ const schema = {
+ cropLeft: {
+ type: 'number',
+ default: 0,
+ hiddenFromList: false,
+ keyframable: true,
+ },
+ cropRight: {
+ type: 'number',
+ default: 0,
+ hiddenFromList: false,
+ keyframable: true,
+ },
+ cropTop: {
+ type: 'number',
+ default: 0,
+ hiddenFromList: false,
+ keyframable: true,
+ },
+ cropBottom: {
+ type: 'number',
+ default: 0,
+ hiddenFromList: false,
+ keyframable: true,
+ },
+ } satisfies InteractivitySchema;
+ const nodePath = makeKey(['body', 0]);
+ const staticField = (value: number) => ({
+ defaultValue: 0,
+ fieldSchema: schema.cropLeft,
+ propStatus: {status: 'static' as const, codeValue: value},
+ value,
+ });
+ const target = {
+ clientId: 'client',
+ fields: {
+ cropLeft: staticField(0.1),
+ cropRight: {
+ defaultValue: 0,
+ fieldSchema: schema.cropRight,
+ propStatus: {
+ status: 'keyframed',
+ interpolationFunction: 'interpolate',
+ keyframes: [
+ {frame: 0, value: 0.2},
+ {frame: 20, value: 0.3},
+ ],
+ easing: [{type: 'linear'}],
+ clamping: {left: 'extend', right: 'extend'},
+ posterize: undefined,
+ output: undefined,
+ },
+ value: 0.2,
+ },
+ cropTop: staticField(0.15),
+ cropBottom: staticField(0.25),
+ },
+ nodePath,
+ schema,
+ sourceFrame: 12,
+ transformOrigin: null,
+ } satisfies SelectedOutlineCropDragTarget;
+
+ expect(
+ getSelectedOutlineCropDragChanges({
+ dimensions: {width: 100, height: 200},
+ target,
+ values: {
+ cropLeft: 0.25,
+ cropRight: 0.35,
+ cropTop: 0.15,
+ cropBottom: 0.25,
+ },
+ }),
+ ).toEqual([
+ {
+ type: 'static',
+ fileName: '/project/src/Comp.tsx',
+ nodePath,
+ fieldKey: 'cropLeft',
+ value: 0.25,
+ defaultValue: '0',
+ schema,
+ },
+ {
+ type: 'keyframed',
+ fileName: '/project/src/Comp.tsx',
+ nodePath,
+ fieldKey: 'cropRight',
+ sourceFrame: 12,
+ value: 0.35,
+ schema,
+ clientId: 'client',
+ },
+ ]);
+
+ expect(
+ getSelectedOutlineCropDragChanges({
+ dimensions: {width: 100, height: 200},
+ target: {
+ ...target,
+ transformOrigin: {
+ defaultValue: '50% 50%',
+ propStatus: {status: 'static', codeValue: undefined},
+ value: '50% 50%',
+ },
+ },
+ values: {
+ cropLeft: 0.2,
+ cropRight: 0.2,
+ cropTop: 0.15,
+ cropBottom: 0.25,
+ },
+ }),
+ ).toEqual([
+ {
+ type: 'static',
+ fileName: '/project/src/Comp.tsx',
+ nodePath,
+ fieldKey: 'cropLeft',
+ value: 0.2,
+ defaultValue: '0',
+ schema,
+ },
+ {
+ type: 'static',
+ fileName: '/project/src/Comp.tsx',
+ nodePath,
+ fieldKey: 'style.transformOrigin',
+ value: '50% 45%',
+ defaultValue: '"50% 50%"',
+ schema,
+ },
+ ]);
+});
+
+test('Crop follows an absent or crop-centered static transform origin', () => {
+ const initialCrop = {
+ cropLeft: 0.11,
+ cropRight: 0.64,
+ cropTop: 0,
+ cropBottom: 0.17,
+ };
+ const nextCrop = {...initialCrop, cropLeft: 0.21};
+ const dimensions = {width: 1920, height: 1080};
+
+ expect(
+ getSelectedOutlineCropFollowingTransformOrigin({
+ dimensions,
+ initialCrop,
+ nextCrop,
+ transformOrigin: {
+ defaultValue: '50% 50%',
+ propStatus: {status: 'static', codeValue: undefined},
+ value: '50% 50%',
+ },
+ }),
+ ).toBe('28.5% 41.5%');
+ expect(
+ getSelectedOutlineCropFollowingTransformOrigin({
+ dimensions,
+ initialCrop,
+ nextCrop,
+ transformOrigin: {
+ defaultValue: '50% 50%',
+ propStatus: {status: 'static', codeValue: '23.5% 41.5% 10px'},
+ value: '23.5% 41.5% 10px',
+ },
+ }),
+ ).toBe('28.5% 41.5% 10px');
+});
+
+test('Crop leaves custom, keyframed and computed transform origins alone', () => {
+ const initialCrop = {
+ cropLeft: 0.11,
+ cropRight: 0.64,
+ cropTop: 0,
+ cropBottom: 0.17,
+ };
+ const base = {
+ dimensions: {width: 1920, height: 1080},
+ initialCrop,
+ nextCrop: {...initialCrop, cropLeft: 0.21},
+ };
+
+ expect(
+ getSelectedOutlineCropFollowingTransformOrigin({
+ ...base,
+ transformOrigin: {
+ defaultValue: '50% 50%',
+ propStatus: {status: 'static', codeValue: '50% 50%'},
+ value: '50% 50%',
+ },
+ }),
+ ).toBeNull();
+ expect(
+ getSelectedOutlineCropFollowingTransformOrigin({
+ ...base,
+ transformOrigin: {
+ defaultValue: '50% 50%',
+ propStatus: {
+ status: 'keyframed',
+ interpolationFunction: 'interpolate',
+ keyframes: [{frame: 0, value: '23.5% 41.5%'}],
+ easing: [],
+ clamping: {left: 'extend', right: 'extend'},
+ posterize: undefined,
+ output: undefined,
+ },
+ value: '23.5% 41.5%',
+ },
+ }),
+ ).toBeNull();
+ expect(
+ getSelectedOutlineCropFollowingTransformOrigin({
+ ...base,
+ transformOrigin: {
+ defaultValue: '50% 50%',
+ propStatus: {status: 'computed'},
+ value: '23.5% 41.5%',
+ },
+ }),
+ ).toBeNull();
+});
+
test('UV handle pointer position maps back to UV coordinates', () => {
const points = [
{x: 20, y: 10},
@@ -3780,29 +4096,37 @@ test('Transform origin drag snaps to center, edge midpoints and corners', () =>
expect(
snapSelectedOutlineTransformOriginUv({
+ crop: null,
point: {x: 47, y: 53},
points,
+ thresholdPx: null,
uv: getUvCoordinateForPoint(points, {x: 47, y: 53}),
}),
).toEqual([0.5, 0.5]);
expect(
snapSelectedOutlineTransformOriginUv({
+ crop: null,
point: {x: 52, y: 4},
points,
+ thresholdPx: null,
uv: getUvCoordinateForPoint(points, {x: 52, y: 4}),
}),
).toEqual([0.5, 0]);
expect(
snapSelectedOutlineTransformOriginUv({
+ crop: null,
point: {x: 96, y: 49},
points,
+ thresholdPx: null,
uv: getUvCoordinateForPoint(points, {x: 96, y: 49}),
}),
).toEqual([1, 0.5]);
expect(
snapSelectedOutlineTransformOriginUv({
+ crop: null,
point: {x: 3, y: 96},
points,
+ thresholdPx: null,
uv: getUvCoordinateForPoint(points, {x: 3, y: 96}),
}),
).toEqual([0, 1]);
@@ -3820,13 +4144,50 @@ test('Transform origin drag snaps to rotated outline anchors', () => {
expect(
snapSelectedOutlineTransformOriginUv({
+ crop: null,
point: pointer,
points,
+ thresholdPx: null,
uv: getUvCoordinateForPoint(points, pointer),
}),
).toEqual([0.5, 0]);
});
+test('Transform origin drag also snaps to cropped outline anchors', () => {
+ const points = [
+ {x: 0, y: 0},
+ {x: 100, y: 0},
+ {x: 100, y: 100},
+ {x: 0, y: 100},
+ ] as const;
+ const crop = {left: 0.11, right: 0.64, top: 0, bottom: 0.17};
+ const croppedSnapTargets = [
+ [0.11, 0],
+ [0.235, 0],
+ [0.36, 0],
+ [0.36, 0.415],
+ [0.36, 0.83],
+ [0.235, 0.83],
+ [0.11, 0.83],
+ [0.11, 0.415],
+ [0.235, 0.415],
+ ] as const;
+
+ for (const snapTarget of croppedSnapTargets) {
+ const snapPoint = getUvHandlePosition(points, snapTarget);
+ const pointer = {x: snapPoint.x + 2, y: snapPoint.y + 2};
+ expect(
+ snapSelectedOutlineTransformOriginUv({
+ crop,
+ point: pointer,
+ points,
+ thresholdPx: null,
+ uv: getUvCoordinateForPoint(points, pointer),
+ }),
+ ).toEqual(snapTarget);
+ }
+});
+
test('Transform origin drag does not snap outside the magnetic threshold', () => {
const points = [
{x: 0, y: 0},
@@ -3840,8 +4201,10 @@ test('Transform origin drag does not snap outside the magnetic threshold', () =>
};
const uv = getUvCoordinateForPoint(points, pointer);
const snapped = snapSelectedOutlineTransformOriginUv({
+ crop: null,
point: pointer,
points,
+ thresholdPx: null,
uv,
});
@@ -4735,6 +5098,42 @@ test('Transform origin easing selection targets the transform origin handle', ()
});
});
+test('Crop prop and keyframe selections target crop handles', () => {
+ const cropNodePathInfo = makeNodePathInfo(
+ ['body', 0],
+ ['controls', 'cropLeft'],
+ );
+ const sequenceKey = getTimelineSequenceSelectionKey(cropNodePathInfo);
+
+ expect(
+ getSelectedCropInfo([
+ {
+ type: 'sequence-prop',
+ nodePathInfo: cropNodePathInfo,
+ key: 'cropLeft',
+ },
+ ]),
+ ).toEqual({sequenceKey, displayFrame: null});
+ expect(
+ getSelectedCropInfo([
+ {
+ type: 'keyframe',
+ nodePathInfo: cropNodePathInfo,
+ frame: 18,
+ },
+ ]),
+ ).toEqual({sequenceKey, displayFrame: 18});
+ expect(
+ getSelectedCropInfo([
+ {
+ type: 'sequence-prop',
+ nodePathInfo: cropNodePathInfo,
+ key: 'style.opacity',
+ },
+ ]),
+ ).toBe(null);
+});
+
test('selected sequence keys only include exact sequence selections', () => {
const sequenceNodePathInfo = makeNodePathInfo(['body', 0], []);
const effectPropNodePathInfo = makeNodePathInfo(