Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/studio`: Add 3D transform controls (#10278)

Jonny Burger523f7fb3f9b2
diff --git a/packages/core/src/interpolate.ts b/packages/core/src/interpolate.ts
index d5583f4d3e..5f98128c87 100644
--- a/packages/core/src/interpolate.ts
+++ b/packages/core/src/interpolate.ts
@@ -33,9 +33,10 @@ type StringInterpolationKind = 'scale' | 'translate' | 'rotate';
type ParsedStringInterpolationValue = {
kind: StringInterpolationKind;
- values: [number, number, number];
- units: [string | null, string | null, string | null];
+ values: [number, number, number, number];
+ units: [string | null, string | null, string | null, string | null];
dimensions: number;
+ axisRotation: boolean;
};
type TransformOriginAxis = 'x' | 'y';
@@ -355,9 +356,58 @@ const parseTransformOriginValue = (
return {
kind: 'translate',
- values: [x.value, y.value, z.value],
- units: [x.unit, y.unit, z.unit],
+ values: [x.value, y.value, z.value, 0],
+ units: [x.unit, y.unit, z.unit, null],
dimensions: parts[2] === undefined ? 2 : 3,
+ axisRotation: false,
+ };
+};
+
+const parseAxisRotationValue = (
+ output: string,
+): ParsedStringInterpolationValue | null => {
+ const parts = output.trim().split(/\s+/);
+ const keywordAxis = parts.length === 2 ? parts[0].toLowerCase() : null;
+ if (keywordAxis === 'x' || keywordAxis === 'y' || keywordAxis === 'z') {
+ const keywordAngle = parseStringInterpolationComponent(parts[1], output);
+ if (keywordAngle.kind !== 'rotate') {
+ return null;
+ }
+
+ return {
+ kind: 'rotate',
+ values:
+ keywordAxis === 'x'
+ ? [1, 0, 0, keywordAngle.value]
+ : keywordAxis === 'y'
+ ? [0, 1, 0, keywordAngle.value]
+ : [0, 0, 1, keywordAngle.value],
+ units: [null, null, null, keywordAngle.unit],
+ dimensions: 4,
+ axisRotation: true,
+ };
+ }
+
+ if (parts.length !== 4) {
+ return null;
+ }
+
+ const axis = parts.slice(0, 3).map(Number);
+ if (!axis.every(Number.isFinite)) {
+ return null;
+ }
+
+ const vectorAngle = parseStringInterpolationComponent(parts[3], output);
+ if (vectorAngle.kind !== 'rotate') {
+ return null;
+ }
+
+ return {
+ kind: 'rotate',
+ values: [axis[0], axis[1], axis[2], vectorAngle.value],
+ units: [null, null, null, vectorAngle.unit],
+ dimensions: 4,
+ axisRotation: true,
};
};
@@ -373,12 +423,18 @@ const parseStringInterpolationValue = (
return {
kind: 'scale',
- values: [output, output, 1],
- units: [null, null, null],
+ values: [output, output, 1, 0],
+ units: [null, null, null, null],
dimensions: 1,
+ axisRotation: false,
};
}
+ const axisRotation = parseAxisRotationValue(output);
+ if (axisRotation !== null) {
+ return axisRotation;
+ }
+
const parts = output.trim().split(/\s+/);
if (parts.length < 1 || parts.length > 3 || parts[0] === '') {
throw new TypeError(
@@ -408,17 +464,24 @@ const parseStringInterpolationValue = (
const z = parsed[2]?.value ?? 1;
return {
kind,
- values: [x, y, z],
- units: [null, null, null],
+ values: [x, y, z, 0],
+ units: [null, null, null, null],
dimensions: parsed.length,
+ axisRotation: false,
};
}
return {
kind,
- values: [parsed[0].value, parsed[1]?.value ?? 0, parsed[2]?.value ?? 0],
- units: [parsed[0].unit, parsed[1]?.unit ?? null, parsed[2]?.unit ?? null],
+ values: [parsed[0].value, parsed[1]?.value ?? 0, parsed[2]?.value ?? 0, 0],
+ units: [
+ parsed[0].unit,
+ parsed[1]?.unit ?? null,
+ parsed[2]?.unit ?? null,
+ null,
+ ],
dimensions: parsed.length,
+ axisRotation: false,
};
};
@@ -427,7 +490,12 @@ const serializeStringInterpolationValue = ({
values,
units,
dimensions,
+ axisRotation,
}: ParsedStringInterpolationValue): string => {
+ if (axisRotation) {
+ return `${stringifyNumber(values[0])} ${stringifyNumber(values[1])} ${stringifyNumber(values[2])} ${stringifyNumber(values[3])}${units[3]}`;
+ }
+
if (kind === 'scale') {
return values
.slice(0, dimensions)
@@ -683,7 +751,47 @@ const interpolateString = ({
outputRange: readonly (string | number)[];
options: InterpolateOptions | undefined;
}): string => {
- const parsedOutputRange = outputRange.map(parseStringInterpolationValue);
+ const initiallyParsedOutputRange = outputRange.map(
+ parseStringInterpolationValue,
+ );
+ const hasAxisRotation = initiallyParsedOutputRange.some(
+ (parsed) => parsed.axisRotation,
+ );
+ const parsedOutputRange = hasAxisRotation
+ ? initiallyParsedOutputRange.map((parsed) => {
+ if (parsed.kind !== 'rotate') {
+ return parsed;
+ }
+
+ if (parsed.axisRotation) {
+ return parsed;
+ }
+
+ if (parsed.dimensions !== 1) {
+ throw new TypeError(
+ 'Cannot interpolate a multi-angle rotate value with an axis rotation',
+ );
+ }
+
+ return {
+ kind: 'rotate' as const,
+ values: [0, 0, 1, parsed.values[0]] as [
+ number,
+ number,
+ number,
+ number,
+ ],
+ units: [null, null, null, parsed.units[0]] as [
+ null,
+ null,
+ null,
+ string | null,
+ ],
+ dimensions: 4,
+ axisRotation: true,
+ };
+ })
+ : initiallyParsedOutputRange;
const kind = parsedOutputRange[0]?.kind;
if (kind === undefined) {
throw new Error('outputRange must have at least 1 element');
@@ -700,7 +808,8 @@ const interpolateString = ({
const dimensions = Math.max(
...parsedOutputRange.map((parsed) => parsed.dimensions),
);
- const units: [string | null, string | null, string | null] = [
+ const units: [string | null, string | null, string | null, string | null] = [
+ null,
null,
null,
null,
@@ -708,6 +817,10 @@ const interpolateString = ({
if (kind !== 'scale') {
for (let axis = 0; axis < dimensions; axis++) {
+ if (hasAxisRotation && axis < 3) {
+ continue;
+ }
+
for (const parsed of parsedOutputRange) {
const unit = parsed.units[axis];
if (unit === null) {
@@ -734,7 +847,7 @@ const interpolateString = ({
}
}
- const values: [number, number, number] = [0, 0, 0];
+ const values: [number, number, number, number] = [0, 0, 0, 0];
for (let axis = 0; axis < dimensions; axis++) {
values[axis] = interpolateNumber({
input,
@@ -749,6 +862,7 @@ const interpolateString = ({
values,
units,
dimensions,
+ axisRotation: hasAxisRotation,
});
};
diff --git a/packages/core/src/test/interpolate-keyframed-status.test.ts b/packages/core/src/test/interpolate-keyframed-status.test.ts
index 42be616418..f731ff4a6e 100644
--- a/packages/core/src/test/interpolate-keyframed-status.test.ts
+++ b/packages/core/src/test/interpolate-keyframed-status.test.ts
@@ -374,3 +374,23 @@ test('interpolates scale strings component-wise', () => {
});
expect(result).toBe('3 5 2');
});
+
+test('interpolates 3D rotation keyframes as one property', () => {
+ const result = interpolateKeyframedStatus({
+ forceSpringAllowTail: null,
+ frame: 30,
+ status: {
+ status: 'keyframed',
+ interpolationFunction: 'interpolate',
+ keyframes: [
+ {frame: 0, value: '0deg'},
+ {frame: 60, value: '1 0 0 90deg'},
+ ],
+ easing: [{type: 'linear'}],
+ clamping: {left: 'extend', right: 'extend'},
+ posterize: undefined,
+ output: undefined,
+ },
+ });
+ expect(result).toBe('0.5 0 0.5 45deg');
+});
diff --git a/packages/core/src/test/interpolate.test.ts b/packages/core/src/test/interpolate.test.ts
index 7dc1684879..f75fcdb1e4 100644
--- a/packages/core/src/test/interpolate.test.ts
+++ b/packages/core/src/test/interpolate.test.ts
@@ -477,6 +477,12 @@ test('Interpolates rotate strings', () => {
'50deg 25deg',
);
expect(interpolate(15, [0, 30], ['0turn', '0.5turn'])).toBe('0.25turn');
+ expect(interpolate(15, [0, 30], ['x 0deg', 'y 100deg'])).toBe(
+ '0.5 0.5 0 50deg',
+ );
+ expect(interpolate(15, [0, 30], ['0deg', '1 0 0 100deg'])).toBe(
+ '0.5 0 0.5 50deg',
+ );
});
test('String interpolation supports easing, extrapolation and posterization', () => {
@@ -514,6 +520,10 @@ test('String interpolation throws on type and unit mismatches', () => {
() => interpolate(15, [0, 30], ['0deg', '0.5turn']),
/different units on axis 1/,
);
+ expectToThrow(
+ () => interpolate(15, [0, 30], ['x 0deg', '0 1 0 0.5turn']),
+ /different units on axis 4/,
+ );
expectToThrow(
() => interpolate(15, [0, 30], ['0px', '1px 2px 3px 4px']),
/1 to 3 components/,
diff --git a/packages/example/e2e/constants.mts b/packages/example/e2e/constants.mts
index e11073f9d6..8d6bb5d4a6 100644
--- a/packages/example/e2e/constants.mts
+++ b/packages/example/e2e/constants.mts
@@ -18,6 +18,11 @@ export const visualControlsFile = path.join(
'VisualControls',
'index.tsx',
);
+export const visualMode3DFile = path.join(
+ exampleDir,
+ 'src',
+ 'VisualMode3D.tsx',
+);
export const effectKeyframeE2eFile = path.join(
exampleDir,
'src',
@@ -61,6 +66,10 @@ export const ORIGINAL_VISUAL_CONTROLS_FILE = path.join(
os.tmpdir(),
'remotion-e2e-original-visual-controls.tsx',
);
+export const ORIGINAL_VISUAL_MODE_3D_FILE = path.join(
+ os.tmpdir(),
+ 'remotion-e2e-original-visual-mode-3d.tsx',
+);
export const ORIGINAL_EFFECT_KEYFRAME_E2E_FILE = path.join(
os.tmpdir(),
'remotion-e2e-original-effect-keyframe-e2e.tsx',
diff --git a/packages/example/e2e/global-setup.mts b/packages/example/e2e/global-setup.mts
index 51bbfb4ede..2e8b03af80 100644
--- a/packages/example/e2e/global-setup.mts
+++ b/packages/example/e2e/global-setup.mts
@@ -6,12 +6,14 @@ import {
ORIGINAL_HOOK_ORDER_CHANGE_E2E_FILE,
ORIGINAL_LOST_NODE_PATH_E2E_FILE,
ORIGINAL_VISUAL_CONTROLS_FILE,
- errorOverlayE2eFile,
+ ORIGINAL_VISUAL_MODE_3D_FILE,
effectKeyframeE2eFile,
+ errorOverlayE2eFile,
hookOrderChangeE2eFile,
lostNodePathE2eFile,
rootFile,
visualControlsFile,
+ visualMode3DFile,
} from './constants.mts';
export default async function globalSetup(): Promise<void> {
@@ -20,6 +22,10 @@ export default async function globalSetup(): Promise<void> {
ORIGINAL_VISUAL_CONTROLS_FILE,
fs.readFileSync(visualControlsFile, 'utf-8'),
);
+ fs.writeFileSync(
+ ORIGINAL_VISUAL_MODE_3D_FILE,
+ fs.readFileSync(visualMode3DFile, 'utf-8'),
+ );
fs.writeFileSync(
ORIGINAL_EFFECT_KEYFRAME_E2E_FILE,
fs.readFileSync(effectKeyframeE2eFile, 'utf-8'),
diff --git a/packages/example/e2e/global-teardown.mts b/packages/example/e2e/global-teardown.mts
index 263509df5e..f37902fc1e 100644
--- a/packages/example/e2e/global-teardown.mts
+++ b/packages/example/e2e/global-teardown.mts
@@ -6,12 +6,14 @@ import {
ORIGINAL_HOOK_ORDER_CHANGE_E2E_FILE,
ORIGINAL_LOST_NODE_PATH_E2E_FILE,
ORIGINAL_VISUAL_CONTROLS_FILE,
- errorOverlayE2eFile,
+ ORIGINAL_VISUAL_MODE_3D_FILE,
effectKeyframeE2eFile,
+ errorOverlayE2eFile,
hookOrderChangeE2eFile,
lostNodePathE2eFile,
rootFile,
visualControlsFile,
+ visualMode3DFile,
} from './constants.mts';
export default async function globalTeardown(): Promise<void> {
@@ -28,6 +30,14 @@ export default async function globalTeardown(): Promise<void> {
fs.unlinkSync(ORIGINAL_VISUAL_CONTROLS_FILE);
}
+ if (fs.existsSync(ORIGINAL_VISUAL_MODE_3D_FILE)) {
+ fs.writeFileSync(
+ visualMode3DFile,
+ fs.readFileSync(ORIGINAL_VISUAL_MODE_3D_FILE, 'utf-8'),
+ );
+ fs.unlinkSync(ORIGINAL_VISUAL_MODE_3D_FILE);
+ }
+
if (fs.existsSync(ORIGINAL_EFFECT_KEYFRAME_E2E_FILE)) {
fs.writeFileSync(
effectKeyframeE2eFile,
diff --git a/packages/example/e2e/inspector-section-collapse.test.mts b/packages/example/e2e/inspector-section-collapse.test.mts
index 4b47e648e8..88d204bb1b 100644
--- a/packages/example/e2e/inspector-section-collapse.test.mts
+++ b/packages/example/e2e/inspector-section-collapse.test.mts
@@ -1,16 +1,397 @@
-import {expect, test} from '@playwright/test';
-import {EXPANDED_SIDEBAR_STATE, STUDIO_URL} from './constants.mts';
+import fs from 'fs';
+import {expect, type Page, test} from '@playwright/test';
+import {
+ EXPANDED_SIDEBAR_STATE,
+ STUDIO_URL,
+ visualMode3DFile,
+} from './constants.mts';
import {startStudio, stopStudio} from './studio-server.mts';
test.use({storageState: EXPANDED_SIDEBAR_STATE});
+let visualMode3DSourceBefore: string;
+
+const read2DTransformRotation = () => {
+ const source = fs.readFileSync(visualMode3DFile, 'utf-8');
+ const sequenceStart = source.indexOf('name="2D transform"');
+ const sequenceEnd = source.indexOf('name="3D transform"');
+ const sequenceSource = source.slice(sequenceStart, sequenceEnd);
+ return /rotate: '([^']+)'/.exec(sequenceSource)?.[1] ?? null;
+};
+
+const read2DTransformScale = () => {
+ const source = fs.readFileSync(visualMode3DFile, 'utf-8');
+ const sequenceStart = source.indexOf('name="2D transform"');
+ const sequenceEnd = source.indexOf('name="3D transform"');
+ const sequenceSource = source.slice(sequenceStart, sequenceEnd);
+ return /scale: ([^,}\n]+)/.exec(sequenceSource)?.[1] ?? null;
+};
+
+const read2DTransformTranslate = () => {
+ const source = fs.readFileSync(visualMode3DFile, 'utf-8');
+ const sequenceStart = source.indexOf('name="2D transform"');
+ const sequenceEnd = source.indexOf('name="3D transform"');
+ const sequenceSource = source.slice(sequenceStart, sequenceEnd);
+ return /translate: '([^']+)'/.exec(sequenceSource)?.[1] ?? null;
+};
+
+const read2DTransformOrigin = () => {
+ const source = fs.readFileSync(visualMode3DFile, 'utf-8');
+ const sequenceStart = source.indexOf('name="2D transform"');
+ const sequenceEnd = source.indexOf('name="3D transform"');
+ const sequenceSource = source.slice(sequenceStart, sequenceEnd);
+ return /transformOrigin: '([^']+)'/.exec(sequenceSource)?.[1] ?? null;
+};
+
+const read3DTransformRotation = () => {
+ const source = fs.readFileSync(visualMode3DFile, 'utf-8');
+ const sequenceStart = source.indexOf('name="3D transform"');
+ const sequenceSource = source.slice(sequenceStart);
+ return /rotate: '([^']+)'/.exec(sequenceSource)?.[1] ?? null;
+};
+
+const select2DTransformAndWaitForInspector = async (page: Page) => {
+ const transform = page.getByText('2D transform', {exact: true}).first();
+ const show3DTransformControls = page.getByRole('button', {
+ name: 'Show 3D transform controls',
+ });
+
+ await expect(async () => {
+ await transform.click();
+ await expect(show3DTransformControls).toBeVisible({timeout: 1_000});
+ }).toPass({timeout: 30_000});
+};
+
test.describe('inspector section collapse', () => {
test.beforeEach(async () => {
+ visualMode3DSourceBefore = fs.readFileSync(visualMode3DFile, 'utf-8');
await startStudio();
});
test.afterEach(async () => {
await stopStudio();
+ fs.writeFileSync(visualMode3DFile, visualMode3DSourceBefore);
+ });
+
+ test('Escape moves crop and rotation selections to the sequence', async ({
+ page,
+ }) => {
+ await page.goto(`${STUDIO_URL}/visual-mode-3d`);
+ await expect(page).toHaveURL(/visual-mode-3d/, {timeout: 15_000});
+ await page.waitForFunction(
+ () => !document.body.innerText.includes('Loading...'),
+ {timeout: 30_000},
+ );
+
+ const selectedOutline = page
+ .locator('polygon[stroke-opacity="1"][pointer-events="all"]')
+ .first();
+ const canvasRotationSurface = page.locator(
+ '[data-remotion-studio-canvas-rotation]',
+ );
+
+ await select2DTransformAndWaitForInspector(page);
+ await expect(
+ page.getByRole('button', {name: 'Show 3D transform controls'}),
+ ).toBeVisible();
+ await expect(selectedOutline).toBeVisible();
+ await selectedOutline.click({button: 'right'});
+ await page.getByRole('button', {name: 'Rotate', exact: true}).click();
+ await expect(canvasRotationSurface).toBeVisible();
+
+ await page.keyboard.press('Escape');
+ await expect(canvasRotationSurface).not.toBeVisible();
+ await expect(selectedOutline).toBeVisible();
+
+ await page.keyboard.press('Escape');
+ await expect(
+ page.getByRole('button', {name: 'Show 3D transform controls'}),
+ ).not.toBeVisible();
+
+ await page.reload();
+ await page.waitForFunction(
+ () => !document.body.innerText.includes('Loading...'),
+ {timeout: 30_000},
+ );
+ await select2DTransformAndWaitForInspector(page);
+ await expect(
+ page.getByRole('button', {name: 'Show 3D transform controls'}),
+ ).toBeVisible();
+ await expect(selectedOutline).toBeVisible();
+ await selectedOutline.click({button: 'right'});
+ await page.getByRole('button', {name: 'Crop', exact: true}).click();
+ await expect(
+ page.locator('[data-remotion-studio-crop-preview]'),
+ ).toBeVisible();
+
+ await page.keyboard.press('Escape');
+ await expect(
+ page.locator('[data-remotion-studio-crop-preview]'),
+ ).not.toBeVisible();
+ await expect(selectedOutline).toBeVisible();
+ });
+
+ test('selects 3D rotation from the sequence context menu', async ({page}) => {
+ await page.goto(`${STUDIO_URL}/visual-mode-3d`);
+ await expect(page).toHaveURL(/visual-mode-3d/, {timeout: 15_000});
+ await page.waitForFunction(
+ () => !document.body.innerText.includes('Loading...'),
+ {timeout: 30_000},
+ );
+
+ await select2DTransformAndWaitForInspector(page);
+ await expect(
+ page.getByRole('button', {name: 'Show 3D transform controls'}),
+ ).toBeVisible();
+ const outline = page
+ .locator('polygon[stroke-opacity="1"][pointer-events="all"]')
+ .first();
+ await expect(outline).toBeVisible();
+ await outline.click({button: 'right'});
+ await page.getByRole('button', {name: /^Rotate(?: all)?$/}).click();
+ await expect(
+ page.getByRole('button', {name: 'Rotation X', exact: true}),
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', {
+ name: 'Hide 3D transform controls',
+ exact: true,
+ }),
+ ).toBeVisible();
+
+ const rightScaleEdge = page
+ .locator(
+ '[data-remotion-studio-scale-edge="right"][data-remotion-studio-scale-edge-contains-selection="true"]',
+ )
+ .first();
+ await expect(rightScaleEdge).toHaveCount(1);
+ const edgeCenter = await rightScaleEdge.evaluate((element) => {
+ if (!(element instanceof SVGLineElement)) {
+ throw new Error('Scale edge should be an SVG line');
+ }
+
+ const matrix = element.getScreenCTM();
+ if (matrix === null) {
+ throw new Error('Scale edge should have a screen transform');
+ }
+
+ return new DOMPoint(
+ (element.x1.baseVal.value + element.x2.baseVal.value) / 2,
+ (element.y1.baseVal.value + element.y2.baseVal.value) / 2,
+ ).matrixTransform(matrix);
+ });
+ expect(
+ await page.evaluate(
+ ({x, y}) =>
+ document
+ .elementFromPoint(x, y)
+ ?.getAttribute('data-remotion-studio-scale-edge') ?? null,
+ {x: edgeCenter.x, y: edgeCenter.y},
+ ),
+ ).toBe('right');
+
+ const scaleBefore = read2DTransformScale();
+ await rightScaleEdge.dispatchEvent('pointerdown', {
+ button: 0,
+ buttons: 1,
+ clientX: edgeCenter.x,
+ clientY: edgeCenter.y,
+ pointerId: 1,
+ });
+ await page.evaluate(
+ ({x, y}) => {
+ window.dispatchEvent(
+ new PointerEvent('pointermove', {
+ buttons: 1,
+ clientX: x + 60,
+ clientY: y,
+ pointerId: 1,
+ }),
+ );
+ window.dispatchEvent(
+ new PointerEvent('pointerup', {
+ button: 0,
+ buttons: 0,
+ clientX: x + 60,
+ clientY: y,
+ pointerId: 1,
+ }),
+ );
+ },
+ {x: edgeCenter.x, y: edgeCenter.y},
+ );
+ await expect.poll(read2DTransformScale).not.toBe(scaleBefore);
+ const canvasRotationSurface = page.locator(
+ '[data-remotion-studio-canvas-rotation]',
+ );
+ await expect(canvasRotationSurface).toBeVisible();
+
+ const transformOriginHandle = page
+ .locator('[data-remotion-studio-transform-origin-handle]')
+ .first();
+ await expect(transformOriginHandle).toBeVisible();
+ const dragTransformOrigin = async ({
+ deltaX,
+ deltaY,
+ pointerId,
+ }: {
+ readonly deltaX: number;
+ readonly deltaY: number;
+ readonly pointerId: number;
+ }) => {
+ const transformOriginCenter = await transformOriginHandle.evaluate(
+ (element) => {
+ const circle = element.querySelector('circle');
+ if (!(circle instanceof SVGCircleElement)) {
+ throw new Error('Transform origin handle should contain a circle');
+ }
+
+ const matrix = circle.getScreenCTM();
+ if (matrix === null) {
+ throw new Error(
+ 'Transform origin handle should have a screen transform',
+ );
+ }
+
+ return new DOMPoint(
+ circle.cx.baseVal.value,
+ circle.cy.baseVal.value,
+ ).matrixTransform(matrix);
+ },
+ );
+ await transformOriginHandle.dispatchEvent('pointerdown', {
+ button: 0,
+ buttons: 1,
+ clientX: transformOriginCenter.x,
+ clientY: transformOriginCenter.y,
+ pointerId,
+ });
+ await page.evaluate(
+ ({x, y, moveX, moveY, id}) => {
+ window.dispatchEvent(
+ new PointerEvent('pointermove', {
+ buttons: 1,
+ clientX: x + moveX,
+ clientY: y + moveY,
+ pointerId: id,
+ }),
+ );
+ window.dispatchEvent(
+ new PointerEvent('pointerup', {
+ button: 0,
+ buttons: 0,
+ clientX: x + moveX,
+ clientY: y + moveY,
+ pointerId: id,
+ }),
+ );
+ },
+ {
+ x: transformOriginCenter.x,
+ y: transformOriginCenter.y,
+ moveX: deltaX,
+ moveY: deltaY,
+ id: pointerId,
+ },
+ );
+ };
+ const transformOriginBefore = read2DTransformOrigin();
+ await dragTransformOrigin({deltaX: 30, deltaY: 20, pointerId: 2});
+ await expect.poll(read2DTransformOrigin).not.toBe(transformOriginBefore);
+ await expect(canvasRotationSurface).toBeVisible();
+
+ const compositionContainer = page.locator(
+ '.remotion-studio-composition-container',
+ );
+ const compositionBox = await compositionContainer.boundingBox();
+ const rotationSurfaceBox = await canvasRotationSurface.boundingBox();
+ if (compositionBox === null || rotationSurfaceBox === null) {
+ throw new Error('Rotation surface should have a visible layout');
+ }
+
+ expect(rotationSurfaceBox.width).toBeLessThan(compositionBox.width);
+ expect(rotationSurfaceBox.height).toBeLessThan(compositionBox.height);
+ const outsidePoint = {
+ x: compositionBox.x + compositionBox.width - 4,
+ y: compositionBox.y + compositionBox.height - 4,
+ };
+ expect(
+ await page.evaluate(
+ ({x, y}) =>
+ document
+ .elementFromPoint(x, y)
+ ?.closest('[data-remotion-studio-canvas-rotation]') ?? null,
+ outsidePoint,
+ ),
+ ).toBeNull();
+ const rotationBefore = read2DTransformRotation();
+ const getInteractiveRotationPoint = () =>
+ canvasRotationSurface.evaluate((surface) => {
+ const box = surface.getBoundingClientRect();
+ for (let yIndex = 1; yIndex < 10; yIndex++) {
+ for (let xIndex = 1; xIndex < 10; xIndex++) {
+ const point = {
+ x: box.x + (box.width * xIndex) / 10,
+ y: box.y + (box.height * yIndex) / 10,
+ };
+ if (
+ document
+ .elementFromPoint(point.x, point.y)
+ ?.closest('[data-remotion-studio-canvas-rotation]') === surface
+ ) {
+ return point;
+ }
+ }
+ }
+
+ throw new Error('Rotation surface should have an interactive point');
+ });
+ const insidePoint = await getInteractiveRotationPoint();
+ await page.mouse.move(insidePoint.x, insidePoint.y);
+ await page.mouse.down();
+ await page.mouse.move(insidePoint.x + 40, insidePoint.y + 30, {steps: 5});
+ await page.mouse.up();
+ await expect.poll(read2DTransformRotation).not.toBe(rotationBefore);
+ const transformOriginAfter3DRotation = read2DTransformOrigin();
+ await dragTransformOrigin({deltaX: -20, deltaY: 25, pointerId: 3});
+ await expect
+ .poll(read2DTransformOrigin)
+ .not.toBe(transformOriginAfter3DRotation);
+
+ const continuedInsidePoint = await getInteractiveRotationPoint();
+ const rotationXControl = page
+ .getByRole('button', {name: 'Rotation X', exact: true})
+ .first();
+ const rotationYControl = page
+ .getByRole('button', {name: 'Rotation Y', exact: true})
+ .first();
+ const readRotationControls = async () =>
+ `${await rotationXControl.textContent()}|${await rotationYControl.textContent()}`;
+ const rotationBeforeLeavingSurface = await readRotationControls();
+ const sourceRotationBeforeLeavingSurface = read2DTransformRotation();
+ await page.mouse.move(continuedInsidePoint.x, continuedInsidePoint.y);
+ await page.mouse.down();
+ await page.mouse.move(outsidePoint.x, outsidePoint.y, {steps: 5});
+ await expect
+ .poll(readRotationControls)
+ .not.toBe(rotationBeforeLeavingSurface);
+ const rotationAfterLeavingSurface = await readRotationControls();
+ await page.mouse.move(outsidePoint.x - 60, outsidePoint.y, {steps: 3});
+ await expect
+ .poll(readRotationControls)
+ .not.toBe(rotationAfterLeavingSurface);
+ await page.mouse.up();
+ await expect
+ .poll(read2DTransformRotation)
+ .not.toBe(sourceRotationBeforeLeavingSurface);
+
+ const rotationAfterInsideDrag = read2DTransformRotation();
+ await page.mouse.move(outsidePoint.x, outsidePoint.y);
+ await page.mouse.down();
+ await page.mouse.move(outsidePoint.x + 20, outsidePoint.y + 20);
+ await page.mouse.up();
+ await page.waitForTimeout(200);
+ expect(read2DTransformRotation()).toBe(rotationAfterInsideDrag);
});
test('collapses inactive static sections and lets the user expand them', async ({
@@ -99,5 +480,320 @@ test.describe('inspector section collapse', () => {
await expect(
page.getByRole('button', {name: 'Expand Layout', exact: true}),
).toBeVisible();
+
+ await page.goto(`${STUDIO_URL}/visual-mode-3d`);
+ await expect(page).toHaveURL(/visual-mode-3d/, {timeout: 15_000});
+ await page.waitForFunction(
+ () => !document.body.innerText.includes('Loading...'),
+ {timeout: 30_000},
+ );
+
+ await page.locator('[title="2D transform"]').first().click();
+ const show3DControls = page.getByRole('button', {
+ name: 'Show 3D transform controls',
+ exact: true,
+ });
+ await expect(show3DControls).toBeVisible();
+ await expect(
+ page.getByRole('button', {name: 'Scale Z', exact: true}),
+ ).toHaveCount(0);
+ await expect(
+ page.getByRole('button', {name: 'Offset Z', exact: true}),
+ ).toHaveCount(0);
+ await expect(
+ page.getByRole('button', {name: 'Rotation Z', exact: true}),
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', {name: 'Rotation X', exact: true}),
+ ).toHaveCount(0);
+ await page.getByTitle('Rotation', {exact: true}).click();
+ const compositionContainer = page.locator(
+ '.remotion-studio-composition-container',
+ );
+ const compositionBox = await compositionContainer.boundingBox();
+ if (compositionBox === null) {
+ throw new Error('Composition should have a visible layout');
+ }
+
+ await page.mouse.move(
+ compositionBox.x + compositionBox.width / 2,
+ compositionBox.y + compositionBox.height / 2,
+ );
+ const canvasRotationSurface = page.locator(
+ '[data-remotion-studio-canvas-rotation]',
+ );
+ await expect(canvasRotationSurface).toBeVisible();
+ await expect(
+ page.locator('[data-remotion-studio-transform-origin-handle]').first(),
+ ).toBeVisible();
+ const rotationSurfaceBox = await canvasRotationSurface.boundingBox();
+ if (rotationSurfaceBox === null) {
+ throw new Error('Canvas rotation surface should have a visible layout');
+ }
+
+ const startX = rotationSurfaceBox.x + rotationSurfaceBox.width * 0.25;
+ const startY = rotationSurfaceBox.y + rotationSurfaceBox.height * 0.25;
+ await page.mouse.move(startX, startY);
+ await page.mouse.down();
+ await page.mouse.move(startX + 60, startY + 80, {steps: 5});
+ await page.mouse.up();
+ await expect.poll(read2DTransformRotation).toMatch(/^-?\d+(?:\.\d+)?deg$/);
+
+ await show3DControls.click();
+ await expect(
+ page.getByRole('button', {name: 'Scale Z', exact: true}),
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', {name: 'Offset Z', exact: true}),
+ ).toBeVisible();
+ await page.getByTitle('Rotation', {exact: true}).click();
+ await page.mouse.move(
+ compositionBox.x + compositionBox.width / 2,
+ compositionBox.y + compositionBox.height / 2,
+ );
+ await expect(canvasRotationSurface).toBeVisible();
+ const threeDRotationSurfaceBox = await canvasRotationSurface.boundingBox();
+ if (threeDRotationSurfaceBox === null) {
+ throw new Error(
+ '3D canvas rotation surface should have a visible layout',
+ );
+ }
+
+ const threeDStartX =
+ threeDRotationSurfaceBox.x + threeDRotationSurfaceBox.width * 0.25;
+ const threeDStartY =
+ threeDRotationSurfaceBox.y + threeDRotationSurfaceBox.height * 0.25;
+ await page.mouse.move(threeDStartX, threeDStartY);
+ await page.mouse.down();
+ await page.mouse.move(threeDStartX + 80, threeDStartY + 60, {steps: 5});
+ await page.mouse.up();
+ await expect
+ .poll(() => read2DTransformRotation()?.split(' ').length)
+ .toBe(4);
+ const scaleLabelBox = await page
+ .getByTitle('Scale', {exact: true})
+ .first()
+ .boundingBox();
+ const scaleXBox = await page
+ .getByRole('button', {name: 'Scale X', exact: true})
+ .first()
+ .boundingBox();
+ const scaleZBox = await page
+ .getByRole('button', {name: 'Scale Z', exact: true})
+ .first()
+ .boundingBox();
+ if (scaleLabelBox === null || scaleXBox === null || scaleZBox === null) {
+ throw new Error('Scale controls should have a visible layout');
+ }
+ const offsetLabelBox = await page
+ .getByTitle('Offset', {exact: true})
+ .first()
+ .boundingBox();
+ const offsetX = page
+ .getByRole('button', {name: 'Offset X', exact: true})
+ .first();
+ const offsetXBox = await offsetX.boundingBox();
+ const offsetZ = page
+ .getByRole('button', {name: 'Offset Z', exact: true})
+ .first();
+ const offsetZBox = await offsetZ.boundingBox();
+ if (offsetLabelBox === null || offsetXBox === null || offsetZBox === null) {
+ throw new Error('Offset controls should have a visible layout');
+ }
+
+ expect(
+ scaleZBox.y - (scaleLabelBox.y + scaleLabelBox.height),
+ ).toBeGreaterThanOrEqual(-1);
+ expect(
+ scaleZBox.y - (scaleLabelBox.y + scaleLabelBox.height),
+ ).toBeLessThanOrEqual(1);
+ expect(
+ offsetZBox.y - (offsetLabelBox.y + offsetLabelBox.height),
+ ).toBeGreaterThanOrEqual(-1);
+ expect(
+ offsetZBox.y - (offsetLabelBox.y + offsetLabelBox.height),
+ ).toBeLessThanOrEqual(1);
+ await expect(
+ page.getByRole('button', {name: 'Rotation X', exact: true}).first(),
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', {name: 'Rotation Y', exact: true}).first(),
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', {name: 'Rotation Z', exact: true}).first(),
+ ).toBeVisible();
+ const rotationLabelBox = await page
+ .getByTitle('Rotation', {exact: true})
+ .first()
+ .boundingBox();
+ const rotationXBox = await page
+ .getByRole('button', {name: 'Rotation X', exact: true})
+ .first()
+ .boundingBox();
+ if (rotationLabelBox === null || rotationXBox === null) {
+ throw new Error('Rotation controls should have a visible layout');
+ }
+
+ expect(
+ rotationXBox.y - (rotationLabelBox.y + rotationLabelBox.height),
+ ).toBeGreaterThanOrEqual(-1);
+ expect(
+ rotationXBox.y - (rotationLabelBox.y + rotationLabelBox.height),
+ ).toBeLessThanOrEqual(1);
+ expect(Math.abs(scaleXBox.x - rotationXBox.x)).toBeLessThanOrEqual(1);
+ expect(Math.abs(scaleXBox.x - offsetXBox.x)).toBeLessThanOrEqual(1);
+ await expect(
+ page
+ .getByRole('button', {name: 'Transform origin Z', exact: true})
+ .first(),
+ ).toBeVisible();
+ await offsetZ.click();
+ const offsetZInput = page.getByRole('textbox', {
+ name: 'Offset Z',
+ exact: true,
+ });
+ await offsetZInput.fill('25');
+ await offsetZInput.press('Enter');
+ await expect.poll(read2DTransformTranslate).toBe('0px 0px 25px');
+ await expect(
+ page.getByRole('button', {
+ name: '3D controls are required by the current transform values',
+ exact: true,
+ }),
+ ).toBeDisabled();
+
+ const threeDTransformElement = page
+ .locator('[title="3D transform"]')
+ .first();
+ await threeDTransformElement.click();
+ await expect(
+ page
+ .getByRole('button', {
+ name: '3D controls are required by the current transform values',
+ exact: true,
+ })
+ .first(),
+ ).toBeDisabled();
+ await expect(
+ page.getByRole('button', {name: 'Scale Z', exact: true}).first(),
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', {name: 'Rotation X', exact: true}).first(),
+ ).not.toContainText('X ');
+ await page.getByTitle('Rotation', {exact: true}).click();
+ const rotationX = page
+ .getByRole('button', {name: 'Rotation X', exact: true})
+ .first();
+ const rotationY = page
+ .getByRole('button', {name: 'Rotation Y', exact: true})
+ .first();
+ const rotationZ = page
+ .getByRole('button', {name: 'Rotation Z', exact: true})
+ .first();
+ const rotationXBefore = await rotationX.textContent();
+ const rotationYBefore = await rotationY.textContent();
+ const rotationZBefore = await rotationZ.textContent();
+ const sourceRotationBefore = read3DTransformRotation();
+ await page.locator('[title="3D transform"]').last().hover();
+ const getRotationCornerCenter = async (
+ corner: 'top-left' | 'top-right' | 'bottom-right' | 'bottom-left',
+ ) => {
+ const box = await page
+ .locator(
+ `[data-remotion-studio-rotation-corner="${corner}"][data-remotion-studio-rotation-corner-contains-selection="true"]`,
+ )
+ .first()
+ .boundingBox();
+ if (box === null) {
+ throw new Error(`The ${corner} rotation corner should be visible`);
+ }
+
+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};
+ };
+ const [topLeft, topRight, bottomRight, bottomLeft] = await Promise.all([
+ getRotationCornerCenter('top-left'),
+ getRotationCornerCenter('top-right'),
+ getRotationCornerCenter('bottom-right'),
+ getRotationCornerCenter('bottom-left'),
+ ]);
+ const topEdgeLength = Math.hypot(
+ topRight.x - topLeft.x,
+ topRight.y - topLeft.y,
+ );
+ const bottomEdgeLength = Math.hypot(
+ bottomRight.x - bottomLeft.x,
+ bottomRight.y - bottomLeft.y,
+ );
+ expect(Math.abs(topEdgeLength - bottomEdgeLength)).toBeGreaterThan(1);
+ const selectedRotationCorner = page
+ .locator(
+ '[data-remotion-studio-rotation-corner="top-right"][data-remotion-studio-rotation-corner-contains-selection="true"]',
+ )
+ .first();
+ await expect(selectedRotationCorner).toBeVisible();
+ const selectedRotationCornerBox =
+ await selectedRotationCorner.boundingBox();
+ if (selectedRotationCornerBox === null) {
+ throw new Error('Selected rotation corner should have a visible layout');
+ }
+
+ const cornerX =
+ selectedRotationCornerBox.x + selectedRotationCornerBox.width / 2;
+ const cornerY =
+ selectedRotationCornerBox.y + selectedRotationCornerBox.height / 2;
+ expect(
+ await page.evaluate(
+ ({x, y}) =>
+ document
+ .elementFromPoint(x, y)
+ ?.getAttribute('data-remotion-studio-rotation-corner') ?? null,
+ {x: cornerX, y: cornerY},
+ ),
+ ).toBe('top-right');
+ await selectedRotationCorner.dispatchEvent('pointerdown', {
+ button: 0,
+ buttons: 1,
+ clientX: cornerX,
+ clientY: cornerY,
+ pointerId: 1,
+ });
+ await page.evaluate(
+ ({x, y}) => {
+ window.dispatchEvent(
+ new PointerEvent('pointermove', {
+ buttons: 1,
+ clientX: x + 60,
+ clientY: y + 40,
+ pointerId: 1,
+ }),
+ );
+ window.dispatchEvent(
+ new PointerEvent('pointerup', {
+ button: 0,
+ buttons: 0,
+ clientX: x + 60,
+ clientY: y + 40,
+ pointerId: 1,
+ }),
+ );
+ },
+ {x: cornerX, y: cornerY},
+ );
+ await expect.poll(read3DTransformRotation).not.toBe(sourceRotationBefore);
+ await expect
+ .poll(() => read3DTransformRotation()?.split(' ').length)
+ .toBe(4);
+ await expect(rotationX).toHaveText(rotationXBefore ?? '');
+ await expect(rotationY).toHaveText(rotationYBefore ?? '');
+ await expect(rotationZ).not.toHaveText(rotationZBefore ?? '');
+ await expect
+ .poll(async () => {
+ const [nextTopLeft, nextTopRight] = await Promise.all([
+ getRotationCornerCenter('top-left'),
+ getRotationCornerCenter('top-right'),
+ ]);
+ return Math.abs(nextTopLeft.y - nextTopRight.y);
+ })
+ .toBeGreaterThan(1);
});
});
diff --git a/packages/example/e2e/rotation-keyframes.test.mts b/packages/example/e2e/rotation-keyframes.test.mts
new file mode 100644
index 0000000000..da1f68a0a8
--- /dev/null
+++ b/packages/example/e2e/rotation-keyframes.test.mts
@@ -0,0 +1,116 @@
+import fs from 'fs';
+import path from 'path';
+import {expect, test} from '@playwright/test';
+import {EXPANDED_SIDEBAR_STATE, STUDIO_URL, exampleDir} from './constants.mts';
+import {startStudio, stopStudio} from './studio-server.mts';
+
+test.use({storageState: EXPANDED_SIDEBAR_STATE});
+
+const rotationKeyframeFile = path.join(
+ exampleDir,
+ 'src',
+ 'RotationKeyframeE2e.tsx',
+);
+
+const readRotationKeyframes = () => {
+ const source = fs.readFileSync(rotationKeyframeFile, 'utf-8');
+ const match =
+ /rotate:\s*interpolate\(\s*frame,\s*\[([^\]]*)\],\s*\[([^\]]*)\]/.exec(
+ source,
+ );
+ if (match === null) {
+ throw new Error('Could not read rotation keyframes');
+ }
+
+ return {
+ frames: match[1]
+ .split(',')
+ .map((frame) => Number(frame.trim()))
+ .filter((frame) => !Number.isNaN(frame)),
+ values: [...match[2].matchAll(/(['"])(.*?)\1/g)].map((value) => value[2]),
+ };
+};
+
+test.describe('canvas rotation keyframes', () => {
+ let sourceBefore: string;
+
+ test.beforeEach(async () => {
+ sourceBefore = fs.readFileSync(rotationKeyframeFile, 'utf-8');
+ await startStudio();
+ });
+
+ test.afterEach(async () => {
+ await stopStudio();
+ fs.writeFileSync(rotationKeyframeFile, sourceBefore);
+ });
+
+ test('inserts and replaces keyframes in keyframed mode', async ({page}) => {
+ await page.goto(`${STUDIO_URL}/rotation-keyframe-e2e`);
+ await expect(page).toHaveURL(/rotation-keyframe-e2e/, {timeout: 15_000});
+ await page.waitForFunction(
+ () => !document.body.innerText.includes('Loading...'),
+ {timeout: 30_000},
+ );
+
+ const keyframedRotation = page
+ .getByTitle('Keyframed rotation', {exact: true})
+ .first();
+ const rotation = page.getByTitle('Rotation', {exact: true}).first();
+ await expect(async () => {
+ await keyframedRotation.click();
+ await expect(rotation).toBeVisible({timeout: 1_000});
+ }).toPass({timeout: 30_000});
+ await rotation.click();
+ const rotationSurface = page.locator(
+ '[data-remotion-studio-canvas-rotation]',
+ );
+ await expect(rotationSurface).toBeVisible({timeout: 15_000});
+ await page.getByTitle('Keyframe at frame 0', {exact: true}).first().click();
+
+ await page.keyboard.press('g');
+ const currentFrameInput = page.locator('input:focus');
+ await expect(currentFrameInput).toBeVisible();
+ await currentFrameInput.fill('10');
+ await currentFrameInput.press('Enter');
+
+ const dragRotationSurface = async (deltaX: number, deltaY: number) => {
+ const point = await rotationSurface.evaluate((surface) => {
+ const box = surface.getBoundingClientRect();
+ for (let yIndex = 1; yIndex < 10; yIndex++) {
+ for (let xIndex = 1; xIndex < 10; xIndex++) {
+ const candidate = {
+ x: box.x + (box.width * xIndex) / 10,
+ y: box.y + (box.height * yIndex) / 10,
+ };
+ if (
+ document
+ .elementFromPoint(candidate.x, candidate.y)
+ ?.closest('[data-remotion-studio-canvas-rotation]') === surface
+ ) {
+ return candidate;
+ }
+ }
+ }
+
+ throw new Error('Rotation surface should have an interactive point');
+ });
+ await page.mouse.move(point.x, point.y);
+ await page.mouse.down();
+ await page.mouse.move(point.x + deltaX, point.y + deltaY, {steps: 5});
+ await page.mouse.up();
+ };
+
+ await dragRotationSurface(40, 30);
+ await expect
+ .poll(() => readRotationKeyframes().frames)
+ .toEqual([0, 10, 30]);
+ const firstValueAtFrame10 = readRotationKeyframes().values[1];
+ expect(firstValueAtFrame10).toBeDefined();
+
+ await dragRotationSurface(-30, 45);
+ await expect
+ .poll(() => readRotationKeyframes().values[1])
+ .not.toBe(firstValueAtFrame10);
+ expect(readRotationKeyframes().frames).toEqual([0, 10, 30]);
+ });
+});
diff --git a/packages/example/e2e/studio-server.mts b/packages/example/e2e/studio-server.mts
index 4e6c8e4c06..a3424fef67 100644
--- a/packages/example/e2e/studio-server.mts
+++ b/packages/example/e2e/studio-server.mts
@@ -10,6 +10,7 @@ import {
ORIGINAL_HOOK_ORDER_CHANGE_E2E_FILE,
ORIGINAL_LOST_NODE_PATH_E2E_FILE,
ORIGINAL_VISUAL_CONTROLS_FILE,
+ ORIGINAL_VISUAL_MODE_3D_FILE,
STUDIO_PORT,
STUDIO_URL,
e2eEntryPoint,
@@ -21,6 +22,7 @@ import {
remotionBin,
rootFile,
visualControlsFile,
+ visualMode3DFile,
} from './constants.mts';
let studioProcess: ChildProcess | null = null;
@@ -59,6 +61,13 @@ export async function startStudio(): Promise<void> {
);
}
+ if (!fs.existsSync(ORIGINAL_VISUAL_MODE_3D_FILE)) {
+ fs.writeFileSync(
+ ORIGINAL_VISUAL_MODE_3D_FILE,
+ fs.readFileSync(visualMode3DFile, 'utf-8'),
+ );
+ }
+
if (!fs.existsSync(ORIGINAL_EFFECT_KEYFRAME_E2E_FILE)) {
fs.writeFileSync(
ORIGINAL_EFFECT_KEYFRAME_E2E_FILE,
@@ -93,6 +102,10 @@ export async function startStudio(): Promise<void> {
visualControlsFile,
fs.readFileSync(ORIGINAL_VISUAL_CONTROLS_FILE, 'utf-8'),
);
+ fs.writeFileSync(
+ visualMode3DFile,
+ fs.readFileSync(ORIGINAL_VISUAL_MODE_3D_FILE, 'utf-8'),
+ );
fs.writeFileSync(
effectKeyframeE2eFile,
fs.readFileSync(ORIGINAL_EFFECT_KEYFRAME_E2E_FILE, 'utf-8'),
@@ -234,6 +247,13 @@ export async function stopStudio(): Promise<void> {
);
}
+ if (fs.existsSync(ORIGINAL_VISUAL_MODE_3D_FILE)) {
+ fs.writeFileSync(
+ visualMode3DFile,
+ fs.readFileSync(ORIGINAL_VISUAL_MODE_3D_FILE, 'utf-8'),
+ );
+ }
+
if (fs.existsSync(ORIGINAL_EFFECT_KEYFRAME_E2E_FILE)) {
fs.writeFileSync(
effectKeyframeE2eFile,
diff --git a/packages/example/e2e/studio.test.mts b/packages/example/e2e/studio.test.mts
index 66a32156eb..8d64c8412f 100644
--- a/packages/example/e2e/studio.test.mts
+++ b/packages/example/e2e/studio.test.mts
@@ -521,7 +521,6 @@ test.describe('visual mode', () => {
),
).toEqual([]);
});
-
test('should use standalone and contextual app names in portaled context menus', async ({
context,
page,
@@ -894,18 +893,19 @@ test.describe('visual mode', () => {
const openInAnotherApp = page
.getByTitle(exampleDir)
.getByRole('button', {name: 'Open in another app'});
+ const changeDefaultApps = page.getByRole('button', {
+ name: 'Change default apps...',
+ });
await openInAnotherApp.click();
- await expect(
- page.getByRole('button', {name: 'Change default apps...'}),
- ).toBeVisible();
- // The menu overlay intercepts pointerleave; Escape closes it deterministically.
- await page.mouse.move(10, 100);
- await page.keyboard.press('Escape');
-
- await expect(
- page.getByRole('button', {name: 'Change default apps...'}),
- ).toBeHidden();
+ await expect(changeDefaultApps).toBeVisible();
+ // The menu overlay intercepts pointerleave; clicking it closes the menu
+ // through the same outside-click path a user would take. Retry the click
+ // until the new layer has registered as the highest z-index context.
+ await expect(async () => {
+ await page.mouse.click(10, 100);
+ await expect(changeDefaultApps).toBeHidden({timeout: 1_000});
+ }).toPass({timeout: 10_000});
await expect(openInAnotherApp).toHaveCSS(
'background-color',
'rgba(0, 0, 0, 0)',
diff --git a/packages/example/src/E2eTestRoot.tsx b/packages/example/src/E2eTestRoot.tsx
index 9210632bb6..c71a9f71b0 100644
--- a/packages/example/src/E2eTestRoot.tsx
+++ b/packages/example/src/E2eTestRoot.tsx
@@ -11,8 +11,10 @@ import {Issue8216} from './Issue8216/Issue8216';
import {LightLeakExample} from './LightLeak';
import {LostNodePathRepro} from './LostNodePathE2e/LostNodePathRepro';
import {NewVideoComp} from './NewVideo';
+import {RotationKeyframeE2e} from './RotationKeyframeE2e';
import {SchemaTest, schemaTestSchema} from './SchemaTest';
import {VisualControls} from './VisualControls';
+import {VisualMode3D} from './VisualMode3D';
const UseCurrentScaleOnLoad: React.FC = () => {
const scale = useCurrentScale();
@@ -152,6 +154,22 @@ export const E2eTestRoot: React.FC = () => {
fps={30}
durationInFrames={90}
/>
+ <Composition
+ id="visual-mode-3d"
+ component={VisualMode3D}
+ width={1080}
+ height={1080}
+ fps={30}
+ durationInFrames={120}
+ />
+ <Composition
+ id="rotation-keyframe-e2e"
+ component={RotationKeyframeE2e}
+ width={1080}
+ height={1080}
+ fps={30}
+ durationInFrames={90}
+ />
<NewVideoComp />
</>
);
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index 9df7e4cad0..7c6a88a94e 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -157,8 +157,8 @@ import {
} from './StudioApis/SaveDefaultProps';
import {TriggerCalculateMetadata} from './StudioApis/TriggerCalculateMetadata';
import {WriteStaticFile} from './StudioApis/WriteStaticFile';
-import './style.css';
import {SubtitleArtifact} from './SubtitleArtifact/SubtitleArtifact';
+import './style.css';
import {SvgFilter} from './SvgFilter';
import {Tailwind} from './Tailwind';
import {TenFrameTester} from './TenFrameTester';
@@ -181,6 +181,7 @@ import {Greenscreen} from './VideoOnCanvas/greenscreen';
import {VideoParser} from './VideoParser';
import {VideoSpeed} from './VideoSpeed';
import {VideoTesting} from './VideoTesting';
+import {VisualMode3D} from './VisualMode3D';
import {WarpDemoOuter} from './WarpText';
import {WarpDemo2} from './WarpText/demo2';
import {WatchStaticDemo} from './watch-static';
@@ -2752,6 +2753,14 @@ export const Index: React.FC = () => {
fps={30}
durationInFrames={120}
/>
+ <Composition
+ id="visual-mode-3d"
+ component={VisualMode3D}
+ width={1080}
+ height={1080}
+ fps={30}
+ durationInFrames={120}
+ />
<Composition
id="sequence-crop-controls"
component={SequenceCropTest}
diff --git a/packages/example/src/RotationKeyframeE2e.tsx b/packages/example/src/RotationKeyframeE2e.tsx
new file mode 100644
index 0000000000..58863c3712
--- /dev/null
+++ b/packages/example/src/RotationKeyframeE2e.tsx
@@ -0,0 +1,22 @@
+import React from 'react';
+import {AbsoluteFill, interpolate, Sequence, useCurrentFrame} from 'remotion';
+
+export const RotationKeyframeE2e: React.FC = () => {
+ const frame = useCurrentFrame();
+
+ return (
+ <AbsoluteFill style={{backgroundColor: '#111'}}>
+ <Sequence
+ name="Keyframed rotation"
+ durationInFrames={90}
+ style={{
+ height: 400,
+ rotate: interpolate(frame, [0, 30], ['0deg', '30deg']),
+ width: 400,
+ }}
+ >
+ <AbsoluteFill style={{backgroundColor: '#0b84ff'}} />
+ </Sequence>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/example/src/VisualMode3D.tsx b/packages/example/src/VisualMode3D.tsx
new file mode 100644
index 0000000000..da48450d2e
--- /dev/null
+++ b/packages/example/src/VisualMode3D.tsx
@@ -0,0 +1,30 @@
+import React from 'react';
+import {AbsoluteFill, Sequence} from 'remotion';
+
+export const VisualMode3D: React.FC = () => {
+ return (
+ <AbsoluteFill style={{backgroundColor: '#111', perspective: 800}}>
+ <Sequence
+ name="2D transform"
+ durationInFrames={120}
+ style={{height: 400, scale: 1, width: 400}}
+ >
+ <AbsoluteFill style={{backgroundColor: '#0b84ff'}} />
+ </Sequence>
+ <Sequence
+ name="3D transform"
+ durationInFrames={120}
+ style={{
+ height: 400,
+ rotate: 'x 30deg',
+ scale: '1 1 2',
+ transformOrigin: '50% 50% 10px',
+ translate: '500px 500px',
+ width: 400,
+ }}
+ >
+ <AbsoluteFill style={{backgroundColor: '#ff4d8d'}} />
+ </Sequence>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
index de2420d560..53b07ee2b7 100644
--- a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
+++ b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
@@ -991,7 +991,7 @@ const PIXEL_VALUE_REGEX = /^-?\d+(\.\d+)?px$/;
const isSupportedTranslateValue = (value: string): boolean => {
const parts = value.split(/\s+/);
- if (parts.length === 1 || parts.length === 2) {
+ if (parts.length >= 1 && parts.length <= 3) {
return parts.every((part) => PIXEL_VALUE_REGEX.test(part));
}
diff --git a/packages/studio-server/src/test/unsupported-translate.test.ts b/packages/studio-server/src/test/unsupported-translate.test.ts
index 85392debd3..9374e433b8 100644
--- a/packages/studio-server/src/test/unsupported-translate.test.ts
+++ b/packages/studio-server/src/test/unsupported-translate.test.ts
@@ -69,10 +69,12 @@ test('Should be able to update translate with negative pixel values', () => {
expect(status.codeValue).toBe('-50px 100px');
});
-// Unsupported: three values (x, y, z)
-test('Should not support translate with three values', () => {
- const status = getTranslateStatus('0px 100px 200px');
- expect(status.status).toBe('computed');
+// Supported: three values (x, y, z)
+test('Should be able to update translate with three pixel values', () => {
+ const status = getTranslateStatus('3px 59.1px -170.6px');
+ expect(status.status).toBe('static');
+ assert(status.status === 'static');
+ expect(status.codeValue).toBe('3px 59.1px -170.6px');
});
// Unsupported: global CSS values
diff --git a/packages/studio/src/components/EditorContent.tsx b/packages/studio/src/components/EditorContent.tsx
index a9f9122f75..ebfbc5dd17 100644
--- a/packages/studio/src/components/EditorContent.tsx
+++ b/packages/studio/src/components/EditorContent.tsx
@@ -1,5 +1,6 @@
import React, {useCallback, useContext} from 'react';
import {Internals} from 'remotion';
+import {Transform3DModeStateProvider} from '../state/transform-3d-mode';
import {GlobalKeybindings} from './GlobalKeybindings';
import {InitialCompositionLoader} from './InitialCompositionLoader';
import {MenuToolbar} from './MenuToolbar';
@@ -80,14 +81,16 @@ export const EditorContent: React.FC<{
return (
<TimelineSelectionProvider>
- <StudioClearSelectionArea>
- <InitialCompositionLoader />
- <MenuToolbar readOnlyStudio={readOnlyStudio} />
- <GlobalKeybindings />
- <TimelineKeyframeDragStateProvider>
- {content}
- </TimelineKeyframeDragStateProvider>
- </StudioClearSelectionArea>
+ <Transform3DModeStateProvider>
+ <StudioClearSelectionArea>
+ <InitialCompositionLoader />
+ <MenuToolbar readOnlyStudio={readOnlyStudio} />
+ <GlobalKeybindings />
+ <TimelineKeyframeDragStateProvider>
+ {content}
+ </TimelineKeyframeDragStateProvider>
+ </StudioClearSelectionArea>
+ </Transform3DModeStateProvider>
</TimelineSelectionProvider>
);
};
diff --git a/packages/studio/src/components/InlineAction.tsx b/packages/studio/src/components/InlineAction.tsx
index 44da193366..c31ff3d2ae 100644
--- a/packages/studio/src/components/InlineAction.tsx
+++ b/packages/studio/src/components/InlineAction.tsx
@@ -17,6 +17,7 @@ export type InlineActionProps = Omit<
> & {
readonly onClick: React.MouseEventHandler<HTMLButtonElement>;
readonly renderAction: RenderInlineAction;
+ readonly hoveredColor?: string;
readonly unhoveredColor?: string;
readonly variant: 'compact' | null;
readonly style?: React.CSSProperties;
@@ -27,6 +28,7 @@ export const InlineAction = ({
onClick,
disabled,
title,
+ hoveredColor = WHITE,
unhoveredColor = LIGHT_TEXT,
variant,
style: customStyle,
@@ -53,11 +55,11 @@ export const InlineAction = ({
? TRANSPARENT
: getBackgroundFromHoverState({hovered: true, selected: false}),
idleColor: unhoveredColor,
- hoverColor: disabled ? unhoveredColor : WHITE,
+ hoverColor: disabled ? unhoveredColor : hoveredColor,
}),
...customStyle,
};
- }, [customStyle, disabled, unhoveredColor, variant]);
+ }, [customStyle, disabled, hoveredColor, unhoveredColor, variant]);
return (
<button
diff --git a/packages/studio/src/components/InspectorPanel/AlignmentControls.tsx b/packages/studio/src/components/InspectorPanel/AlignmentControls.tsx
index fd446eee8f..5cf2844f49 100644
--- a/packages/studio/src/components/InspectorPanel/AlignmentControls.tsx
+++ b/packages/studio/src/components/InspectorPanel/AlignmentControls.tsx
@@ -170,7 +170,7 @@ export const AlignmentControls: React.FC<{
)
: String(fieldSchema.default ?? '0px 0px');
- const [currentX, currentY] = parseTranslate(currentTranslate);
+ const [currentX, currentY, currentZ] = parseTranslate(currentTranslate);
const {x: newX, y: newY} = computeAlignedTranslate({
direction,
@@ -181,7 +181,7 @@ export const AlignmentControls: React.FC<{
scale,
});
- const newValue = serializeTranslate(newX, newY);
+ const newValue = serializeTranslate([newX, newY, currentZ]);
const undoLabels = {
left: 'Align left',
diff --git a/packages/studio/src/components/InspectorPanel/styles.ts b/packages/studio/src/components/InspectorPanel/styles.ts
index 0f793eeb3e..0da017946b 100644
--- a/packages/studio/src/components/InspectorPanel/styles.ts
+++ b/packages/studio/src/components/InspectorPanel/styles.ts
@@ -55,7 +55,7 @@ export const sectionHeader: React.CSSProperties = {
fontSize: 12,
fontWeight: 'bold',
lineHeight: '24px',
- padding: `4px ${INSPECTOR_PANEL_HORIZONTAL_PADDING}px`,
+ padding: `4px 0 4px ${INSPECTOR_PANEL_HORIZONTAL_PADDING}px`,
userSelect: 'none',
};
diff --git a/packages/studio/src/components/InspectorSequenceSection.tsx b/packages/studio/src/components/InspectorSequenceSection.tsx
index 28be15e19b..d1f587beff 100644
--- a/packages/studio/src/components/InspectorSequenceSection.tsx
+++ b/packages/studio/src/components/InspectorSequenceSection.tsx
@@ -9,7 +9,7 @@ import React, {
import {Internals, type TSequence} from 'remotion';
import type {CodePosition} from '../error-overlay/react-overlay/utils/get-source-map';
import {StudioServerConnectionCtx} from '../helpers/client-id';
-import {LIGHT_TEXT, WHITE} from '../helpers/colors';
+import {BLUE, LIGHT_TEXT, WHITE} from '../helpers/colors';
import {getPreviewFileType} from '../helpers/get-preview-file-type';
import type {SequenceNodePathInfo} from '../helpers/get-timeline-sequence-sort-key';
import {isStudioInteractivityEnabled} from '../helpers/interactivity-enabled';
@@ -21,9 +21,11 @@ import {
type TimelineTreeNode,
} from '../helpers/timeline-layout';
import {BorderRadiusIcon} from '../icons/border-radius';
+import {CubeIcon} from '../icons/cube';
import {FullscreenIcon} from '../icons/fullscreen';
import {Plus} from '../icons/plus';
import {SetSelectedModalContext} from '../state/modals';
+import {Transform3DModeStateContext} from '../state/transform-3d-mode';
import {AssetFileIcon} from './AssetFileIcon';
import {InlineAction} from './InlineAction';
import {InlineCaptionInspector} from './InlineCaptionInspector';
@@ -57,9 +59,12 @@ import {
} from './Timeline/TimelineRowLayoutContext';
import {
getTimelineSelectionFromNodePathInfo,
+ getTimelineSequenceSelectionKey,
TimelineSelectionOrderProvider,
type TimelineSelection,
} from './Timeline/TimelineSelection';
+import {propStatusHas3DTransformValue} from './Timeline/transform-3d-mode';
+import {Transform3DModeContext} from './Timeline/Transform3DModeContext';
import {useTimelineExpandedTree} from './Timeline/use-timeline-expanded-tree';
import {useSelectAsset} from './use-select-asset';
@@ -95,6 +100,12 @@ const borderRadiusToggleIcon: React.CSSProperties = {
width: 15,
};
+const transform3DToggleIcon: React.CSSProperties = {
+ flexShrink: 0,
+ height: 14,
+ width: 14,
+};
+
const collapsibleSectionHeaderButton: React.CSSProperties = {
appearance: 'none',
backgroundColor: 'transparent',
@@ -380,6 +391,12 @@ export const InspectorSequenceSection: React.FC<{
const [automaticSectionExpansion, setAutomaticSectionExpansion] = useState<
Readonly<Record<string, boolean>>
>({});
+ const {manuallyEnabledSequenceKeys, setManuallyEnabled} = useContext(
+ Transform3DModeStateContext,
+ );
+ const sequenceKey = getTimelineSequenceSelectionKey(nodePathInfo);
+ const manuallyEnabled3DTransform =
+ manuallyEnabledSequenceKeys.has(sequenceKey);
const {previewServerState} = useContext(StudioServerConnectionCtx);
const {getDragOverrides} = useContext(
Internals.VisualModeDragOverridesContext,
@@ -513,6 +530,25 @@ export const InspectorSequenceSection: React.FC<{
propStatuses,
nodePathInfo.sequenceSubscriptionKey,
);
+ const automaticallyEnabled3DTransform = useMemo(() => {
+ return [
+ 'style.translate',
+ 'style.scale',
+ 'style.rotate',
+ 'style.transformOrigin',
+ ].some((fieldKey) =>
+ propStatusHas3DTransformValue({
+ fieldKey,
+ propStatus: sequencePropStatuses?.[fieldKey],
+ runtimeValue: runtimeValues[fieldKey],
+ }),
+ );
+ }, [runtimeValues, sequencePropStatuses]);
+ const show3DTransformControls =
+ automaticallyEnabled3DTransform || manuallyEnabled3DTransform;
+ const onToggle3DTransform = useCallback(() => {
+ setManuallyEnabled(sequenceKey, !manuallyEnabled3DTransform);
+ }, [manuallyEnabled3DTransform, sequenceKey, setManuallyEnabled]);
const {schema} = sequence.controls;
const getControlGroupActivity = useCallback(
(group: InspectorControlGroup) => {
@@ -722,6 +758,26 @@ export const InspectorSequenceSection: React.FC<{
/>
) : null;
+ const transform3DAction = (
+ <InlineAction
+ variant={null}
+ disabled={automaticallyEnabled3DTransform}
+ onClick={onToggle3DTransform}
+ title={
+ automaticallyEnabled3DTransform
+ ? '3D controls are required by the current transform values'
+ : show3DTransformControls
+ ? 'Hide 3D transform controls'
+ : 'Show 3D transform controls'
+ }
+ hoveredColor={show3DTransformControls ? BLUE : undefined}
+ unhoveredColor={show3DTransformControls ? BLUE : LIGHT_TEXT}
+ renderAction={(color) => (
+ <CubeIcon color={color} style={transform3DToggleIcon} />
+ )}
+ />
+ );
+
const effectsHeader = (
<div style={sectionHeaderRow}>
<div style={effectsHeaderTitle}>Effects</div>
@@ -777,6 +833,7 @@ export const InspectorSequenceSection: React.FC<{
return (
<div style={sectionHeaderRow}>
<div style={effectsHeaderTitle}>{group.label}</div>
+ {group.id === 'transforms' ? transform3DAction : null}
</div>
);
};
@@ -806,12 +863,16 @@ export const InspectorSequenceSection: React.FC<{
header={renderControlGroupHeader(group)}
>
{isControlGroupExpanded(group) ? (
- <>
- {group.id === 'transforms'
- ? renderTransformControls()
- : null}
- {group.rows.map(renderRow)}
- </>
+ group.id === 'transforms' ? (
+ <Transform3DModeContext.Provider
+ value={show3DTransformControls}
+ >
+ {renderTransformControls()}
+ {group.rows.map(renderRow)}
+ </Transform3DModeContext.Provider>
+ ) : (
+ group.rows.map(renderRow)
+ )
) : null}
</InspectorSection>
))}
diff --git a/packages/studio/src/components/SelectedOutlineCanvasRotation.tsx b/packages/studio/src/components/SelectedOutlineCanvasRotation.tsx
new file mode 100644
index 0000000000..59d8918aa2
--- /dev/null
+++ b/packages/studio/src/components/SelectedOutlineCanvasRotation.tsx
@@ -0,0 +1,282 @@
+import React, {useContext} from 'react';
+import {Internals} from 'remotion';
+import {TRANSPARENT} from '../helpers/colors';
+import {startPointerSession} from '../helpers/pointer-session';
+import {EditorSnappingContext} from '../state/editor-snapping';
+import {canvasRotationCursor} from './canvas-rotation-cursor';
+import {
+ forceSpecificCursor,
+ stopForcingSpecificCursor,
+} from './ForceSpecificCursor';
+import {showNotification} from './Notifications/NotificationCenter';
+import {
+ clearSelectedOutlineRotationDragOverrides,
+ getSelectedOutline3DRotationDragValues,
+ getSelectedOutlineRotationDragChanges,
+ getSelectedOutlineRotationDragStates,
+ getSelectedOutlineRotationDragValues,
+ isSelectedOutlineDragPastThreshold,
+ snapSelectedOutlineRotationDeltaDegrees,
+ type SelectedOutlineKeyframedDragChange,
+ type SelectedOutlineStaticDragChange,
+} from './selected-outline-drag';
+import type {SelectedOutline} from './selected-outline-geometry';
+import {
+ getAngleDegrees,
+ getSelectedOutlineRotationDeltaDegrees,
+ getSelectedOutlineRotationPivot,
+} from './selected-outline-measurement';
+import {
+ rotateFieldKey,
+ type SelectedOutlineLayoutTarget,
+ type SelectedOutlineTarget,
+} from './selected-outline-types';
+import {svgPointToClientPoint} from './svg-point-to-client-point';
+import {callAddKeyframes} from './Timeline/call-add-keyframe';
+import {commitPendingInspectorFields} from './Timeline/focus-inspector-field';
+import {getCurrentFrame} from './Timeline/imperative-state';
+import {saveSequenceProps} from './Timeline/save-sequence-prop';
+
+const rotationDegreesPerPixel = 0.5;
+
+export const SelectedOutlineCanvasRotation: React.FC<{
+ readonly getLatestTargetByKey: (
+ key: string,
+ ) => SelectedOutlineTarget | undefined;
+ readonly layoutTarget: SelectedOutlineLayoutTarget;
+ readonly onDraggingChange: (dragging: boolean) => void;
+ readonly outline: SelectedOutline;
+}> = ({getLatestTargetByKey, layoutTarget, onDraggingChange, outline}) => {
+ const {getDragOverrides} = useContext(
+ Internals.VisualModeDragOverridesContext,
+ );
+ const {setPropStatuses, setDragOverrides, clearDragOverrides} = useContext(
+ Internals.VisualModeSettersContext,
+ );
+ const {editorSnapping} = useContext(EditorSnappingContext);
+
+ const onPointerDown = React.useCallback(
+ (event: React.PointerEvent<SVGPathElement>) => {
+ if (event.button !== 0) {
+ return;
+ }
+
+ const target = getLatestTargetByKey(layoutTarget.key);
+ const rotationDrag = target?.rotationDrag ?? null;
+ if (rotationDrag === null || !target?.selectedForRotation) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ if (commitPendingInspectorFields()) {
+ return;
+ }
+
+ const svg = event.currentTarget.ownerSVGElement;
+ if (svg === null) {
+ return;
+ }
+
+ const startPointer = {x: event.clientX, y: event.clientY};
+ const center = svgPointToClientPoint(
+ getSelectedOutlineRotationPivot({
+ dimensions: outline.dimensions,
+ points: outline.uncroppedPoints ?? outline.points,
+ transformOriginValue: rotationDrag.transformOriginValue,
+ }),
+ svg.getBoundingClientRect(),
+ );
+ const dragStates = getSelectedOutlineRotationDragStates({
+ dragTargets: [rotationDrag],
+ getDragOverrides,
+ timelinePosition: getCurrentFrame(),
+ });
+ let previousAngle = getAngleDegrees(center, startPointer);
+ let accumulatedDelta = 0;
+ let lastValues = new Map<string, string>();
+ let dragStarted = false;
+
+ const onPointerMove = (moveEvent: PointerEvent) => {
+ moveEvent.preventDefault();
+ const screenDeltaX = moveEvent.clientX - startPointer.x;
+ const screenDeltaY = moveEvent.clientY - startPointer.y;
+ if (!dragStarted) {
+ if (
+ !isSelectedOutlineDragPastThreshold({
+ deltaX: screenDeltaX,
+ deltaY: screenDeltaY,
+ })
+ ) {
+ return;
+ }
+
+ dragStarted = true;
+ onDraggingChange(true);
+ }
+
+ if (rotationDrag.transform3DMode) {
+ const startRotation = dragStates[0]?.startRotation ?? [0, 0, 0];
+ let rotationXDeltaDegrees = -screenDeltaY * rotationDegreesPerPixel;
+ let rotationYDeltaDegrees = screenDeltaX * rotationDegreesPerPixel;
+ if (moveEvent.shiftKey && editorSnapping) {
+ rotationXDeltaDegrees =
+ Math.round((startRotation[0] + rotationXDeltaDegrees) / 15) * 15 -
+ startRotation[0];
+ rotationYDeltaDegrees =
+ Math.round((startRotation[1] + rotationYDeltaDegrees) / 15) * 15 -
+ startRotation[1];
+ }
+
+ lastValues = getSelectedOutline3DRotationDragValues({
+ dragStates,
+ rotationXDeltaDegrees,
+ rotationYDeltaDegrees,
+ });
+ forceSpecificCursor(canvasRotationCursor);
+ } else {
+ const nextAngle = getAngleDegrees(center, {
+ x: moveEvent.clientX,
+ y: moveEvent.clientY,
+ });
+ accumulatedDelta += getSelectedOutlineRotationDeltaDegrees({
+ from: previousAngle,
+ to: nextAngle,
+ });
+ previousAngle = nextAngle;
+ const rotationDeltaDegrees =
+ moveEvent.shiftKey && editorSnapping
+ ? snapSelectedOutlineRotationDeltaDegrees({
+ dragStates,
+ rotationDeltaDegrees: accumulatedDelta,
+ })
+ : accumulatedDelta;
+ lastValues = getSelectedOutlineRotationDragValues({
+ dragStates,
+ rotationDeltaDegrees,
+ });
+ forceSpecificCursor(canvasRotationCursor);
+ }
+
+ for (const dragState of dragStates) {
+ const value = lastValues.get(dragState.key);
+ if (value === undefined) {
+ throw new Error('Expected rotation drag value to be available');
+ }
+
+ if (dragState.target.propStatus.status === 'keyframed') {
+ setDragOverrides(
+ dragState.target.nodePath,
+ rotateFieldKey,
+ Internals.makeKeyframedDragOverride({
+ status: dragState.target.propStatus,
+ frame: dragState.sourceFrame,
+ value,
+ }),
+ );
+ } else {
+ setDragOverrides(
+ dragState.target.nodePath,
+ rotateFieldKey,
+ Internals.makeStaticDragOverride(value),
+ );
+ }
+ }
+ };
+
+ const onPointerUp = () => {
+ if (dragStarted) {
+ stopForcingSpecificCursor();
+ onDraggingChange(false);
+ }
+
+ const changes = getSelectedOutlineRotationDragChanges({
+ dragStates,
+ lastValues,
+ });
+ if (changes.length === 0) {
+ clearSelectedOutlineRotationDragOverrides({
+ clearDragOverrides,
+ dragStates,
+ });
+ return;
+ }
+
+ const staticChanges = changes.filter(
+ (change): change is SelectedOutlineStaticDragChange =>
+ change.type === 'static',
+ );
+ const keyframedChanges = changes.filter(
+ (change): change is SelectedOutlineKeyframedDragChange =>
+ change.type === 'keyframed',
+ );
+
+ Promise.all([
+ staticChanges.length > 0
+ ? saveSequenceProps({
+ changes: staticChanges,
+ addedKeyframes: null,
+ movedKeyframes: null,
+ setPropStatuses,
+ clientId: rotationDrag.clientId,
+ undoLabel: 'Rotate sequence',
+ redoLabel: 'Rotate sequence back',
+ })
+ : Promise.resolve(),
+ callAddKeyframes({
+ sequenceKeyframes: keyframedChanges,
+ effectKeyframes: [],
+ setPropStatuses,
+ clientId: rotationDrag.clientId,
+ }),
+ ])
+ .catch((error) => {
+ showNotification(
+ `Could not save sequence props: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ 4000,
+ );
+ })
+ .finally(() => {
+ clearSelectedOutlineRotationDragOverrides({
+ clearDragOverrides,
+ dragStates,
+ });
+ });
+ };
+
+ // The polygon gates pointer-down, while the stable overlay keeps the
+ // session alive after the pointer leaves the selected item.
+ startPointerSession({
+ event,
+ target: svg,
+ onMove: onPointerMove,
+ onEnd: onPointerUp,
+ });
+ },
+ [
+ clearDragOverrides,
+ editorSnapping,
+ getDragOverrides,
+ getLatestTargetByKey,
+ layoutTarget.key,
+ onDraggingChange,
+ outline.dimensions,
+ outline.points,
+ outline.uncroppedPoints,
+ setDragOverrides,
+ setPropStatuses,
+ ],
+ );
+ return (
+ <polygon
+ points={outline.points.map((point) => `${point.x},${point.y}`).join(' ')}
+ fill={TRANSPARENT}
+ pointerEvents="all"
+ cursor={canvasRotationCursor}
+ onPointerDown={onPointerDown}
+ data-remotion-studio-canvas-rotation
+ />
+ );
+};
diff --git a/packages/studio/src/components/SelectedOutlineElement.tsx b/packages/studio/src/components/SelectedOutlineElement.tsx
index 555f242b5d..af7819d137 100644
--- a/packages/studio/src/components/SelectedOutlineElement.tsx
+++ b/packages/studio/src/components/SelectedOutlineElement.tsx
@@ -15,6 +15,7 @@ import {
useIsTimelineSequenceHovered,
useSetTimelineSequenceHover,
} from '../state/timeline-sequence-hover';
+import {Transform3DModeStateContext} from '../state/transform-3d-mode';
import {callApi} from './call-api';
import {useConfirmationDialog} from './ConfirmationDialog';
import {useSelectComposition} from './InitialCompositionLoader';
@@ -23,12 +24,14 @@ import type {SelectedOutline} from './selected-outline-geometry';
import {type SelectedOutlineSnapPoint} from './selected-outline-snap';
import {
cropFieldKeys,
+ rotateFieldKey,
type SelectedOutlineDragTarget,
type SelectedOutlineLayoutTarget,
type SelectedOutlineRotationDragTarget,
type SelectedOutlineScaleDragTarget,
type SelectedOutlineTarget,
} from './selected-outline-types';
+import {SelectedOutlineCanvasRotation} from './SelectedOutlineCanvasRotation';
import {SelectedOutlineCropControls} from './SelectedOutlineCropControls';
import {SelectedOutlinePolygon} from './SelectedOutlinePolygon';
import {SelectedOutlineRotationCornerHandle} from './SelectedOutlineRotationCornerHandle';
@@ -37,9 +40,10 @@ import {disableSequenceInteractivity} from './Timeline/disable-sequence-interact
import {duplicateSequencesFromSource} from './Timeline/duplicate-selected-timeline-item';
import {getSequenceContextMenuItems} from './Timeline/get-sequence-context-menu-items';
import {getTimelineAssetLinkInfo} from './Timeline/timeline-asset-link';
-import type {
- TimelineSelection,
- TimelineSelectionInteraction,
+import {
+ getTimelineSequenceSelectionKey,
+ type TimelineSelection,
+ type TimelineSelectionInteraction,
} from './Timeline/TimelineSelection';
import {getOriginalLocationFromStack} from './Timeline/TimelineStack/get-stack';
import {
@@ -107,6 +111,7 @@ const SelectedOutlineElementUnmemoized: React.FC<
const selectComposition = useSelectComposition();
const {compositions} = useContext(Internals.CompositionManager);
const {setSelectedModal} = useContext(SetSelectedModalContext);
+ const {setManuallyEnabled} = useContext(Transform3DModeStateContext);
const setHoveredSequence = useSetTimelineSequenceHover();
const targetRef = useRef(layoutTarget);
useLayoutEffect(() => {
@@ -269,6 +274,7 @@ const SelectedOutlineElementUnmemoized: React.FC<
!sourceEditDisabled &&
previewServerState.type === 'connected';
const canCrop = contextMenuTarget.canCrop && !sourceEditDisabled;
+ const canRotate = !sourceEditDisabled;
return getSequenceContextMenuItems({
assetLinkInfo,
@@ -437,9 +443,43 @@ const SelectedOutlineElementUnmemoized: React.FC<
subMenu: null,
value: 'crop',
},
+ {
+ type: 'item' as const,
+ id: 'rotate',
+ keyHint: null,
+ label: isProgrammaticallyDuplicated ? 'Rotate all' : 'Rotate',
+ leftItem: null,
+ disabled: !canRotate,
+ onClick: () => {
+ if (!canRotate) {
+ return;
+ }
+
+ setManuallyEnabled(
+ getTimelineSequenceSelectionKey(
+ contextMenuTarget.nodePathInfo,
+ ),
+ true,
+ );
+ onSelect(
+ {
+ type: 'sequence-prop',
+ nodePathInfo: {
+ ...contextMenuTarget.nodePathInfo,
+ auxiliaryKeys: ['controls', rotateFieldKey],
+ },
+ key: rotateFieldKey,
+ },
+ {shiftKey: false, toggleKey: false},
+ );
+ },
+ quickSwitcherLabel: null,
+ subMenu: null,
+ value: 'rotate',
+ },
{
type: 'divider' as const,
- id: 'crop-divider',
+ id: 'rotate-divider',
},
]
: [],
@@ -453,6 +493,7 @@ const SelectedOutlineElementUnmemoized: React.FC<
onSelect,
previewServerState,
resolveOriginalLocation,
+ setManuallyEnabled,
selectAsset,
setSelectedModal,
setPropStatuses,
@@ -481,6 +522,14 @@ const SelectedOutlineElementUnmemoized: React.FC<
scale={scale}
showSelectedOutline={layoutTarget?.showSelectedOutline ?? false}
/>
+ {layoutTarget?.selectedForRotation && controlTarget?.rotationDrag ? (
+ <SelectedOutlineCanvasRotation
+ getLatestTargetByKey={getLatestTargetByKey}
+ layoutTarget={layoutTarget}
+ onDraggingChange={onDraggingChange}
+ outline={outline}
+ />
+ ) : null}
<SelectedOutlineCropControls
outline={outline}
onDraggingChange={onDraggingChange}
diff --git a/packages/studio/src/components/SelectedOutlineOverlay.tsx b/packages/studio/src/components/SelectedOutlineOverlay.tsx
index c3d8811ec3..e03066d9c7 100644
--- a/packages/studio/src/components/SelectedOutlineOverlay.tsx
+++ b/packages/studio/src/components/SelectedOutlineOverlay.tsx
@@ -29,10 +29,12 @@ import {
useSetTimelineSequenceHover,
useTimelineSequenceHoverState,
} from '../state/timeline-sequence-hover';
+import {Transform3DModeStateContext} from '../state/transform-3d-mode';
import {getSelectedOutlineActiveSchema} from './selected-outline-drag';
import {
getSelectedCropInfo,
getSelectedEffectFieldsBySequenceKey,
+ getSelectedRotationInfo,
getSelectedSequenceKeys,
getSelectedTransformOriginInfo,
getSequenceKeysContainingSelection,
@@ -58,6 +60,7 @@ import {
type TimelineSelection,
type TimelineSelectionInteraction,
} from './Timeline/TimelineSelection';
+import {propStatusHas3DTransformValue} from './Timeline/transform-3d-mode';
export {orderOutlinesForRendering};
@@ -65,6 +68,7 @@ export {
applySelectedOutlineDragAxisLock,
applySelectedOutlineTransformOriginAxisLock,
compensateTranslateForTransformOrigin,
+ getSelectedOutline3DRotationDragValues,
getSelectedOutlineActiveSchema,
getSelectedOutlineCropDragChanges,
getSelectedOutlineCropDragValues,
@@ -203,6 +207,7 @@ const calculateOutlineTargets = ({
getDragOverrides,
getScaleLockState,
isFullscreen,
+ manuallyEnabled3DTransformSequenceKeys,
mode,
previewSelectionAvailable,
propStatuses,
@@ -210,6 +215,7 @@ const calculateOutlineTargets = ({
selectableOutlines,
selectedCropInfo,
selectedEffectsBySequenceKey,
+ selectedRotationInfo,
selectedSequenceKeys,
selectedTransformOriginInfo,
sequenceKeysContainingSelection,
@@ -226,6 +232,7 @@ const calculateOutlineTargets = ({
typeof ScaleLockContext
>['getScaleLockState'];
readonly isFullscreen: boolean;
+ readonly manuallyEnabled3DTransformSequenceKeys: ReadonlySet<string>;
readonly previewSelectionAvailable: boolean;
readonly propStatuses: React.ContextType<
typeof Internals.VisualModePropStatusesContext
@@ -234,6 +241,7 @@ const calculateOutlineTargets = ({
readonly selectedEffectsBySequenceKey: ReturnType<
typeof getSelectedEffectFieldsBySequenceKey
>;
+ readonly selectedRotationInfo: ReturnType<typeof getSelectedRotationInfo>;
readonly selectedSequenceKeys: ReadonlySet<string>;
readonly selectedTransformOriginInfo: ReturnType<
typeof getSelectedTransformOriginInfo
@@ -350,7 +358,31 @@ const calculateOutlineTargets = ({
const selectedForTransformOrigin =
selectedTransformOriginInfo?.sequenceKey === key;
const selectedForCrop = selectedCropInfo?.sequenceKey === key;
+ const selectedForRotation = selectedRotationInfo?.sequenceKey === key;
const selectedForUvHandles = selectedEffectsBySequenceKey.has(key);
+ const fieldSchema = activeSchema?.[translateFieldKey];
+ const propStatus = nodePropStatuses?.[translateFieldKey];
+ const scaleFieldSchema = activeSchema?.[scaleFieldKey];
+ const scalePropStatus = nodePropStatuses?.[scaleFieldKey];
+ const rotationFieldSchema = activeSchema?.[rotateFieldKey];
+ const rotationPropStatus = nodePropStatuses?.[rotateFieldKey];
+ const transformOriginFieldSchema = activeSchema?.[transformOriginFieldKey];
+ const transformOriginPropStatus =
+ nodePropStatuses?.[transformOriginFieldKey];
+ const transformOriginValueForRotation =
+ transformOriginFieldSchema?.type === 'transform-origin' &&
+ (transformOriginPropStatus?.status === 'static' ||
+ transformOriginPropStatus?.status === 'keyframed')
+ ? String(
+ Internals.getEffectiveVisualModeValue({
+ propStatus: transformOriginPropStatus,
+ dragOverrideValue: dragOverrides[transformOriginFieldKey],
+ defaultValue: transformOriginFieldSchema.default,
+ frame: sourceFrame,
+ shouldResortToDefaultValueIfUndefined: true,
+ }) ?? transformOriginFieldSchema.default,
+ )
+ : '50% 50%';
const layoutTarget: SelectedOutlineLayoutTarget = {
key,
containsSelection,
@@ -360,9 +392,11 @@ const calculateOutlineTargets = ({
ref: sequence.refForOutline,
selected,
selectedForCrop,
+ selectedForRotation,
selectedForTransformOrigin,
selectedForUvHandles,
showSelectedOutline,
+ transformOriginValue: transformOriginValueForRotation,
selection: {
type: 'sequence',
nodePathInfo: selectionNodePathInfo,
@@ -378,29 +412,6 @@ const calculateOutlineTargets = ({
cropValues,
propStatuses: nodePropStatuses,
});
- const fieldSchema = activeSchema?.[translateFieldKey];
- const propStatus = nodePropStatuses?.[translateFieldKey];
- const scaleFieldSchema = activeSchema?.[scaleFieldKey];
- const scalePropStatus = nodePropStatuses?.[scaleFieldKey];
- const rotationFieldSchema = activeSchema?.[rotateFieldKey];
- const rotationPropStatus = nodePropStatuses?.[rotateFieldKey];
- const transformOriginFieldSchema = activeSchema?.[transformOriginFieldKey];
- const transformOriginPropStatus =
- nodePropStatuses?.[transformOriginFieldKey];
- const transformOriginValueForRotation =
- transformOriginFieldSchema?.type === 'transform-origin' &&
- (transformOriginPropStatus?.status === 'static' ||
- transformOriginPropStatus?.status === 'keyframed')
- ? String(
- Internals.getEffectiveVisualModeValue({
- propStatus: transformOriginPropStatus,
- dragOverrideValue: dragOverrides[transformOriginFieldKey],
- defaultValue: transformOriginFieldSchema.default,
- frame: sourceFrame,
- shouldResortToDefaultValueIfUndefined: true,
- }) ?? transformOriginFieldSchema.default,
- )
- : '50% 50%';
const canDragStatus =
propStatus?.status === 'static' ||
(propStatus?.status === 'keyframed' &&
@@ -428,6 +439,20 @@ const calculateOutlineTargets = ({
controls !== null &&
rotationFieldSchema?.type === 'rotation-css' &&
canRotationDragStatus;
+ const transform3DMode =
+ manuallyEnabled3DTransformSequenceKeys.has(key) ||
+ [
+ 'style.translate',
+ 'style.scale',
+ 'style.rotate',
+ 'style.transformOrigin',
+ ].some((fieldKey) =>
+ propStatusHas3DTransformValue({
+ fieldKey,
+ propStatus: nodePropStatuses?.[fieldKey],
+ runtimeValue: runtimeValues[fieldKey],
+ }),
+ );
const transformOriginSourceFrame =
selectedTransformOriginInfo?.displayFrame === null ||
selectedTransformOriginInfo?.displayFrame === undefined
@@ -443,7 +468,7 @@ const calculateOutlineTargets = ({
propStatus.interpolationFunction === 'interpolate');
const canTransformOriginDrag =
previewInteractive &&
- selectedForTransformOrigin &&
+ (selectedForTransformOrigin || selectedForRotation) &&
controls !== null &&
transformOriginFieldSchema?.type === 'transform-origin' &&
fieldSchema?.type === 'translate' &&
@@ -527,6 +552,7 @@ const calculateOutlineTargets = ({
keyframeDisplayOffset,
nodePath,
schema: controls.schema,
+ transform3DMode,
transformOriginValue: transformOriginValueForRotation,
}
: null,
@@ -758,6 +784,7 @@ const SelectedOutlineOverlayUnmemoized: React.FC<
Internals.VisualModeDragOverridesContext,
);
const {getScaleLockState} = useContext(ScaleLockContext);
+ const {manuallyEnabledSequenceKeys} = useContext(Transform3DModeStateContext);
const {editorShowOutlines} = useContext(EditorShowOutlinesContext);
const setHoveredSequence = useSetTimelineSequenceHover();
const hoveredSequence = useTimelineSequenceHoverState();
@@ -783,6 +810,10 @@ const SelectedOutlineOverlayUnmemoized: React.FC<
() => getSelectedTransformOriginInfo(selectedItems),
[selectedItems],
);
+ const selectedRotationInfo = useMemo(
+ () => getSelectedRotationInfo(selectedItems),
+ [selectedItems],
+ );
const selectedCropInfo = useMemo(
() => getSelectedCropInfo(selectedItems),
[selectedItems],
@@ -828,10 +859,12 @@ const SelectedOutlineOverlayUnmemoized: React.FC<
getDragOverrides,
getScaleLockState,
isFullscreen,
+ manuallyEnabled3DTransformSequenceKeys: manuallyEnabledSequenceKeys,
previewSelectionAvailable,
propStatuses,
selectedCropInfo,
selectedEffectsBySequenceKey,
+ selectedRotationInfo,
selectedSequenceKeys,
selectedTransformOriginInfo,
sequenceKeysContainingSelection,
@@ -842,11 +875,13 @@ const SelectedOutlineOverlayUnmemoized: React.FC<
getDragOverrides,
getScaleLockState,
isFullscreen,
+ manuallyEnabledSequenceKeys,
previewSelectionAvailable,
previewServerState,
propStatuses,
selectedCropInfo,
selectedEffectsBySequenceKey,
+ selectedRotationInfo,
selectedSequenceKeys,
selectedTransformOriginInfo,
sequenceKeysContainingSelection,
diff --git a/packages/studio/src/components/SelectedOutlineRenderer.tsx b/packages/studio/src/components/SelectedOutlineRenderer.tsx
index 8fc17a6e8e..8d8aca823d 100644
--- a/packages/studio/src/components/SelectedOutlineRenderer.tsx
+++ b/packages/studio/src/components/SelectedOutlineRenderer.tsx
@@ -339,16 +339,6 @@ const SelectedOutlineRendererUnmemoized: React.FC<{
layoutTarget={targetsByKey.get(outline.key)}
/>
))}
- {/* Keep transform-origin handles above every transparent outline polygon so SVG hit-testing reaches the selected knob first. */}
- {outlinesForRendering.map((outline) => (
- <SelectedOutlineTransformOriginHandle
- key={`${outline.key}-transform-origin`}
- outline={outline}
- onDraggingChange={onDraggingChange}
- getLatestTargetByKey={getLatestOutlineTargetByKey}
- layoutTarget={targetsByKey.get(outline.key)}
- />
- ))}
{/* Keep UV controls above every transparent outline polygon so SVG hit-testing reaches the handles first. */}
{outlinesForRendering.map((outline) => (
<SelectedOutlineUvHandleConnectionLayer
@@ -366,6 +356,16 @@ const SelectedOutlineRendererUnmemoized: React.FC<{
layoutTarget={targetsByKey.get(outline.key)}
/>
))}
+ {/* Keep transform-origin handles above the canvas rotation surface so the knob stays visible in rotation mode and hit-testable while editing the origin. */}
+ {outlinesForRendering.map((outline) => (
+ <SelectedOutlineTransformOriginHandle
+ key={`${outline.key}-transform-origin`}
+ outline={outline}
+ onDraggingChange={onDraggingChange}
+ getLatestTargetByKey={getLatestOutlineTargetByKey}
+ layoutTarget={targetsByKey.get(outline.key)}
+ />
+ ))}
</svg>
);
};
diff --git a/packages/studio/src/components/SelectedOutlineRotationCornerHandle.tsx b/packages/studio/src/components/SelectedOutlineRotationCornerHandle.tsx
index 9cd9cb7808..ad6265e728 100644
--- a/packages/studio/src/components/SelectedOutlineRotationCornerHandle.tsx
+++ b/packages/studio/src/components/SelectedOutlineRotationCornerHandle.tsx
@@ -80,6 +80,7 @@ export const SelectedOutlineRotationCornerHandle: React.FC<{
const {editorSnapping} = useContext(EditorSnappingContext);
const rotationDrag = target?.rotationDrag ?? null;
const selected = target?.selected ?? false;
+ const containsSelection = target?.containsSelection ?? false;
const circleRef = useRef<SVGCircleElement>(null);
const cornerInfo = useMemo(
() => getSelectedOutlineRotationCornerInfo(outline.points, corner),
@@ -101,7 +102,8 @@ export const SelectedOutlineRotationCornerHandle: React.FC<{
}
const interaction = getOutlineSelectionInteraction(event);
- const shouldUpdateSelection = !selected || interaction.toggleKey;
+ const shouldUpdateSelection =
+ (!selected && !containsSelection) || interaction.toggleKey;
if (shouldUpdateSelection && target !== undefined) {
onSelect(target.selection, {
shiftKey: false,
@@ -312,6 +314,7 @@ export const SelectedOutlineRotationCornerHandle: React.FC<{
},
[
clearDragOverrides,
+ containsSelection,
cornerInfo,
editorSnapping,
getDragOverrides,
@@ -345,6 +348,10 @@ export const SelectedOutlineRotationCornerHandle: React.FC<{
vectorEffect="non-scaling-stroke"
pointerEvents="all"
cursor={cornerInfo.cursor}
+ data-remotion-studio-rotation-corner={corner}
+ data-remotion-studio-rotation-corner-contains-selection={
+ containsSelection
+ }
onPointerEnter={() => {
if (!dragging) {
onHoverChange(outline.key);
diff --git a/packages/studio/src/components/SelectedOutlineScaleEdgeLine.tsx b/packages/studio/src/components/SelectedOutlineScaleEdgeLine.tsx
index 7b0d96949f..a91154e39b 100644
--- a/packages/studio/src/components/SelectedOutlineScaleEdgeLine.tsx
+++ b/packages/studio/src/components/SelectedOutlineScaleEdgeLine.tsx
@@ -73,6 +73,7 @@ export const SelectedOutlineScaleEdgeLine: React.FC<{
);
const scaleDrag = target?.scaleDrag ?? null;
const selected = target?.selected ?? false;
+ const containsSelection = target?.containsSelection ?? false;
const lineRef = useRef<SVGLineElement>(null);
const edgeInfo = useMemo(
() => getSelectedOutlineScaleEdgeInfo(outline.points, edge),
@@ -90,7 +91,9 @@ export const SelectedOutlineScaleEdgeLine: React.FC<{
const interaction = getOutlineSelectionInteraction(event);
const shouldUpdateSelection =
- !selected || interaction.shiftKey || interaction.toggleKey;
+ (!selected && !containsSelection) ||
+ interaction.shiftKey ||
+ interaction.toggleKey;
if (shouldUpdateSelection && target !== undefined) {
onSelect(target.selection, interaction);
}
@@ -250,6 +253,7 @@ export const SelectedOutlineScaleEdgeLine: React.FC<{
},
[
clearDragOverrides,
+ containsSelection,
getAllScaleDragTargets,
edgeInfo,
getDragOverrides,
@@ -280,6 +284,10 @@ export const SelectedOutlineScaleEdgeLine: React.FC<{
vectorEffect="non-scaling-stroke"
pointerEvents="stroke"
cursor={edgeInfo.cursor}
+ data-remotion-studio-scale-edge={edge}
+ data-remotion-studio-scale-edge-contains-selection={
+ target?.containsSelection ?? false
+ }
onPointerEnter={() => {
if (!dragging) {
onHoverChange(outline.key);
diff --git a/packages/studio/src/components/SelectedOutlineTransformOriginHandle.tsx b/packages/studio/src/components/SelectedOutlineTransformOriginHandle.tsx
index 98aa4f831b..2af47fcf30 100644
--- a/packages/studio/src/components/SelectedOutlineTransformOriginHandle.tsx
+++ b/packages/studio/src/components/SelectedOutlineTransformOriginHandle.tsx
@@ -14,11 +14,11 @@ import {
compensateTranslateForTransformOrigin,
getSelectedOutlineTransformOriginDragChanges,
getSelectedOutlineTransformOriginLockedAxis,
- parseCssRotationToRadians,
snapSelectedOutlineTransformOriginUv,
uvsEqual,
} from './selected-outline-drag';
import type {SelectedOutline} from './selected-outline-geometry';
+import {getSelectedOutlineRotationPivot} from './selected-outline-measurement';
import {
transformOriginFieldKey,
translateFieldKey,
@@ -31,6 +31,7 @@ import {
} from './selected-outline-uv';
import {callAddKeyframes} from './Timeline/call-add-keyframe';
import {saveSequenceProps} from './Timeline/save-sequence-prop';
+import {parseCssRotation} from './Timeline/timeline-rotation-utils';
import {
parseTranslate,
serializeTranslate,
@@ -53,19 +54,26 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
Internals.VisualModeSettersContext,
);
const {editorSnapping} = useContext(EditorSnappingContext);
- const target = layoutTarget?.selectedForTransformOrigin
- ? getLatestTargetByKey(layoutTarget.key)
- : undefined;
+ const target =
+ layoutTarget?.selectedForTransformOrigin ||
+ layoutTarget?.selectedForRotation
+ ? getLatestTargetByKey(layoutTarget.key)
+ : undefined;
const transformOriginDrag = target?.transformOriginDrag ?? null;
+ const transformOriginValue =
+ transformOriginDrag?.originValue ??
+ (layoutTarget?.selectedForRotation
+ ? layoutTarget.transformOriginValue
+ : null);
const crop = target?.crop;
const transformOriginPoints = outline.uncroppedPoints ?? outline.points;
const parsed = useMemo(
() =>
- transformOriginDrag === null
+ transformOriginValue === null
? null
- : parseTransformOrigin(transformOriginDrag.originValue),
- [transformOriginDrag],
+ : parseTransformOrigin(transformOriginValue),
+ [transformOriginValue],
);
const uv = useMemo(() => {
if (parsed === null || outline.dimensions === null) {
@@ -78,10 +86,23 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
height: outline.dimensions.height,
});
}, [outline.dimensions, parsed]);
- const position = useMemo(
- () => (uv === null ? null : getUvHandlePosition(transformOriginPoints, uv)),
- [transformOriginPoints, uv],
- );
+ const position = useMemo(() => {
+ if (layoutTarget?.selectedForRotation) {
+ return getSelectedOutlineRotationPivot({
+ dimensions: outline.dimensions,
+ points: transformOriginPoints,
+ transformOriginValue: layoutTarget.transformOriginValue,
+ });
+ }
+
+ return uv === null ? null : getUvHandlePosition(transformOriginPoints, uv);
+ }, [
+ layoutTarget?.selectedForRotation,
+ layoutTarget?.transformOriginValue,
+ outline.dimensions,
+ transformOriginPoints,
+ uv,
+ ]);
const onPointerDown = React.useCallback(
(event: React.PointerEvent<SVGGElement>) => {
@@ -103,9 +124,7 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
return;
}
- const rotation = parseCssRotationToRadians(
- transformOriginDrag.rotateValue,
- );
+ const rotation = parseCssRotation(transformOriginDrag.rotateValue);
if (rotation === null) {
return;
}
@@ -115,7 +134,7 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
return;
}
- const [scaleX, scaleY] = NoReactInternals.parseScaleValue(
+ const scale = NoReactInternals.parseScaleValue(
transformOriginDrag.scaleValue,
);
const startTranslate = parseTranslate(transformOriginDrag.translateValue);
@@ -174,16 +193,20 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
] as const;
const [nextTranslateX, nextTranslateY] =
compensateTranslateForTransformOrigin({
- startTranslate,
+ startTranslate: [startTranslate[0], startTranslate[1]],
deltaOrigin,
- rotate: rotation,
- scale: [scaleX, scaleY],
+ rotation,
+ scale,
});
const origin = serializeTransformOrigin({
uv: nextUv,
z: parsed.z,
});
- const translate = serializeTranslate(nextTranslateX, nextTranslateY);
+ const translate = serializeTranslate([
+ nextTranslateX,
+ nextTranslateY,
+ startTranslate[2],
+ ]);
last = {uv: nextUv, origin, translate};
setDragOverrides(
@@ -219,14 +242,15 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
);
return {
...keyframe,
- value: serializeTranslate(
+ value: serializeTranslate([
keyframeTranslate[0] +
nextTranslateX -
startTranslate[0],
keyframeTranslate[1] +
nextTranslateY -
startTranslate[1],
- ),
+ keyframeTranslate[2],
+ ]),
};
},
),
@@ -339,19 +363,15 @@ export const SelectedOutlineTransformOriginHandle: React.FC<{
],
);
- if (
- transformOriginDrag === null ||
- parsed === null ||
- uv === null ||
- position === null
- ) {
+ if (position === null) {
return null;
}
return (
<g
- pointerEvents="all"
- cursor="crosshair"
+ data-remotion-studio-transform-origin-handle
+ pointerEvents={transformOriginDrag === null ? 'none' : 'all'}
+ cursor={transformOriginDrag === null ? undefined : 'crosshair'}
onPointerDown={onPointerDown}
aria-hidden="true"
style={{
diff --git a/packages/studio/src/components/Timeline/TimelineFieldRowContent.tsx b/packages/studio/src/components/Timeline/TimelineFieldRowContent.tsx
index 0405f2eff0..b574f2e8d0 100644
--- a/packages/studio/src/components/Timeline/TimelineFieldRowContent.tsx
+++ b/packages/studio/src/components/Timeline/TimelineFieldRowContent.tsx
@@ -1,10 +1,13 @@
-import React from 'react';
+import React, {useContext} from 'react';
import type {SchemaFieldInfo} from '../../helpers/timeline-layout';
import {
+ isTimelineFieldStacked,
+ timelineCompactStackedFieldValueColumnStyle,
timelineFieldValueColumnStyle,
timelineStackedFieldContentStyle,
} from './timeline-field-row-layout';
import {TimelineFieldLabel} from './TimelineFieldLabel';
+import {Transform3DModeContext} from './Transform3DModeContext';
export const TimelineFieldRowContent: React.FC<{
readonly field: SchemaFieldInfo;
@@ -12,17 +15,30 @@ export const TimelineFieldRowContent: React.FC<{
readonly selected: boolean;
readonly children: React.ReactNode;
}> = ({field, rowDepth, selected, children}) => {
+ const transform3DMode = useContext(Transform3DModeContext);
+ const stacked = isTimelineFieldStacked({field, transform3DMode});
+ const compactStacked = stacked && field.typeName !== 'text-content';
const label = (
<TimelineFieldLabel
rowDepth={rowDepth}
selected={selected}
label={field.description ?? field.key}
- stacked={field.typeName === 'text-content'}
+ stacked={stacked}
/>
);
- const value = <div style={timelineFieldValueColumnStyle}>{children}</div>;
+ const value = (
+ <div
+ style={
+ compactStacked
+ ? timelineCompactStackedFieldValueColumnStyle
+ : timelineFieldValueColumnStyle
+ }
+ >
+ {children}
+ </div>
+ );
- if (field.typeName === 'text-content') {
+ if (stacked) {
return (
<div style={timelineStackedFieldContentStyle}>
{label}
diff --git a/packages/studio/src/components/Timeline/TimelineRotationField.tsx b/packages/studio/src/components/Timeline/TimelineRotationField.tsx
index 4f2195db9c..626090398c 100644
--- a/packages/studio/src/components/Timeline/TimelineRotationField.tsx
+++ b/packages/studio/src/components/Timeline/TimelineRotationField.tsx
@@ -1,4 +1,4 @@
-import React, {useCallback, useMemo, useState} from 'react';
+import React, {useCallback, useContext, useMemo, useState} from 'react';
import type {CanUpdateSequencePropStatusStatic} from 'remotion';
import type {
SchemaFieldInfo,
@@ -13,9 +13,27 @@ import {
} from './timeline-field-utils';
import {formatTimelineRotationFieldValue} from './timeline-rotation-field-utils';
import {
- parseCssRotationToDegrees,
+ type CssRotationEuler,
+ parseCssRotationToEuler,
serializeCssRotation,
+ serializeCssRotationFromEuler,
} from './timeline-rotation-utils';
+import {Transform3DModeContext} from './Transform3DModeContext';
+
+const containerStyle: React.CSSProperties = {
+ alignItems: 'center',
+ display: 'flex',
+ gap: 4,
+};
+
+const compactDraggerStyle: React.CSSProperties = {
+ paddingBottom: 2,
+ paddingLeft: 2,
+ paddingRight: 2,
+ paddingTop: 2,
+};
+
+const ROTATION_LABELS = ['X', 'Y', 'Z'] as const;
export const TimelineRotationField: React.FC<{
readonly field: SchemaFieldInfo;
@@ -33,15 +51,27 @@ export const TimelineRotationField: React.FC<{
onDragEnd,
}) => {
const [dragValue, setDragValue] = useState<number | null>(null);
+ const [dragRotation, setDragRotation] = useState<CssRotationEuler | null>(
+ null,
+ );
+ const transform3DMode = useContext(Transform3DModeContext);
const isCssRotation = field.fieldSchema.type === 'rotation-css';
+ const cssRotation = useMemo(
+ () =>
+ isCssRotation
+ ? parseCssRotationToEuler(String(effectiveValue ?? '0deg'))
+ : ([0, 0, 0] as const),
+ [effectiveValue, isCssRotation],
+ );
+ const show3D =
+ isCssRotation &&
+ (transform3DMode || cssRotation[0] !== 0 || cssRotation[1] !== 0);
- const degrees = useMemo(() => {
- if (isCssRotation) {
- return parseCssRotationToDegrees(String(effectiveValue ?? '0deg'));
- }
-
- return typeof effectiveValue === 'number' ? effectiveValue : 0;
- }, [effectiveValue, isCssRotation]);
+ const degrees = isCssRotation
+ ? cssRotation[2]
+ : typeof effectiveValue === 'number'
+ ? effectiveValue
+ : 0;
const configuredStep =
field.fieldSchema.type === 'rotation-css' ||
@@ -68,13 +98,20 @@ export const TimelineRotationField: React.FC<{
);
const serializeValue = useCallback(
- (value: number) => {
- return isCssRotation
+ (value: number) =>
+ isCssRotation
? serializeCssRotation(value, decimalPlaces)
- : normalizeTimelineNumber(value);
- },
+ : normalizeTimelineNumber(value),
[decimalPlaces, isCssRotation],
);
+ const serializeRotation = useCallback(
+ (rotation: CssRotationEuler) =>
+ serializeCssRotationFromEuler({
+ rotation,
+ decimalPlaces: Math.max(6, decimalPlaces),
+ }),
+ [decimalPlaces],
+ );
const onValueChange = useCallback(
(newVal: number) => {
@@ -127,7 +164,79 @@ export const TimelineRotationField: React.FC<{
[decimalPlaces, field.fieldSchema],
);
- return (
+ const onRotationValueChange = useCallback(
+ (rotationIndex: number, newValue: number) => {
+ const nextRotation = [...(dragRotation ?? cssRotation)] as [
+ number,
+ number,
+ number,
+ ];
+ nextRotation[rotationIndex] = newValue;
+ setDragRotation(nextRotation);
+ onDragValueChange(serializeRotation(nextRotation));
+ },
+ [cssRotation, dragRotation, onDragValueChange, serializeRotation],
+ );
+
+ const onRotationValueChangeEnd = useCallback(
+ (rotationIndex: number, newValue: number) => {
+ const nextRotation = [...(dragRotation ?? cssRotation)] as [
+ number,
+ number,
+ number,
+ ];
+ nextRotation[rotationIndex] = newValue;
+ const newRotation = serializeRotation(nextRotation);
+ const clearDragState = () => {
+ setDragRotation(null);
+ onDragEnd();
+ };
+
+ if (newRotation !== propStatus.codeValue) {
+ onSave(newRotation).finally(clearDragState);
+ } else {
+ clearDragState();
+ }
+ },
+ [
+ cssRotation,
+ dragRotation,
+ onDragEnd,
+ onSave,
+ propStatus.codeValue,
+ serializeRotation,
+ ],
+ );
+
+ const onRotationTextChange = useCallback(
+ (rotationIndex: number, newValue: string) => {
+ const parsed = Number(newValue);
+ if (Number.isNaN(parsed)) {
+ return;
+ }
+
+ const nextRotation = [...(dragRotation ?? cssRotation)] as [
+ number,
+ number,
+ number,
+ ];
+ nextRotation[rotationIndex] = parsed;
+ const newRotation = serializeRotation(nextRotation);
+ if (newRotation !== propStatus.codeValue) {
+ setDragRotation(nextRotation);
+ onSave(newRotation).finally(() => setDragRotation(null));
+ }
+ },
+ [
+ cssRotation,
+ dragRotation,
+ onSave,
+ propStatus.codeValue,
+ serializeRotation,
+ ],
+ );
+
+ const angleDragger = (
<InputDragger
type="number"
value={dragValue ?? degrees}
@@ -142,6 +251,41 @@ export const TimelineRotationField: React.FC<{
step={step}
formatter={formatter}
rightAlign={false}
+ aria-label={isCssRotation ? 'Rotation Z' : 'Rotation angle'}
/>
);
+
+ if (show3D) {
+ return (
+ <span style={containerStyle}>
+ {ROTATION_LABELS.map((rotationLabel, rotationIndex) => (
+ <InputDragger
+ key={rotationLabel}
+ type="number"
+ value={(dragRotation ?? cssRotation)[rotationIndex]}
+ buttonStyle={compactDraggerStyle}
+ status="ok"
+ small
+ onValueChange={(newValue) =>
+ onRotationValueChange(rotationIndex, newValue)
+ }
+ onValueChangeEnd={(newValue) =>
+ onRotationValueChangeEnd(rotationIndex, newValue)
+ }
+ onTextChange={(newValue) =>
+ onRotationTextChange(rotationIndex, newValue)
+ }
+ min={-Infinity}
+ max={Infinity}
+ step={step}
+ formatter={formatter}
+ rightAlign={false}
+ aria-label={`Rotation ${rotationLabel}`}
+ />
+ ))}
+ </span>
+ );
+ }
+
+ return angleDragger;
};
diff --git a/packages/studio/src/components/Timeline/TimelineScaleField.tsx b/packages/studio/src/components/Timeline/TimelineScaleField.tsx
index 44a94c7bd0..db131761f4 100644
--- a/packages/studio/src/components/Timeline/TimelineScaleField.tsx
+++ b/packages/studio/src/components/Timeline/TimelineScaleField.tsx
@@ -15,13 +15,18 @@ import {InputDragger} from '../NewComposition/InputDragger';
import {formatTimelineFieldValueForDisplay} from './timeline-field-display-utils';
import {normalizeTimelineNumber} from './timeline-field-utils';
import {timelineLayerIconContainer} from './TimelineLayerEye';
+import {Transform3DModeContext} from './Transform3DModeContext';
const leftDraggerStyle: React.CSSProperties = {
+ paddingBottom: 2,
paddingLeft: 0,
+ paddingTop: 2,
};
const rightDraggerStyle: React.CSSProperties = {
+ paddingBottom: 2,
paddingRight: 0,
+ paddingTop: 2,
};
const containerStyle: React.CSSProperties = {
@@ -160,13 +165,16 @@ export const TimelineScaleField: React.FC<{
}) => {
const [dragX, setDragX] = useState<number | null>(null);
const [dragY, setDragY] = useState<number | null>(null);
+ const [dragZ, setDragZ] = useState<number | null>(null);
const dragStartRef = useRef<readonly [number, number] | null>(null);
const {getScaleLockState, setScaleLockState} = useContext(ScaleLockContext);
+ const transform3DMode = useContext(Transform3DModeContext);
const [codeX, codeY, codeZ] = useMemo(
() => NoReactInternals.parseScaleValue(effectiveValue),
[effectiveValue],
);
+ const show3D = transform3DMode || codeZ !== 1;
const defaultLinked = codeX === codeY;
const linked = getScaleLockState({
@@ -206,10 +214,10 @@ export const TimelineScaleField: React.FC<{
}, [codeX, codeY, dragX, dragY]);
const serialize = useCallback(
- (x: number, y: number) => {
- return NoReactInternals.serializeScaleValue([x, y, codeZ]);
+ (x: number, y: number, z = dragZ ?? codeZ) => {
+ return NoReactInternals.serializeScaleValue([x, y, z]);
},
- [codeZ],
+ [codeZ, dragZ],
);
const onXChange = useCallback(
@@ -264,6 +272,7 @@ export const TimelineScaleField: React.FC<{
dragStartRef.current = null;
setDragX(null);
setDragY(null);
+ setDragZ(null);
onDragEnd();
};
@@ -312,6 +321,7 @@ export const TimelineScaleField: React.FC<{
dragStartRef.current = null;
setDragX(null);
setDragY(null);
+ setDragZ(null);
});
}
},
@@ -370,6 +380,7 @@ export const TimelineScaleField: React.FC<{
dragStartRef.current = null;
setDragX(null);
setDragY(null);
+ setDragZ(null);
onDragEnd();
};
@@ -418,6 +429,7 @@ export const TimelineScaleField: React.FC<{
dragStartRef.current = null;
setDragX(null);
setDragY(null);
+ setDragZ(null);
});
}
},
@@ -432,11 +444,65 @@ export const TimelineScaleField: React.FC<{
});
}, [field.key, linked, scaleLockNodePath, setScaleLockState]);
+ const onZChange = useCallback(
+ (newVal: number) => {
+ setDragZ(newVal);
+ onDragValueChange(serialize(dragX ?? codeX, dragY ?? codeY, newVal));
+ },
+ [codeX, codeY, dragX, dragY, onDragValueChange, serialize],
+ );
+
+ const onZChangeEnd = useCallback(
+ (newVal: number) => {
+ const newScale = serialize(dragX ?? codeX, dragY ?? codeY, newVal);
+ const clearDragState = () => {
+ dragStartRef.current = null;
+ setDragX(null);
+ setDragY(null);
+ setDragZ(null);
+ onDragEnd();
+ };
+
+ if (!valuesEqual(newScale, propStatus.codeValue)) {
+ onSave(newScale).finally(clearDragState);
+ } else {
+ clearDragState();
+ }
+ },
+ [
+ codeX,
+ codeY,
+ dragX,
+ dragY,
+ onDragEnd,
+ onSave,
+ propStatus.codeValue,
+ serialize,
+ ],
+ );
+
+ const onZTextChange = useCallback(
+ (newVal: string) => {
+ const parsed = Number(newVal);
+ if (Number.isNaN(parsed)) {
+ return;
+ }
+
+ const newScale = serialize(dragX ?? codeX, dragY ?? codeY, parsed);
+ if (!valuesEqual(newScale, propStatus.codeValue)) {
+ setDragZ(parsed);
+ onSave(newScale).finally(() => setDragZ(null));
+ }
+ },
+ [codeX, codeY, dragX, dragY, onSave, propStatus.codeValue, serialize],
+ );
+
return (
<span style={containerStyle}>
<InputDragger
type="number"
value={dragX ?? codeX}
+ buttonStyle={leftDraggerStyle}
style={leftDraggerStyle}
status="ok"
small
@@ -449,11 +515,13 @@ export const TimelineScaleField: React.FC<{
formatter={formatter}
rightAlign={false}
allowStepMismatch
+ aria-label="Scale X"
/>
<div style={gapStyle} />
<InputDragger
type="number"
value={dragY ?? codeY}
+ buttonStyle={rightDraggerStyle}
style={rightDraggerStyle}
status="ok"
small
@@ -466,7 +534,31 @@ export const TimelineScaleField: React.FC<{
formatter={formatter}
rightAlign={false}
allowStepMismatch
+ aria-label="Scale Y"
/>
+ {show3D ? (
+ <>
+ <div style={gapStyle} />
+ <InputDragger
+ type="number"
+ value={dragZ ?? codeZ}
+ buttonStyle={rightDraggerStyle}
+ style={rightDraggerStyle}
+ status="ok"
+ small
+ onValueChange={onZChange}
+ onValueChangeEnd={onZChangeEnd}
+ onTextChange={onZTextChange}
+ min={min}
+ max={max}
+ step={step}
+ formatter={formatter}
+ rightAlign={false}
+ allowStepMismatch
+ aria-label="Scale Z"
+ />
+ </>
+ ) : null}
<LinkToggle linked={linked} onToggle={onToggleLink} />
</span>
);
diff --git a/packages/studio/src/components/Timeline/TimelineSelection.tsx b/packages/studio/src/components/Timeline/TimelineSelection.tsx
index f49ca4a034..b184e84564 100644
--- a/packages/studio/src/components/Timeline/TimelineSelection.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSelection.tsx
@@ -56,6 +56,7 @@ import {selectOptionsSidebarInspectorPanel} from '../options-sidebar-tabs';
import {getNodeHasKeyframes, getNodeKeyframes} from './get-node-keyframes';
import {getTimelineEasingSegments} from './get-timeline-easing-segments';
import {getCurrentFrame} from './imperative-state';
+import {parseKeyframeFieldFromNodePath} from './parse-keyframe-field-from-node-path';
import {
filterTimelineExpandedTree,
getSelectedTimelineExpandedRowKeys,
@@ -1034,6 +1035,50 @@ export const TimelineSelectAllKeybindings: React.FC<{
return null;
};
+const fieldsSelectingSequenceOnEscape = new Set([
+ 'cropLeft',
+ 'cropRight',
+ 'cropTop',
+ 'cropBottom',
+ 'style.rotate',
+]);
+
+export const getTimelineSequenceSelectionForEscape = (
+ selectedItems: readonly TimelineSelection[],
+): Extract<TimelineSelection, {type: 'sequence'}> | null => {
+ if (selectedItems.length !== 1) {
+ return null;
+ }
+
+ const [selectedItem] = selectedItems;
+ let fieldKey: string | null = null;
+ if (selectedItem.type === 'sequence-prop') {
+ fieldKey = selectedItem.key;
+ } else if (
+ selectedItem.type === 'keyframe' ||
+ selectedItem.type === 'easing'
+ ) {
+ const field = parseKeyframeFieldFromNodePath(
+ selectedItem.nodePathInfo.auxiliaryKeys,
+ );
+ fieldKey = field?.type === 'sequence' ? field.fieldKey : null;
+ } else {
+ return null;
+ }
+
+ if (!fieldsSelectingSequenceOnEscape.has(fieldKey ?? '')) {
+ return null;
+ }
+
+ return {
+ type: 'sequence',
+ nodePathInfo: {
+ ...selectedItem.nodePathInfo,
+ auxiliaryKeys: [],
+ },
+ };
+};
+
const TimelineEscapeKeybindings: React.FC = () => {
const keybindings = useKeybinding();
const currentSelection = useCurrentTimelineSelectionStateAsRef();
@@ -1043,11 +1088,20 @@ const TimelineEscapeKeybindings: React.FC = () => {
event: 'keydown',
key: 'Escape',
callback: (event) => {
- const {selectedItems, clearSelection} = currentSelection.current;
+ const {selectedItems, clearSelection, selectItems} =
+ currentSelection.current;
if (selectedItems.length === 0) {
return;
}
+ const sequenceSelection =
+ getTimelineSequenceSelectionForEscape(selectedItems);
+ if (sequenceSelection) {
+ selectItems([sequenceSelection]);
+ event.preventDefault();
+ return;
+ }
+
clearSelection();
event.preventDefault();
},
diff --git a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
index 38e08beb67..add8e2e03a 100644
--- a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
@@ -35,6 +35,7 @@ import {
} from '../../helpers/use-runtime-values';
import {SetSelectedModalContext} from '../../state/modals';
import {useTimelineSequenceHover} from '../../state/timeline-sequence-hover';
+import {Transform3DModeStateContext} from '../../state/transform-3d-mode';
import {callApi} from '../call-api';
import {CompositionOrStillIcon} from '../CompositionOrStillIcon';
import {useConfirmationDialog} from '../ConfirmationDialog';
@@ -55,6 +56,7 @@ import {showNotification} from '../Notifications/NotificationCenter';
import {
canEditSelectedOutlineCrop,
cropFieldKeys,
+ rotateFieldKey,
} from '../selected-outline-types';
import {useSelectAsset} from '../use-select-asset';
import {disableSequenceInteractivity} from './disable-sequence-interactivity';
@@ -74,6 +76,7 @@ import {TimelineMediaInfo} from './TimelineMediaInfo';
import {TimelineRowChrome} from './TimelineRowChrome';
import {
getTimelineColor,
+ getTimelineSequenceSelectionKey,
isTimelineSelectionModifierEvent,
useTimelineRowContainsSelection,
useTimelineRowSelection,
@@ -924,6 +927,8 @@ const TimelineSequenceItemInner: React.FC<{
});
},
});
+ const canRotate = nodePathInfo !== null;
+ const {setManuallyEnabled} = useContext(Transform3DModeStateContext);
const onAddEffect = useCallback(() => {
if (
@@ -969,6 +974,27 @@ const TimelineSequenceItemInner: React.FC<{
);
}, [canCrop, nodePathInfo, selectItem]);
+ const onRotate = useCallback(() => {
+ if (!canRotate || !nodePathInfo) {
+ return;
+ }
+
+ setManuallyEnabled(getTimelineSequenceSelectionKey(nodePathInfo), true);
+ selectItem(
+ {
+ type: 'sequence-prop',
+ nodePathInfo: {
+ ...nodePathInfo,
+ auxiliaryKeys: ['controls', rotateFieldKey],
+ },
+ key: rotateFieldKey,
+ },
+ undefined,
+ undefined,
+ {reveal: true},
+ );
+ }, [canRotate, nodePathInfo, selectItem, setManuallyEnabled]);
+
const getContextMenuItems = useCallback(() => {
if (selectable) {
onSelect({shiftKey: false, toggleKey: false});
@@ -1048,9 +1074,31 @@ const TimelineSequenceItemInner: React.FC<{
subMenu: null,
value: 'crop',
},
+ ]
+ : []),
+ ...(canRotate
+ ? [
+ {
+ type: 'item' as const,
+ id: 'rotate',
+ keyHint: null,
+ label: isProgrammaticallyDuplicated
+ ? 'Rotate all'
+ : 'Rotate',
+ leftItem: null,
+ disabled: false,
+ onClick: onRotate,
+ quickSwitcherLabel: null,
+ subMenu: null,
+ value: 'rotate',
+ },
+ ]
+ : []),
+ ...(canCrop || canRotate
+ ? [
{
type: 'divider' as const,
- id: 'crop-divider',
+ id: 'transform-controls-divider',
},
]
: []),
@@ -1075,6 +1123,7 @@ const TimelineSequenceItemInner: React.FC<{
}, [
canAddEffect,
canCrop,
+ canRotate,
canConfigureApps,
canOpenInEditor,
canRenameThisSequence,
@@ -1089,6 +1138,7 @@ const TimelineSequenceItemInner: React.FC<{
nodePathInfo?.supportsEffects,
onAddEffect,
onCrop,
+ onRotate,
onDeleteSequenceFromSource,
onDisableSequenceInteractivity,
onDuplicateSequenceFromSource,
diff --git a/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx b/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
index dc3443f7e3..f9584361ce 100644
--- a/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
@@ -23,6 +23,7 @@ import type {ComboboxValue} from '../NewComposition/ComboBox';
import {callAddSequenceKeyframe} from './call-add-keyframe';
import {getSequencePropResetChanges} from './get-sequence-prop-reset-changes';
import {saveSequenceProps} from './save-sequence-prop';
+import {isTimelineFieldStacked} from './timeline-field-row-layout';
import {TimelineExpandArrowSpacer} from './TimelineExpandArrowButton';
import {TimelineFieldRowContent} from './TimelineFieldRowContent';
import {
@@ -38,6 +39,7 @@ import {
TimelineNonEditableStatus,
} from './TimelineSchemaField';
import {useTimelineRowSelection} from './TimelineSelection';
+import {Transform3DModeContext} from './Transform3DModeContext';
const fieldRowBase: React.CSSProperties = {};
@@ -409,6 +411,7 @@ export const TimelineSequencePropItem: React.FC<{
const {setPropStatuses} = useContext(Internals.VisualModeSettersContext);
const {previewServerState} = useContext(StudioServerConnectionCtx);
const selection = useTimelineRowSelection(nodePathInfo);
+ const transform3DMode = useContext(Transform3DModeContext);
const propStatusesForOverride = Internals.getPropStatusesCtx(
visualModePropStatuses,
nodePath,
@@ -448,10 +451,10 @@ export const TimelineSequencePropItem: React.FC<{
) : null;
const style = useMemo((): React.CSSProperties => {
- return field.typeName === 'text-content'
+ return isTimelineFieldStacked({field, transform3DMode})
? fieldRowBase
: {...fieldRowBase, height: field.rowHeight};
- }, [field.rowHeight, field.typeName]);
+ }, [field, transform3DMode]);
const canResetToDefault = useMemo(() => {
if (!propStatus || propStatus.status === 'computed') {
diff --git a/packages/studio/src/components/Timeline/TimelineTransformOriginField.tsx b/packages/studio/src/components/Timeline/TimelineTransformOriginField.tsx
index 9117c5a4ad..c3c7d47d7d 100644
--- a/packages/studio/src/components/Timeline/TimelineTransformOriginField.tsx
+++ b/packages/studio/src/components/Timeline/TimelineTransformOriginField.tsx
@@ -1,4 +1,4 @@
-import React, {useCallback, useMemo, useState} from 'react';
+import React, {useCallback, useContext, useMemo, useState} from 'react';
import type {CanUpdateSequencePropStatusStatic} from 'remotion';
import type {
SchemaFieldInfo,
@@ -7,21 +7,30 @@ import type {
} from '../../helpers/timeline-layout';
import {InputDragger} from '../NewComposition/InputDragger';
import {formatTimelineFieldValueForDisplay} from './timeline-field-display-utils';
-import {getTimelineDisplayDecimalPlaces} from './timeline-field-utils';
+import {
+ getTimelineDisplayDecimalPlaces,
+ normalizeTimelineNumber,
+} from './timeline-field-utils';
import {UnsupportedStatus} from './TimelineSchemaField';
import {
parseTransformOrigin,
+ parseTransformOriginZ,
parsedTransformOriginToPercent,
serializeTransformOrigin,
transformOriginPercentToUv,
} from './transform-origin-utils';
+import {Transform3DModeContext} from './Transform3DModeContext';
const leftDraggerStyle: React.CSSProperties = {
+ paddingBottom: 2,
paddingLeft: 0,
+ paddingTop: 2,
};
const rightDraggerStyle: React.CSSProperties = {
+ paddingBottom: 2,
paddingRight: 0,
+ paddingTop: 2,
};
const containerStyle: React.CSSProperties = {
@@ -46,6 +55,8 @@ export const TimelineTransformOriginField: React.FC<{
}) => {
const [dragX, setDragX] = useState<number | null>(null);
const [dragY, setDragY] = useState<number | null>(null);
+ const [dragZ, setDragZ] = useState<number | null>(null);
+ const transform3DMode = useContext(Transform3DModeContext);
const parsed = useMemo(
() => parseTransformOrigin(effectiveValue),
@@ -55,6 +66,14 @@ export const TimelineTransformOriginField: React.FC<{
() => (parsed === null ? null : parsedTransformOriginToPercent(parsed)),
[parsed],
);
+ const parsedZ = useMemo(
+ () =>
+ parsed?.z === null || parsed?.z === undefined
+ ? null
+ : parseTransformOriginZ(parsed.z),
+ [parsed?.z],
+ );
+ const show3D = transform3DMode || (parsedZ !== null && parsedZ.value !== 0);
const configuredStep =
field.fieldSchema.type === 'transform-origin'
@@ -82,15 +101,21 @@ export const TimelineTransformOriginField: React.FC<{
);
const serialize = useCallback(
- (x: number, y: number) => {
+ (x: number, y: number, z = parsed?.z ?? null) => {
return serializeTransformOrigin({
uv: transformOriginPercentToUv([x, y]),
- z: parsed?.z ?? null,
+ z,
decimalPlaces,
});
},
[decimalPlaces, parsed?.z],
);
+ const serializeZ = useCallback(
+ (value: number) => {
+ return `${normalizeTimelineNumber(value)}${parsedZ?.unit ?? 'px'}`;
+ },
+ [parsedZ?.unit],
+ );
const onXChange = useCallback(
(newVal: number) => {
@@ -202,6 +227,83 @@ export const TimelineTransformOriginField: React.FC<{
[dragX, onSave, percent, propStatus.codeValue, serialize],
);
+ const onZChange = useCallback(
+ (newVal: number) => {
+ if (percent === null) {
+ return;
+ }
+
+ setDragZ(newVal);
+ onDragValueChange(
+ serialize(dragX ?? percent[0], dragY ?? percent[1], serializeZ(newVal)),
+ );
+ },
+ [dragX, dragY, onDragValueChange, percent, serialize, serializeZ],
+ );
+
+ const onZChangeEnd = useCallback(
+ (newVal: number) => {
+ if (percent === null) {
+ return;
+ }
+
+ const value = serialize(
+ dragX ?? percent[0],
+ dragY ?? percent[1],
+ serializeZ(newVal),
+ );
+ if (value !== propStatus.codeValue) {
+ onSave(value).finally(() => {
+ setDragZ(null);
+ onDragEnd();
+ });
+ } else {
+ setDragZ(null);
+ onDragEnd();
+ }
+ },
+ [
+ dragX,
+ dragY,
+ onDragEnd,
+ onSave,
+ percent,
+ propStatus.codeValue,
+ serialize,
+ serializeZ,
+ ],
+ );
+
+ const onZTextChange = useCallback(
+ (newVal: string) => {
+ if (percent === null) {
+ return;
+ }
+
+ const parsedValue = Number(newVal);
+ if (!Number.isNaN(parsedValue)) {
+ const value = serialize(
+ dragX ?? percent[0],
+ dragY ?? percent[1],
+ serializeZ(parsedValue),
+ );
+ if (value !== propStatus.codeValue) {
+ setDragZ(parsedValue);
+ onSave(value).finally(() => setDragZ(null));
+ }
+ }
+ },
+ [
+ dragX,
+ dragY,
+ onSave,
+ percent,
+ propStatus.codeValue,
+ serialize,
+ serializeZ,
+ ],
+ );
+
if (percent === null) {
return <UnsupportedStatus label="unsupported origin" />;
}
@@ -211,6 +313,7 @@ export const TimelineTransformOriginField: React.FC<{
<InputDragger
type="number"
value={dragX ?? percent[0]}
+ buttonStyle={leftDraggerStyle}
style={leftDraggerStyle}
status="ok"
small
@@ -224,11 +327,13 @@ export const TimelineTransformOriginField: React.FC<{
rightAlign={false}
snapToStep={false}
dragDecimalPlaces={decimalPlaces}
+ aria-label="Transform origin X"
/>
<div style={{marginLeft: -6, marginRight: -6}} />
<InputDragger
type="number"
value={dragY ?? percent[1]}
+ buttonStyle={rightDraggerStyle}
style={rightDraggerStyle}
status="ok"
small
@@ -242,7 +347,32 @@ export const TimelineTransformOriginField: React.FC<{
rightAlign={false}
snapToStep={false}
dragDecimalPlaces={decimalPlaces}
+ aria-label="Transform origin Y"
/>
+ {show3D ? (
+ <>
+ <div style={{marginLeft: -6, marginRight: -6}} />
+ <InputDragger
+ type="number"
+ value={dragZ ?? parsedZ?.value ?? 0}
+ buttonStyle={rightDraggerStyle}
+ style={rightDraggerStyle}
+ status="ok"
+ small
+ onValueChange={onZChange}
+ onValueChangeEnd={onZChangeEnd}
+ onTextChange={onZTextChange}
+ min={-Infinity}
+ max={Infinity}
+ step={step}
+ formatter={(value) => `${value}${parsedZ?.unit ?? 'px'}`}
+ rightAlign={false}
+ snapToStep={false}
+ dragDecimalPlaces={decimalPlaces}
+ aria-label="Transform origin Z"
+ />
+ </>
+ ) : null}
</span>
);
};
diff --git a/packages/studio/src/components/Timeline/TimelineTranslateField.tsx b/packages/studio/src/components/Timeline/TimelineTranslateField.tsx
index bb9fba9602..7383a10e48 100644
--- a/packages/studio/src/components/Timeline/TimelineTranslateField.tsx
+++ b/packages/studio/src/components/Timeline/TimelineTranslateField.tsx
@@ -1,4 +1,4 @@
-import React, {useCallback, useMemo, useState} from 'react';
+import React, {useCallback, useContext, useMemo, useState} from 'react';
import type {CanUpdateSequencePropStatusStatic} from 'remotion';
import type {
SchemaFieldInfo,
@@ -9,13 +9,18 @@ import {InputDragger} from '../NewComposition/InputDragger';
import {formatTimelineFieldValueForDisplay} from './timeline-field-display-utils';
import {getTimelineDisplayDecimalPlaces} from './timeline-field-utils';
import {parseTranslate, serializeTranslate} from './timeline-translate-utils';
+import {Transform3DModeContext} from './Transform3DModeContext';
const leftDraggerStyle: React.CSSProperties = {
+ paddingBottom: 2,
paddingLeft: 0,
+ paddingTop: 2,
};
const rightDraggerStyle: React.CSSProperties = {
+ paddingBottom: 2,
paddingRight: 0,
+ paddingTop: 2,
};
const containerStyle: React.CSSProperties = {
@@ -42,11 +47,14 @@ export const TimelineTranslateField: React.FC<{
}) => {
const [dragX, setDragX] = useState<number | null>(null);
const [dragY, setDragY] = useState<number | null>(null);
+ const [dragZ, setDragZ] = useState<number | null>(null);
+ const transform3DMode = useContext(Transform3DModeContext);
- const [codeX, codeY] = useMemo(
+ const [codeX, codeY, codeZ] = useMemo(
() => parseTranslate(String(effectiveValue ?? '0px 0px')),
[effectiveValue],
);
+ const show3D = transform3DMode || (codeZ !== null && codeZ !== 0);
const configuredStep =
field.fieldSchema.type === 'translate' ? field.fieldSchema.step : undefined;
@@ -70,21 +78,27 @@ export const TimelineTranslateField: React.FC<{
},
[field.fieldSchema],
);
+ const serialize = useCallback(
+ (x: number, y: number, z = dragZ ?? codeZ) => {
+ return serializeTranslate([x, y, z], decimalPlaces);
+ },
+ [codeZ, decimalPlaces, dragZ],
+ );
// --- X callbacks ---
const onXChange = useCallback(
(newVal: number) => {
setDragX(newVal);
const currentY = dragY ?? codeY;
- onDragValueChange(serializeTranslate(newVal, currentY, decimalPlaces));
+ onDragValueChange(serialize(newVal, currentY));
},
- [onDragValueChange, dragY, codeY, decimalPlaces],
+ [codeY, dragY, onDragValueChange, serialize],
);
const onXChangeEnd = useCallback(
(newVal: number) => {
const currentY = dragY ?? codeY;
- const newStr = serializeTranslate(newVal, currentY, decimalPlaces);
+ const newStr = serialize(newVal, currentY);
if (newStr !== propStatus.codeValue) {
onSave(newStr).finally(() => {
setDragX(null);
@@ -95,7 +109,7 @@ export const TimelineTranslateField: React.FC<{
onDragEnd();
}
},
- [dragY, codeY, decimalPlaces, propStatus, onSave, onDragEnd],
+ [codeY, dragY, onDragEnd, onSave, propStatus, serialize],
);
const onXTextChange = useCallback(
@@ -103,7 +117,7 @@ export const TimelineTranslateField: React.FC<{
const parsed = Number(newVal);
if (!Number.isNaN(parsed)) {
const currentY = dragY ?? codeY;
- const newStr = serializeTranslate(parsed, currentY, decimalPlaces);
+ const newStr = serialize(parsed, currentY);
if (newStr !== propStatus.codeValue) {
setDragX(parsed);
onSave(newStr).finally(() => {
@@ -112,7 +126,7 @@ export const TimelineTranslateField: React.FC<{
}
}
},
- [propStatus, dragY, codeY, decimalPlaces, onSave],
+ [codeY, dragY, onSave, propStatus, serialize],
);
// --- Y callbacks ---
@@ -120,15 +134,15 @@ export const TimelineTranslateField: React.FC<{
(newVal: number) => {
setDragY(newVal);
const currentX = dragX ?? codeX;
- onDragValueChange(serializeTranslate(currentX, newVal, decimalPlaces));
+ onDragValueChange(serialize(currentX, newVal));
},
- [onDragValueChange, dragX, codeX, decimalPlaces],
+ [codeX, dragX, onDragValueChange, serialize],
);
const onYChangeEnd = useCallback(
(newVal: number) => {
const currentX = dragX ?? codeX;
- const newStr = serializeTranslate(currentX, newVal, decimalPlaces);
+ const newStr = serialize(currentX, newVal);
if (newStr !== propStatus.codeValue) {
onSave(newStr).finally(() => {
setDragY(null);
@@ -139,7 +153,7 @@ export const TimelineTranslateField: React.FC<{
onDragEnd();
}
},
- [dragX, codeX, decimalPlaces, propStatus, onSave, onDragEnd],
+ [codeX, dragX, onDragEnd, onSave, propStatus, serialize],
);
const onYTextChange = useCallback(
@@ -147,7 +161,7 @@ export const TimelineTranslateField: React.FC<{
const parsed = Number(newVal);
if (!Number.isNaN(parsed)) {
const currentX = dragX ?? codeX;
- const newStr = serializeTranslate(currentX, parsed, decimalPlaces);
+ const newStr = serialize(currentX, parsed);
if (newStr !== propStatus.codeValue) {
setDragY(parsed);
onSave(newStr).finally(() => {
@@ -156,7 +170,45 @@ export const TimelineTranslateField: React.FC<{
}
}
},
- [propStatus, onSave, dragX, codeX, decimalPlaces],
+ [codeX, dragX, onSave, propStatus, serialize],
+ );
+
+ const onZChange = useCallback(
+ (newVal: number) => {
+ setDragZ(newVal);
+ onDragValueChange(serialize(dragX ?? codeX, dragY ?? codeY, newVal));
+ },
+ [codeX, codeY, dragX, dragY, onDragValueChange, serialize],
+ );
+
+ const onZChangeEnd = useCallback(
+ (newVal: number) => {
+ const newStr = serialize(dragX ?? codeX, dragY ?? codeY, newVal);
+ if (newStr !== propStatus.codeValue) {
+ onSave(newStr).finally(() => {
+ setDragZ(null);
+ onDragEnd();
+ });
+ } else {
+ setDragZ(null);
+ onDragEnd();
+ }
+ },
+ [codeX, codeY, dragX, dragY, onDragEnd, onSave, propStatus, serialize],
+ );
+
+ const onZTextChange = useCallback(
+ (newVal: string) => {
+ const parsed = Number(newVal);
+ if (!Number.isNaN(parsed)) {
+ const newStr = serialize(dragX ?? codeX, dragY ?? codeY, parsed);
+ if (newStr !== propStatus.codeValue) {
+ setDragZ(parsed);
+ onSave(newStr).finally(() => setDragZ(null));
+ }
+ }
+ },
+ [codeX, codeY, dragX, dragY, onSave, propStatus, serialize],
);
return (
@@ -164,6 +216,7 @@ export const TimelineTranslateField: React.FC<{
<InputDragger
type="number"
value={dragX ?? codeX}
+ buttonStyle={leftDraggerStyle}
style={leftDraggerStyle}
status="ok"
small
@@ -178,11 +231,13 @@ export const TimelineTranslateField: React.FC<{
snapToStep={false}
dragDecimalPlaces={decimalPlaces}
dragSensitivity={translateDragSensitivity}
+ aria-label="Offset X"
/>
<div style={{marginLeft: -6, marginRight: -6}} />
<InputDragger
type="number"
value={dragY ?? codeY}
+ buttonStyle={rightDraggerStyle}
style={rightDraggerStyle}
status="ok"
small
@@ -197,7 +252,33 @@ export const TimelineTranslateField: React.FC<{
snapToStep={false}
dragDecimalPlaces={decimalPlaces}
dragSensitivity={translateDragSensitivity}
+ aria-label="Offset Y"
/>
+ {show3D ? (
+ <>
+ <div style={{marginLeft: -6, marginRight: -6}} />
+ <InputDragger
+ type="number"
+ value={dragZ ?? codeZ ?? 0}
+ buttonStyle={rightDraggerStyle}
+ style={rightDraggerStyle}
+ status="ok"
+ small
+ onValueChange={onZChange}
+ onValueChangeEnd={onZChangeEnd}
+ onTextChange={onZTextChange}
+ min={-Infinity}
+ max={Infinity}
+ step={step}
+ formatter={formatter}
+ rightAlign={false}
+ snapToStep={false}
+ dragDecimalPlaces={decimalPlaces}
+ dragSensitivity={translateDragSensitivity}
+ aria-label="Offset Z"
+ />
+ </>
+ ) : null}
</span>
);
};
diff --git a/packages/studio/src/components/Timeline/Transform3DModeContext.ts b/packages/studio/src/components/Timeline/Transform3DModeContext.ts
new file mode 100644
index 0000000000..74dc331325
--- /dev/null
+++ b/packages/studio/src/components/Timeline/Transform3DModeContext.ts
@@ -0,0 +1,3 @@
+import {createContext} from 'react';
+
+export const Transform3DModeContext = createContext(false);
diff --git a/packages/studio/src/components/Timeline/timeline-field-display-utils.ts b/packages/studio/src/components/Timeline/timeline-field-display-utils.ts
index 659d083ff2..284c5ea02a 100644
--- a/packages/studio/src/components/Timeline/timeline-field-display-utils.ts
+++ b/packages/studio/src/components/Timeline/timeline-field-display-utils.ts
@@ -229,8 +229,8 @@ const formatTranslateTimelineFieldValueForDisplay = ({
return formatTranslateCoordinateForDisplay(numericValue, decimalPlaces);
}
- const [x, y] = parseTranslate(String(value ?? '0px 0px'));
- return serializeTranslate(x, y, decimalPlaces);
+ const translate = parseTranslate(String(value ?? '0px 0px'));
+ return serializeTranslate(translate, decimalPlaces);
};
const formatTransformOriginAxisValueForDisplay = ({
diff --git a/packages/studio/src/components/Timeline/timeline-field-row-layout.ts b/packages/studio/src/components/Timeline/timeline-field-row-layout.ts
index 8fdc1035b4..8267a5e3c1 100644
--- a/packages/studio/src/components/Timeline/timeline-field-row-layout.ts
+++ b/packages/studio/src/components/Timeline/timeline-field-row-layout.ts
@@ -1,7 +1,27 @@
import type React from 'react';
-import {EXPANDED_SECTION_PADDING_RIGHT} from '../../helpers/timeline-layout';
+import {
+ EXPANDED_SECTION_PADDING_RIGHT,
+ type SchemaFieldInfo,
+} from '../../helpers/timeline-layout';
import {getTimelineFieldLabelFlexBasis} from './timeline-row-layout';
+export const isTimelineFieldStacked = ({
+ field,
+ transform3DMode,
+}: {
+ readonly field: SchemaFieldInfo;
+ readonly transform3DMode: boolean;
+}) => {
+ return (
+ field.typeName === 'text-content' ||
+ (transform3DMode &&
+ (field.typeName === 'translate' ||
+ field.typeName === 'rotation-css' ||
+ field.typeName === 'scale' ||
+ field.typeName === 'transform-origin'))
+ );
+};
+
export const getTimelineFieldLabelRowStyle = (
depth: number,
basePadding?: number,
@@ -25,6 +45,14 @@ export const timelineFieldValueColumnStyle: React.CSSProperties = {
paddingRight: EXPANDED_SECTION_PADDING_RIGHT,
};
+export const timelineCompactStackedFieldValueColumnStyle: React.CSSProperties =
+ {
+ ...timelineFieldValueColumnStyle,
+ marginBottom: -2,
+ position: 'relative',
+ top: -2,
+ };
+
export const timelineStackedFieldContentStyle: React.CSSProperties = {
alignSelf: 'stretch',
display: 'flex',
diff --git a/packages/studio/src/components/Timeline/timeline-rotation-utils.ts b/packages/studio/src/components/Timeline/timeline-rotation-utils.ts
index 62f9ad7330..409663fb3c 100644
--- a/packages/studio/src/components/Timeline/timeline-rotation-utils.ts
+++ b/packages/studio/src/components/Timeline/timeline-rotation-utils.ts
@@ -9,10 +9,71 @@ const unitToDegrees: Record<string, number> = {
grad: 360 / 400,
};
+export type ParsedCssRotation = {
+ readonly axis: readonly [number, number, number];
+ readonly degrees: number;
+};
+
+export const parseCssRotation = (value: string): ParsedCssRotation | null => {
+ const trimmed = value.trim();
+ const bareAngle = trimmed.match(unitPattern);
+ if (bareAngle) {
+ return {
+ axis: [0, 0, 1],
+ degrees: normalizeTimelineNumber(
+ Number(bareAngle[1]) * unitToDegrees[bareAngle[2]],
+ ),
+ };
+ }
+
+ const keywordAxis = /^(x|y|z)\s+(.+)$/i.exec(trimmed);
+ if (keywordAxis) {
+ const keywordAngle = keywordAxis[2].match(unitPattern);
+ if (!keywordAngle) {
+ return null;
+ }
+
+ const keywordAxisName = keywordAxis[1].toLowerCase();
+ return {
+ axis:
+ keywordAxisName === 'x'
+ ? [1, 0, 0]
+ : keywordAxisName === 'y'
+ ? [0, 1, 0]
+ : [0, 0, 1],
+ degrees: normalizeTimelineNumber(
+ Number(keywordAngle[1]) * unitToDegrees[keywordAngle[2]],
+ ),
+ };
+ }
+
+ const vectorAxis = /^(\S+)\s+(\S+)\s+(\S+)\s+(.+)$/.exec(trimmed);
+ if (!vectorAxis) {
+ return null;
+ }
+
+ const vectorAxisComponents = [
+ Number(vectorAxis[1]),
+ Number(vectorAxis[2]),
+ Number(vectorAxis[3]),
+ ] as const;
+ const vectorAngle = vectorAxis[4].match(unitPattern);
+ if (!vectorAxisComponents.every(Number.isFinite) || !vectorAngle) {
+ return null;
+ }
+
+ return {
+ axis: vectorAxisComponents,
+ degrees: normalizeTimelineNumber(
+ Number(vectorAngle[1]) * unitToDegrees[vectorAngle[2]],
+ ),
+ };
+};
+
export const parseCssRotationToDegrees = (value: string): number => {
- const match = value.trim().match(unitPattern);
- if (match) {
- return normalizeTimelineNumber(Number(match[1]) * unitToDegrees[match[2]]);
+ const parsed = parseCssRotation(value);
+ if (parsed) {
+ return parsed.degrees;
}
if (typeof DOMMatrix === 'undefined') {
@@ -27,6 +88,142 @@ export const parseCssRotationToDegrees = (value: string): number => {
}
};
+export type CssRotationEuler = readonly [number, number, number];
+
+export const parseCssRotationToEuler = (value: string): CssRotationEuler => {
+ const parsed = parseCssRotation(value);
+ if (parsed === null) {
+ return [0, 0, parseCssRotationToDegrees(value)];
+ }
+
+ const [axisX, axisY, axisZ] = parsed.axis;
+ if (parsed.degrees === 0) {
+ return [0, 0, 0];
+ }
+
+ if (axisY === 0 && axisZ === 0 && axisX !== 0) {
+ return [Math.sign(axisX) * parsed.degrees, 0, 0];
+ }
+
+ if (axisX === 0 && axisZ === 0 && axisY !== 0) {
+ return [0, Math.sign(axisY) * parsed.degrees, 0];
+ }
+
+ if (axisX === 0 && axisY === 0 && axisZ !== 0) {
+ return [0, 0, Math.sign(axisZ) * parsed.degrees];
+ }
+
+ const axisLength = Math.hypot(axisX, axisY, axisZ);
+ if (axisLength === 0) {
+ return [0, 0, 0];
+ }
+
+ const halfAngle = (parsed.degrees * Math.PI) / 360;
+ const sinHalfAngle = Math.sin(halfAngle);
+ const quaternionX = (axisX / axisLength) * sinHalfAngle;
+ const quaternionY = (axisY / axisLength) * sinHalfAngle;
+ const quaternionZ = (axisZ / axisLength) * sinHalfAngle;
+ const quaternionW = Math.cos(halfAngle);
+ // Decompose the rotation using the same X β†’ Y β†’ Z order used when serializing.
+ const matrix11 =
+ 1 - 2 * (quaternionY * quaternionY + quaternionZ * quaternionZ);
+ const matrix12 = 2 * (quaternionX * quaternionY - quaternionZ * quaternionW);
+ const matrix13 = 2 * (quaternionX * quaternionZ + quaternionY * quaternionW);
+ const matrix22 =
+ 1 - 2 * (quaternionX * quaternionX + quaternionZ * quaternionZ);
+ const matrix23 = 2 * (quaternionY * quaternionZ - quaternionX * quaternionW);
+ const matrix32 = 2 * (quaternionY * quaternionZ + quaternionX * quaternionW);
+ const matrix33 =
+ 1 - 2 * (quaternionX * quaternionX + quaternionY * quaternionY);
+ const clampedMatrix13 = Math.max(-1, Math.min(1, matrix13));
+ const rotationY = Math.asin(clampedMatrix13);
+ const rotationX =
+ Math.abs(clampedMatrix13) < 0.9999999
+ ? Math.atan2(-matrix23, matrix33)
+ : Math.atan2(matrix32, matrix22);
+ const rotationZ =
+ Math.abs(clampedMatrix13) < 0.9999999 ? Math.atan2(-matrix12, matrix11) : 0;
+
+ return [rotationX, rotationY, rotationZ].map((rotation) =>
+ normalizeTimelineNumber(rotation * (180 / Math.PI)),
+ ) as [number, number, number];
+};
+
+export const serializeCssRotation3d = ({
+ axis,
+ degrees,
+ decimalPlaces = 6,
+}: {
+ readonly axis: readonly [number, number, number];
+ readonly degrees: number;
+ readonly decimalPlaces?: number;
+}): string => {
+ const factor = 10 ** decimalPlaces;
+ const values = [...axis, degrees].map((value) => {
+ const rounded =
+ Math.round(normalizeTimelineNumber(value) * factor) / factor;
+ return Object.is(rounded, -0) ? 0 : rounded;
+ });
+
+ return `${values[0]} ${values[1]} ${values[2]} ${values[3]}deg`;
+};
+
+export const serializeCssRotationFromEuler = ({
+ rotation,
+ decimalPlaces = 6,
+}: {
+ readonly rotation: CssRotationEuler;
+ readonly decimalPlaces?: number;
+}): string => {
+ const [rotationX, rotationY, rotationZ] = rotation.map((value) =>
+ normalizeTimelineNumber(value),
+ ) as [number, number, number];
+
+ if (rotationY === 0 && rotationZ === 0) {
+ return rotationX === 0
+ ? serializeCssRotation(0, decimalPlaces)
+ : `x ${serializeCssRotation(rotationX, decimalPlaces)}`;
+ }
+
+ if (rotationX === 0 && rotationZ === 0) {
+ return `y ${serializeCssRotation(rotationY, decimalPlaces)}`;
+ }
+
+ if (rotationX === 0 && rotationY === 0) {
+ return serializeCssRotation(rotationZ, decimalPlaces);
+ }
+
+ const halfRotationX = (rotationX * Math.PI) / 360;
+ const halfRotationY = (rotationY * Math.PI) / 360;
+ const halfRotationZ = (rotationZ * Math.PI) / 360;
+ const sinX = Math.sin(halfRotationX);
+ const cosX = Math.cos(halfRotationX);
+ const sinY = Math.sin(halfRotationY);
+ const cosY = Math.cos(halfRotationY);
+ const sinZ = Math.sin(halfRotationZ);
+ const cosZ = Math.cos(halfRotationZ);
+ // Compose the three editable angles into the axis-angle form CSS rotate accepts.
+ const quaternionX = sinX * cosY * cosZ + cosX * sinY * sinZ;
+ const quaternionY = cosX * sinY * cosZ - sinX * cosY * sinZ;
+ const quaternionZ = cosX * cosY * sinZ + sinX * sinY * cosZ;
+ const quaternionW = cosX * cosY * cosZ - sinX * sinY * sinZ;
+ const angle = 2 * Math.acos(Math.max(-1, Math.min(1, quaternionW)));
+ const sinHalfAngle = Math.sqrt(Math.max(0, 1 - quaternionW * quaternionW));
+ if (sinHalfAngle < 0.0000001) {
+ return serializeCssRotation(0, decimalPlaces);
+ }
+
+ return serializeCssRotation3d({
+ axis: [
+ quaternionX / sinHalfAngle,
+ quaternionY / sinHalfAngle,
+ quaternionZ / sinHalfAngle,
+ ],
+ degrees: angle * (180 / Math.PI),
+ decimalPlaces,
+ });
+};
+
export const serializeCssRotation = (
value: number,
decimalPlaces = 6,
diff --git a/packages/studio/src/components/Timeline/timeline-translate-utils.ts b/packages/studio/src/components/Timeline/timeline-translate-utils.ts
index 01270325ce..abfffef26e 100644
--- a/packages/studio/src/components/Timeline/timeline-translate-utils.ts
+++ b/packages/studio/src/components/Timeline/timeline-translate-utils.ts
@@ -3,18 +3,22 @@ import {
roundToDecimalPlaces,
} from './timeline-field-utils';
-const PIXEL_PATTERN = /^(-?\d+(?:\.\d+)?)px(?:\s+(-?\d+(?:\.\d+)?)px)?$/;
+const PIXEL_PATTERN =
+ /^(-?\d+(?:\.\d+)?)px(?:\s+(-?\d+(?:\.\d+)?)px)?(?:\s+(-?\d+(?:\.\d+)?)px)?$/;
const translateDecimalPlaces = 1;
-export const parseTranslate = (value: string): [number, number] => {
+export type ParsedTranslate = readonly [number, number, number | null];
+
+export const parseTranslate = (value: string): ParsedTranslate => {
const m = value.match(PIXEL_PATTERN);
if (!m) {
- return [0, 0];
+ return [0, 0, null];
}
return [
normalizeTimelineNumber(Number(m[1])),
m[2] !== undefined ? normalizeTimelineNumber(Number(m[2])) : 0,
+ m[3] !== undefined ? normalizeTimelineNumber(Number(m[3])) : null,
];
};
@@ -28,12 +32,11 @@ const formatTranslateCoordinate = (
};
export const serializeTranslate = (
- x: number,
- y: number,
+ [x, y, z]: ParsedTranslate,
decimalPlaces = translateDecimalPlaces,
): string => {
- return `${formatTranslateCoordinate(x, decimalPlaces)}px ${formatTranslateCoordinate(
- y,
- decimalPlaces,
- )}px`;
+ const xy = `${formatTranslateCoordinate(x, decimalPlaces)}px ${formatTranslateCoordinate(y, decimalPlaces)}px`;
+ return z === null
+ ? xy
+ : `${xy} ${formatTranslateCoordinate(z, decimalPlaces)}px`;
};
diff --git a/packages/studio/src/components/Timeline/transform-3d-mode.ts b/packages/studio/src/components/Timeline/transform-3d-mode.ts
new file mode 100644
index 0000000000..7a9c455530
--- /dev/null
+++ b/packages/studio/src/components/Timeline/transform-3d-mode.ts
@@ -0,0 +1,60 @@
+import type {CanUpdateSequencePropStatus} from 'remotion';
+import {NoReactInternals} from 'remotion/no-react';
+import {parseCssRotationToEuler} from './timeline-rotation-utils';
+import {parseTranslate} from './timeline-translate-utils';
+import {
+ parseTransformOrigin,
+ parseTransformOriginZ,
+} from './transform-origin-utils';
+
+const has3DTransformValue = ({
+ fieldKey,
+ value,
+}: {
+ readonly fieldKey: string;
+ readonly value: unknown;
+}): boolean => {
+ if (fieldKey === 'style.scale') {
+ return NoReactInternals.parseScaleValue(value)[2] !== 1;
+ }
+
+ if (fieldKey === 'style.rotate') {
+ const rotation = parseCssRotationToEuler(String(value ?? '0deg'));
+ return rotation[0] !== 0 || rotation[1] !== 0;
+ }
+
+ if (fieldKey === 'style.translate') {
+ const z = parseTranslate(String(value ?? '0px 0px'))[2];
+ return z !== null && z !== 0;
+ }
+
+ if (fieldKey === 'style.transformOrigin') {
+ const parsed = parseTransformOrigin(value);
+ const z = parsed?.z ? parseTransformOriginZ(parsed.z) : null;
+ return z !== null && z.value !== 0;
+ }
+
+ return false;
+};
+
+export const propStatusHas3DTransformValue = ({
+ fieldKey,
+ propStatus,
+ runtimeValue,
+}: {
+ readonly fieldKey: string;
+ readonly propStatus: CanUpdateSequencePropStatus | undefined;
+ readonly runtimeValue: unknown;
+}): boolean => {
+ if (propStatus?.status === 'keyframed') {
+ return propStatus.keyframes.some((keyframe) =>
+ has3DTransformValue({fieldKey, value: keyframe.value}),
+ );
+ }
+
+ return has3DTransformValue({
+ fieldKey,
+ value:
+ propStatus?.status === 'static' ? propStatus.codeValue : runtimeValue,
+ });
+};
diff --git a/packages/studio/src/components/Timeline/transform-origin-utils.ts b/packages/studio/src/components/Timeline/transform-origin-utils.ts
index 44f8da12b2..c86f123ffe 100644
--- a/packages/studio/src/components/Timeline/transform-origin-utils.ts
+++ b/packages/studio/src/components/Timeline/transform-origin-utils.ts
@@ -17,7 +17,7 @@ export type ParsedTransformOrigin = {
};
const cssNumberWithUnit = /^([+-]?(?:\d+\.?\d*|\.\d+))(px|%)$/i;
-const cssLength = /^([+-]?(?:\d+\.?\d*|\.\d+))[a-zA-Z]+$/;
+const cssLength = /^([+-]?(?:\d+\.?\d*|\.\d+))([a-zA-Z]+)$/;
const keywords = new Set(['left', 'center', 'right', 'top', 'bottom']);
const center: TransformOriginAxisValue = {value: 50, unit: '%'};
@@ -174,12 +174,20 @@ const parseXY = (
return keywordIsFirst ? [center, length] : [length, center];
};
-const isSupportedZ = (token: string): boolean => {
+export const parseTransformOriginZ = (
+ token: string,
+): {readonly value: number; readonly unit: string} | null => {
if (token.includes('%')) {
- return false;
+ return null;
}
- return cssLength.test(token);
+ const match = cssLength.exec(token);
+ if (!match) {
+ return null;
+ }
+
+ const value = Number(match[1]);
+ return Number.isFinite(value) ? {value, unit: match[2]} : null;
};
export const parseTransformOrigin = (
@@ -200,7 +208,7 @@ export const parseTransformOrigin = (
}
const z = parts[2] ?? null;
- if (z !== null && !isSupportedZ(z)) {
+ if (z !== null && parseTransformOriginZ(z) === null) {
return null;
}
diff --git a/packages/studio/src/components/canvas-rotation-cursor.ts b/packages/studio/src/components/canvas-rotation-cursor.ts
new file mode 100644
index 0000000000..9d19b088e6
--- /dev/null
+++ b/packages/studio/src/components/canvas-rotation-cursor.ts
@@ -0,0 +1,12 @@
+const canvasRotationCursorSvg = `<svg width="29" height="30" viewBox="0 0 83 85" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#shadow)">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M58.673 35.4941C58.6612 35.1059 58.6552 34.9899 58.6346 34.4705L58.605 33.8746C58.608 33.9357 58.5753 33.3889 58.5813 33.4469L58.5695 33.2635L54.9726 33.508V33.5201C54.9874 33.7371 54.9992 33.9389 55.011 34.1587C55.011 34.1556 55.0851 36.3955 55.0851 36.3924L55.0881 36.4688L55.0851 36.4382L55.0881 36.5268V36.591V36.5604V36.6521V36.6246V36.7163V36.6857L55.0911 36.7927L55.0881 36.7621L55.0911 36.8844V36.8538V36.9913V36.9607V37.1441L55.0908 37.1166V37.3C55.0908 40.1263 54.8952 43.0781 54.4568 46.0083C55.7693 45.6263 57.0555 45.1771 58.273 44.6517C58.5605 42.2072 58.6966 39.7506 58.6966 37.3031C58.6936 36.9149 58.6906 36.527 58.6848 36.1389L58.673 35.4941ZM21.7249 51.5816L11.6923 48.5781L13.6418 46.4055C11.1501 43.9916 9.3219 40.9118 9.3219 37.3C9.33972 34.501 10.3589 32.133 12.0242 29.9697C14.4835 26.8805 17.9916 24.5982 21.9176 22.9633C21.5738 24.4421 21.2893 25.9362 21.0613 27.4426C19.3486 28.3349 17.7752 29.386 16.4095 30.6144C14.7415 32.1421 13.3428 34.0304 13.0051 36.3039C12.7799 37.8317 13.0852 39.2831 13.7724 40.6338C14.3562 41.7765 15.1886 42.8063 16.0896 43.674L18.0364 41.5015L21.7249 51.5816ZM34.2108 19.8313C36.6997 19.5167 39.1175 19.3792 41.3219 19.3792C46.5515 19.3792 51.8463 20.0576 56.8656 21.5854C63.7397 23.6785 73.2715 28.711 73.3219 37.3001C73.3041 40.096 72.2879 42.464 70.6226 44.6274C64.2492 52.639 50.8152 55.221 41.3218 55.221C38.6848 55.221 35.9232 55.056 33.3307 54.6647L33.8196 50.9828C36.2492 51.3495 38.8536 51.5022 41.3248 51.5022C49.3544 51.5022 59.9855 49.6047 66.2374 43.9856C68.1455 42.2377 69.6953 40.0224 69.7189 37.3C69.6804 32.8542 65.5411 29.6123 62.0922 27.7239C55.9115 24.3841 48.2344 23.0948 41.3218 23.0948C38.7026 23.0948 35.8047 23.2965 32.8715 23.7639C33.2479 22.4132 33.6923 21.0965 34.2108 19.8313ZM50.8745 58.1816C52.3146 57.9493 53.7634 57.6652 55.1974 57.317C52.6789 63.6206 48.1633 70.2572 41.3218 70.3C38.6077 70.2816 36.3114 69.2337 34.2137 67.5163C26.4448 60.9408 23.9441 47.09 23.9441 37.3C23.9441 31.91 24.602 26.4466 26.0834 21.2705C28.1131 14.1817 32.9931 4.35195 41.322 4.3C45.63 4.3 49.1057 7.12951 51.5916 10.5272L53.8967 8.76404L55.7041 19.3699L46.3885 14.5025L48.6936 12.7393C46.9723 10.3347 44.3528 8.01873 41.3217 8.01873C37.0106 8.05836 33.8669 12.3302 32.0358 15.8868C28.7972 22.2546 27.5469 30.1715 27.5469 37.3001C27.5469 45.5806 29.387 56.544 34.8388 62.9912C36.5337 64.9589 38.6788 66.5571 41.3217 66.5815C45.6328 66.5418 48.7765 62.2731 50.6076 58.7165L50.8745 58.1816Z" fill="black" stroke="white" stroke-width="3" stroke-linejoin="round" paint-order="stroke"/>
+</g>
+<defs>
+<filter id="shadow" x="0" y="0" width="83" height="85" filterUnits="userSpaceOnUse">
+<feDropShadow dx="0" dy="5" stdDeviation="3.15" flood-color="black" flood-opacity="0.25"/>
+</filter>
+</defs>
+</svg>`;
+
+export const canvasRotationCursor = `url("data:image/svg+xml,${encodeURIComponent(canvasRotationCursorSvg)}") 15 13, alias`;
diff --git a/packages/studio/src/components/selected-outline-drag.ts b/packages/studio/src/components/selected-outline-drag.ts
index 1a308cef1a..7bc4190f85 100644
--- a/packages/studio/src/components/selected-outline-drag.ts
+++ b/packages/studio/src/components/selected-outline-drag.ts
@@ -47,11 +47,15 @@ import {
} from './Timeline/timeline-field-utils';
import {
parseCssRotationToDegrees,
+ parseCssRotationToEuler,
serializeCssRotation,
+ serializeCssRotationFromEuler,
+ type ParsedCssRotation,
} from './Timeline/timeline-rotation-utils';
import {
parseTranslate,
serializeTranslate,
+ type ParsedTranslate,
} from './Timeline/timeline-translate-utils';
import {getLinkedScale} from './Timeline/TimelineScaleField';
import {
@@ -106,7 +110,7 @@ export const getSelectedOutlineDragStates = ({
frame: sourceFrame,
shouldResortToDefaultValueIfUndefined: true,
});
- const [startX, startY] = parseTranslate(
+ const [startX, startY, startZ] = parseTranslate(
String(effectiveValue ?? '0px 0px'),
);
@@ -119,6 +123,7 @@ export const getSelectedOutlineDragStates = ({
sourceFrame,
startX,
startY,
+ startZ,
target,
};
});
@@ -136,7 +141,11 @@ export const getSelectedOutlineDragValues = ({
return new Map(
dragStates.map((dragState) => [
dragState.key,
- serializeTranslate(dragState.startX + deltaX, dragState.startY + deltaY),
+ serializeTranslate([
+ dragState.startX + deltaX,
+ dragState.startY + deltaY,
+ dragState.startZ,
+ ]),
]),
);
};
@@ -206,7 +215,11 @@ export const getSelectedOutlineDragChanges = ({
}
if (dragState.target.propStatus.status === 'keyframed') {
- const startValue = serializeTranslate(dragState.startX, dragState.startY);
+ const startValue = serializeTranslate([
+ dragState.startX,
+ dragState.startY,
+ dragState.startZ,
+ ]);
if (value === startValue) {
continue;
}
@@ -728,6 +741,7 @@ export const getSelectedOutlineRotationDragStates = ({
frame: sourceFrame,
shouldResortToDefaultValueIfUndefined: true,
});
+ const startValue = String(effectiveValue ?? '0deg');
return {
defaultValue:
@@ -736,12 +750,49 @@ export const getSelectedOutlineRotationDragStates = ({
: null,
key: Internals.makeSequencePropsSubscriptionKey(target.nodePath),
sourceFrame,
- startDegrees: parseCssRotationToDegrees(String(effectiveValue ?? '0deg')),
+ startDegrees: parseCssRotationToDegrees(startValue),
+ startRotation: parseCssRotationToEuler(startValue),
+ startValue,
target,
};
});
};
+export const getSelectedOutline3DRotationDragValues = ({
+ dragStates,
+ rotationXDeltaDegrees,
+ rotationYDeltaDegrees,
+}: {
+ readonly dragStates: readonly SelectedOutlineRotationDragState[];
+ readonly rotationXDeltaDegrees: number;
+ readonly rotationYDeltaDegrees: number;
+}): Map<string, string> => {
+ return new Map(
+ dragStates.map((dragState) => {
+ const decimalPlaces = Math.max(
+ 6,
+ getTimelineDisplayDecimalPlaces({
+ defaultDecimalPlaces: 1,
+ step: dragState.target.fieldSchema.step,
+ }),
+ );
+ const {startRotation} = dragState;
+
+ return [
+ dragState.key,
+ serializeCssRotationFromEuler({
+ rotation: [
+ startRotation[0] + rotationXDeltaDegrees,
+ startRotation[1] + rotationYDeltaDegrees,
+ startRotation[2],
+ ],
+ decimalPlaces,
+ }),
+ ];
+ }),
+ );
+};
+
export const getSelectedOutlineRotationDragValues = ({
dragStates,
rotationDeltaDegrees,
@@ -755,6 +806,20 @@ export const getSelectedOutlineRotationDragValues = ({
defaultDecimalPlaces: 1,
step: dragState.target.fieldSchema.step,
});
+ const {startRotation} = dragState;
+ if (dragState.target.transform3DMode) {
+ return [
+ dragState.key,
+ serializeCssRotationFromEuler({
+ rotation: [
+ startRotation[0],
+ startRotation[1],
+ startRotation[2] + rotationDeltaDegrees,
+ ],
+ decimalPlaces: Math.max(6, decimalPlaces),
+ }),
+ ];
+ }
return [
dragState.key,
@@ -781,13 +846,14 @@ export const snapSelectedOutlineRotationDeltaDegrees = ({
return rotationDeltaDegrees;
}
+ const startDegrees = anchor.startRotation[2];
return (
Math.round(
- (anchor.startDegrees + rotationDeltaDegrees) /
+ (startDegrees + rotationDeltaDegrees) /
selectedOutlineRotationSnapStepDegrees,
) *
selectedOutlineRotationSnapStepDegrees -
- anchor.startDegrees
+ startDegrees
);
};
@@ -807,14 +873,7 @@ export const getSelectedOutlineRotationDragChanges = ({
}
if (dragState.target.propStatus.status === 'keyframed') {
- const decimalPlaces = getTimelineDisplayDecimalPlaces({
- defaultDecimalPlaces: 1,
- step: dragState.target.fieldSchema.step,
- });
- const startValue = serializeCssRotation(
- dragState.startDegrees,
- decimalPlaces,
- );
+ const {startValue} = dragState;
if (value === startValue) {
continue;
}
@@ -916,51 +975,37 @@ export const clearSelectedOutlineRotationDragOverrides = ({
}
};
-export const parseCssRotationToRadians = (value: string): number | null => {
- const match = value
- .trim()
- .match(/^([+-]?(?:\d+\.?\d*|\.\d+))(deg|rad|turn|grad)$/);
- if (!match) {
- return null;
- }
-
- const number = Number(match[1]);
- if (!Number.isFinite(number)) {
- return null;
- }
-
- if (match[2] === 'rad') {
- return number;
- }
-
- if (match[2] === 'turn') {
- return number * Math.PI * 2;
- }
-
- if (match[2] === 'grad') {
- return (number / 400) * Math.PI * 2;
- }
-
- return (number / 180) * Math.PI;
-};
-
export const compensateTranslateForTransformOrigin = ({
startTranslate,
deltaOrigin,
- rotate,
+ rotation,
scale,
}: {
readonly startTranslate: readonly [number, number];
readonly deltaOrigin: readonly [number, number];
- readonly rotate: number;
- readonly scale: readonly [number, number];
+ readonly rotation: ParsedCssRotation;
+ readonly scale: readonly [number, number, number];
}): readonly [number, number] => {
- const cos = Math.cos(rotate);
- const sin = Math.sin(rotate);
- const matrixA = cos * scale[0];
- const matrixB = sin * scale[0];
- const matrixC = -sin * scale[1];
- const matrixD = cos * scale[1];
+ const [rawAxisX, rawAxisY, rawAxisZ] = rotation.axis;
+ const axisLength = Math.hypot(rawAxisX, rawAxisY, rawAxisZ);
+ if (axisLength === 0) {
+ return [
+ startTranslate[0] + deltaOrigin[0] * (scale[0] - 1),
+ startTranslate[1] + deltaOrigin[1] * (scale[1] - 1),
+ ];
+ }
+
+ const axisX = rawAxisX / axisLength;
+ const axisY = rawAxisY / axisLength;
+ const axisZ = rawAxisZ / axisLength;
+ const radians = (rotation.degrees * Math.PI) / 180;
+ const cos = Math.cos(radians);
+ const sin = Math.sin(radians);
+ const oneMinusCos = 1 - cos;
+ const matrixA = (cos + axisX * axisX * oneMinusCos) * scale[0];
+ const matrixB = (axisY * axisX * oneMinusCos + axisZ * sin) * scale[0];
+ const matrixC = (axisX * axisY * oneMinusCos - axisZ * sin) * scale[1];
+ const matrixD = (cos + axisY * axisY * oneMinusCos) * scale[1];
const transformedDeltaX = matrixA * deltaOrigin[0] + matrixC * deltaOrigin[1];
const transformedDeltaY = matrixB * deltaOrigin[0] + matrixD * deltaOrigin[1];
const compensationX = deltaOrigin[0] - transformedDeltaX;
@@ -976,7 +1021,7 @@ export const getSelectedOutlineTransformOriginDragChanges = ({
translate,
}: {
readonly target: SelectedOutlineTransformOriginDragTarget;
- readonly startTranslate: readonly [number, number];
+ readonly startTranslate: ParsedTranslate;
readonly origin: string;
readonly translate: string;
}): {
@@ -1054,10 +1099,11 @@ export const getSelectedOutlineTransformOriginDragChanges = ({
nodePath: target.nodePath,
fieldKey: translateFieldKey,
sourceFrame: keyframe.frame,
- value: serializeTranslate(
+ value: serializeTranslate([
keyframeTranslate[0] + deltaTranslateX,
keyframeTranslate[1] + deltaTranslateY,
- ),
+ keyframeTranslate[2],
+ ]),
schema: target.schema,
});
}
diff --git a/packages/studio/src/components/selected-outline-measurement.ts b/packages/studio/src/components/selected-outline-measurement.ts
index 5770f919d2..2ec2f7a1d9 100644
--- a/packages/studio/src/components/selected-outline-measurement.ts
+++ b/packages/studio/src/components/selected-outline-measurement.ts
@@ -8,7 +8,11 @@ import type {
SelectedOutlineLayoutTarget,
SequenceWithSelectedOutline,
} from './selected-outline-types';
-import {cropFieldKeys, transformOriginFieldKey} from './selected-outline-types';
+import {
+ cropFieldKeys,
+ rotateFieldKey,
+ transformOriginFieldKey,
+} from './selected-outline-types';
import {getUvHandlePosition} from './selected-outline-uv';
import {parseKeyframeFieldFromNodePath} from './Timeline/parse-keyframe-field-from-node-path';
import {
@@ -456,6 +460,11 @@ type SelectedTransformOriginInfo = {
readonly displayFrame: number | null;
};
+export type SelectedRotationInfo = {
+ readonly sequenceKey: string;
+ readonly displayFrame: number | null;
+};
+
export type SelectedCropInfo = {
readonly sequenceKey: string;
readonly displayFrame: number | null;
@@ -539,6 +548,42 @@ export const getSelectedTransformOriginInfo = (
};
};
+export const getSelectedRotationInfo = (
+ selectedItems: readonly TimelineSelection[],
+): SelectedRotationInfo | null => {
+ if (selectedItems.length !== 1) {
+ return null;
+ }
+
+ const [selectedItem] = selectedItems;
+ if (
+ selectedItem.type === 'sequence-prop' &&
+ selectedItem.key === rotateFieldKey
+ ) {
+ return {
+ sequenceKey: getTimelineSequenceSelectionKey(selectedItem.nodePathInfo),
+ displayFrame: null,
+ };
+ }
+
+ if (selectedItem.type !== 'keyframe' && selectedItem.type !== 'easing') {
+ return null;
+ }
+
+ const field = getKeyframeOrEasingField(selectedItem);
+ if (field?.type !== 'sequence' || field.fieldKey !== rotateFieldKey) {
+ return null;
+ }
+
+ return {
+ sequenceKey: getTimelineSequenceSelectionKey(selectedItem.nodePathInfo),
+ displayFrame:
+ selectedItem.type === 'keyframe'
+ ? selectedItem.frame
+ : selectedItem.fromFrame,
+ };
+};
+
export const getSequencesWithSelectableOutlines = ({
sequences,
overrideIdsToNodePaths,
diff --git a/packages/studio/src/components/selected-outline-types.ts b/packages/studio/src/components/selected-outline-types.ts
index 554cae2d88..ccf1815b56 100644
--- a/packages/studio/src/components/selected-outline-types.ts
+++ b/packages/studio/src/components/selected-outline-types.ts
@@ -27,9 +27,11 @@ export type SelectedOutlineLayoutTarget = {
readonly ref: React.RefObject<Element | null>;
readonly selected: boolean;
readonly selectedForCrop: boolean;
+ readonly selectedForRotation: boolean;
readonly selectedForTransformOrigin: boolean;
readonly selectedForUvHandles: boolean;
readonly showSelectedOutline: boolean;
+ readonly transformOriginValue: string;
readonly selection: TimelineSelection;
readonly sequence: TSequence;
readonly crop: {
@@ -188,6 +190,7 @@ export type SelectedOutlineRotationDragTarget = {
readonly keyframeDisplayOffset: number;
readonly nodePath: SequencePropsSubscriptionKey;
readonly schema: InteractivitySchema;
+ readonly transform3DMode: boolean;
readonly transformOriginValue: string;
};
@@ -197,6 +200,7 @@ export type SelectedOutlineDragState = {
readonly sourceFrame: number;
readonly startX: number;
readonly startY: number;
+ readonly startZ: number | null;
readonly target: SelectedOutlineDragTarget;
};
@@ -215,6 +219,8 @@ export type SelectedOutlineRotationDragState = {
readonly key: string;
readonly sourceFrame: number;
readonly startDegrees: number;
+ readonly startRotation: readonly [number, number, number];
+ readonly startValue: string;
readonly target: SelectedOutlineRotationDragTarget;
};
diff --git a/packages/studio/src/helpers/get-box-quads-polyfill-internals.js b/packages/studio/src/helpers/get-box-quads-polyfill-internals.js
index fe176d8828..999474b6f4 100644
--- a/packages/studio/src/helpers/get-box-quads-polyfill-internals.js
+++ b/packages/studio/src/helpers/get-box-quads-polyfill-internals.js
@@ -2161,14 +2161,19 @@ export function getElementCombinedTransform(element, iframes) {
m.multiplySelf(new DOMMatrix('translate(' + tr.replaceAll(' ', ',') + ')'));
}
if (hasRotate) {
- m.multiplySelf(
- new DOMMatrix('rotate(' + s.rotate.replaceAll(' ', ',') + ')'),
- );
+ const rotateParts = s.rotate.trim().split(/\s+/);
+ const rotateTransform =
+ rotateParts.length === 1
+ ? `rotate(${rotateParts[0]})`
+ : rotateParts.length === 2 && /^[xyz]$/i.test(rotateParts[0])
+ ? `rotate${rotateParts[0].toUpperCase()}(${rotateParts[1]})`
+ : `rotate3d(${rotateParts.join(',')})`;
+ m.multiplySelf(new DOMMatrix(rotateTransform));
}
if (hasScale) {
- m.multiplySelf(
- new DOMMatrix('scale(' + s.scale.replaceAll(' ', ',') + ')'),
- );
+ const scaleParts = s.scale.trim().split(/\s+/);
+ const scaleFunction = scaleParts.length === 3 ? 'scale3d' : 'scale';
+ m.multiplySelf(new DOMMatrix(`${scaleFunction}(${scaleParts.join(',')})`));
}
if (hasOffsetPath) {
m.multiplySelf(computeOffsetTransformMatrix(element));
diff --git a/packages/studio/src/icons/cube.tsx b/packages/studio/src/icons/cube.tsx
new file mode 100644
index 0000000000..844256d490
--- /dev/null
+++ b/packages/studio/src/icons/cube.tsx
@@ -0,0 +1,13 @@
+import type {SVGProps} from 'react';
+
+export const CubeIcon = ({
+ color,
+ ...props
+}: SVGProps<SVGSVGElement> & {readonly color: string}) => (
+ <svg viewBox="0 0 512 512" {...props}>
+ <path
+ fill={color}
+ d="M234.5 5.7c13.6-7.6 29.3-7.6 42.9 0l192 107.3c14.2 7.9 22.9 22.9 22.9 39.2v207.6c0 16.3-8.8 31.2-22.9 39.2l-192 107.3c-13.6 7.6-29.3 7.6-42.9 0l-192-107.3c-14.2-7.9-22.9-22.9-22.9-39.2V152.2c0-16.3 8.8-31.2 22.9-39.2l192-107.3zM256 50.4L82.2 147.5 256 244.7l173.8-97.2L256 50.4zm-192 137v172.4l168 93.9V281.3L64 187.4zm216 266.3l168-93.9V187.4l-168 93.9v172.4z"
+ />
+ </svg>
+);
diff --git a/packages/studio/src/state/transform-3d-mode.tsx b/packages/studio/src/state/transform-3d-mode.tsx
new file mode 100644
index 0000000000..abfe24ea66
--- /dev/null
+++ b/packages/studio/src/state/transform-3d-mode.tsx
@@ -0,0 +1,43 @@
+import React, {createContext, useCallback, useMemo, useState} from 'react';
+
+type Transform3DModeState = {
+ readonly manuallyEnabledSequenceKeys: ReadonlySet<string>;
+ readonly setManuallyEnabled: (sequenceKey: string, enabled: boolean) => void;
+};
+
+export const Transform3DModeStateContext = createContext<Transform3DModeState>({
+ manuallyEnabledSequenceKeys: new Set(),
+ setManuallyEnabled: () => undefined,
+});
+
+export const Transform3DModeStateProvider: React.FC<{
+ readonly children: React.ReactNode;
+}> = ({children}) => {
+ const [manuallyEnabledSequenceKeys, setManuallyEnabledSequenceKeys] =
+ useState<ReadonlySet<string>>(() => new Set());
+ const setManuallyEnabled = useCallback(
+ (sequenceKey: string, enabled: boolean) => {
+ setManuallyEnabledSequenceKeys((previous) => {
+ const next = new Set(previous);
+ if (enabled) {
+ next.add(sequenceKey);
+ } else {
+ next.delete(sequenceKey);
+ }
+
+ return next;
+ });
+ },
+ [],
+ );
+ const value = useMemo(
+ () => ({manuallyEnabledSequenceKeys, setManuallyEnabled}),
+ [manuallyEnabledSequenceKeys, setManuallyEnabled],
+ );
+
+ return (
+ <Transform3DModeStateContext.Provider value={value}>
+ {children}
+ </Transform3DModeStateContext.Provider>
+ );
+};
diff --git a/packages/studio/src/test/timeline-rotation-utils.test.ts b/packages/studio/src/test/timeline-rotation-utils.test.ts
new file mode 100644
index 0000000000..444830a152
--- /dev/null
+++ b/packages/studio/src/test/timeline-rotation-utils.test.ts
@@ -0,0 +1,45 @@
+import {expect, test} from 'bun:test';
+import {
+ parseCssRotation,
+ parseCssRotationToEuler,
+ serializeCssRotationFromEuler,
+} from '../components/Timeline/timeline-rotation-utils';
+
+test('parses CSS axis rotations', () => {
+ expect(parseCssRotation('45deg')).toEqual({
+ axis: [0, 0, 1],
+ degrees: 45,
+ });
+ expect(parseCssRotation('x 0.25turn')).toEqual({
+ axis: [1, 0, 0],
+ degrees: 90,
+ });
+ expect(parseCssRotation('0.5 1 -2 100grad')).toEqual({
+ axis: [0.5, 1, -2],
+ degrees: 90,
+ });
+});
+
+test('converts CSS rotations to X, Y and Z angles', () => {
+ expect(parseCssRotationToEuler('45deg')).toEqual([0, 0, 45]);
+ expect(parseCssRotationToEuler('x 90deg')).toEqual([90, 0, 0]);
+ expect(parseCssRotationToEuler('y -45deg')).toEqual([0, -45, 0]);
+ expect(parseCssRotationToEuler('-2.4 -5 2.9 0deg')).toEqual([0, 0, 0]);
+});
+
+test('serializes X, Y and Z angles as CSS rotations', () => {
+ expect(serializeCssRotationFromEuler({rotation: [0, 0, 45]})).toBe('45deg');
+ expect(serializeCssRotationFromEuler({rotation: [30, 0, 0]})).toBe('x 30deg');
+ expect(serializeCssRotationFromEuler({rotation: [0, -20, 0]})).toBe(
+ 'y -20deg',
+ );
+ expect(serializeCssRotationFromEuler({rotation: [0, 0, 0]})).toBe('0deg');
+
+ const serialized = serializeCssRotationFromEuler({
+ rotation: [30, 45, 60],
+ });
+ const parsed = parseCssRotationToEuler(serialized);
+ expect(parsed[0]).toBeCloseTo(30, 4);
+ expect(parsed[1]).toBeCloseTo(45, 4);
+ expect(parsed[2]).toBeCloseTo(60, 4);
+});
diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.ts
index 20b9ec71fd..91c45182f3 100644
--- a/packages/studio/src/test/timeline-selection.test.ts
+++ b/packages/studio/src/test/timeline-selection.test.ts
@@ -40,6 +40,7 @@ import {
compensateTranslateForTransformOrigin,
getOutlineSelectionInteraction,
getSelectedEffectFieldsBySequenceKey,
+ getSelectedOutline3DRotationDragValues,
getSelectedOutlineActiveSchema,
getSelectedOutlineCropDragChanges,
getSelectedOutlineCropDragValues,
@@ -89,6 +90,7 @@ import {
} from '../components/Timeline/keyframe-clipboard';
import {getTimelinePropResetTargets} from '../components/Timeline/reset-selected-timeline-props';
import {shouldSubscribeToSequenceProps} from '../components/Timeline/should-subscribe-to-sequence-props';
+import {parseCssRotationToEuler} from '../components/Timeline/timeline-rotation-utils';
import {
getEasingClipboardDataFromSelection,
getEffectPropClipboardDataFromSelection,
@@ -111,6 +113,7 @@ import {
getTimelineSelectionAfterInteraction,
getTimelineSelectionFromNodePathInfo,
getTimelineSelectionKey,
+ getTimelineSequenceSelectionForEscape,
getTimelineSequenceSelectionKey,
isTimelineSelectionModifierEvent,
shouldSelectTimelineRowOnPointerDown,
@@ -3959,16 +3962,26 @@ test('Transform origin parser rejects unsupported calc values', () => {
expect(parseTransformOrigin('calc(50% + 10px) 50%')).toBeNull();
});
-test('Transform origin compensation keeps rotated and scaled elements in place', () => {
- const next = compensateTranslateForTransformOrigin({
+test('Transform origin compensation supports 2D and 3D rotation', () => {
+ const next2D = compensateTranslateForTransformOrigin({
startTranslate: [20, 30],
deltaOrigin: [10, 5],
- rotate: Math.PI / 2,
- scale: [2, 3],
+ rotation: {axis: [0, 0, 1], degrees: 90},
+ scale: [2, 3, 1],
});
- expect(next[0]).toBeCloseTo(-5, 5);
- expect(next[1]).toBeCloseTo(45, 5);
+ expect(next2D[0]).toBeCloseTo(-5, 5);
+ expect(next2D[1]).toBeCloseTo(45, 5);
+
+ const next3D = compensateTranslateForTransformOrigin({
+ startTranslate: [20, 30],
+ deltaOrigin: [10, 5],
+ rotation: {axis: [1, 0, 0], degrees: 60},
+ scale: [2, 3, 4],
+ });
+
+ expect(next3D[0]).toBeCloseTo(30, 5);
+ expect(next3D[1]).toBeCloseTo(32.5, 5);
});
const makeTransformOriginDragTarget = ({
@@ -4025,7 +4038,7 @@ test('Transform origin drag keeps static properties static', () => {
originKeyframed: false,
translateKeyframed: false,
}),
- startTranslate: [10, 20],
+ startTranslate: [10, 20, null],
origin: '25% 75%',
translate: '13px 24px',
});
@@ -4038,14 +4051,29 @@ test('Transform origin drag keeps static properties static', () => {
});
test('Transform origin drag offsets all animated translate keyframes', () => {
+ const target = makeTransformOriginDragTarget({
+ originKeyframed: false,
+ translateKeyframed: true,
+ });
+ if (target.translatePropStatus.status !== 'keyframed') {
+ throw new Error('Expected a keyframed translate');
+ }
+
const changes = getSelectedOutlineTransformOriginDragChanges({
- target: makeTransformOriginDragTarget({
- originKeyframed: false,
- translateKeyframed: true,
- }),
- startTranslate: [10, 20],
+ target: {
+ ...target,
+ translatePropStatus: {
+ ...target.translatePropStatus,
+ keyframes: [
+ {frame: 0, value: '0px 0px 5px'},
+ {frame: 20, value: '20px 40px 25px'},
+ ],
+ },
+ translateValue: '10px 20px 15px',
+ },
+ startTranslate: [10, 20, 15],
origin: '25% 75%',
- translate: '13px 24px',
+ translate: '13px 24px 15px',
});
expect(changes.staticChanges.map((change) => change.fieldKey)).toEqual([
@@ -4058,8 +4086,8 @@ test('Transform origin drag offsets all animated translate keyframes', () => {
value,
})),
).toEqual([
- {fieldKey: 'style.translate', sourceFrame: 0, value: '3px 4px'},
- {fieldKey: 'style.translate', sourceFrame: 20, value: '23px 44px'},
+ {fieldKey: 'style.translate', sourceFrame: 0, value: '3px 4px 5px'},
+ {fieldKey: 'style.translate', sourceFrame: 20, value: '23px 44px 25px'},
]);
});
@@ -4069,7 +4097,7 @@ test('Transform origin drag does not keyframe a static translate', () => {
originKeyframed: true,
translateKeyframed: false,
}),
- startTranslate: [10, 20],
+ startTranslate: [10, 20, null],
origin: '25% 75%',
translate: '13px 24px',
});
@@ -4091,7 +4119,7 @@ test('Transform origin drag updates both animated properties locally', () => {
originKeyframed: true,
translateKeyframed: true,
}),
- startTranslate: [10, 20],
+ startTranslate: [10, 20, null],
origin: '25% 75%',
translate: '13px 24px',
});
@@ -5156,6 +5184,79 @@ test('Crop prop and keyframe selections target crop handles', () => {
).toBe(null);
});
+test('Escape moves crop and rotation selections to the sequence', () => {
+ const sequenceNodePathInfo = makeNodePathInfo(['body', 0], []);
+ const expectedSelection = {
+ type: 'sequence' as const,
+ nodePathInfo: sequenceNodePathInfo,
+ };
+
+ expect(
+ getTimelineSequenceSelectionForEscape([
+ {
+ type: 'sequence-prop',
+ nodePathInfo: makeNodePathInfo(['body', 0], ['controls', 'cropLeft']),
+ key: 'cropLeft',
+ },
+ ]),
+ ).toEqual(expectedSelection);
+ expect(
+ getTimelineSequenceSelectionForEscape([
+ {
+ type: 'sequence-prop',
+ nodePathInfo: makeNodePathInfo(
+ ['body', 0],
+ ['controls', 'style', 'rotate'],
+ ),
+ key: 'style.rotate',
+ },
+ ]),
+ ).toEqual(expectedSelection);
+ expect(
+ getTimelineSequenceSelectionForEscape([
+ {
+ type: 'keyframe',
+ nodePathInfo: makeNodePathInfo(
+ ['body', 0],
+ ['controls', 'style', 'rotate'],
+ ),
+ frame: 10,
+ },
+ ]),
+ ).toEqual(expectedSelection);
+ expect(
+ getTimelineSequenceSelectionForEscape([
+ {
+ type: 'easing',
+ nodePathInfo: makeNodePathInfo(['body', 0], ['controls', 'cropBottom']),
+ fromFrame: 10,
+ toFrame: 20,
+ segmentIndex: 0,
+ },
+ ]),
+ ).toEqual(expectedSelection);
+ expect(
+ getTimelineSequenceSelectionForEscape([
+ {
+ type: 'sequence-prop',
+ nodePathInfo: makeNodePathInfo(
+ ['body', 0],
+ ['controls', 'style', 'opacity'],
+ ),
+ key: 'style.opacity',
+ },
+ ]),
+ ).toBe(null);
+ expect(
+ getTimelineSequenceSelectionForEscape([
+ {
+ type: 'sequence',
+ nodePathInfo: sequenceNodePathInfo,
+ },
+ ]),
+ ).toBe(null);
+});
+
test('selected sequence keys only include exact sequence selections', () => {
const sequenceNodePathInfo = makeNodePathInfo(['body', 0], []);
const effectPropNodePathInfo = makeNodePathInfo(
@@ -5673,9 +5774,10 @@ test('Selected outline dragging applies the same delta to all selected sequences
sourceFrame: 12,
startX: 10,
startY: 20,
+ startZ: 30,
target: {
clientId: 'client',
- propStatus: {status: 'static', codeValue: '10px 20px'},
+ propStatus: {status: 'static', codeValue: '10px 20px 30px'},
fieldDefault: '0px 0px',
keyframeDisplayOffset: 30,
nodePath: firstNodePath,
@@ -5688,6 +5790,7 @@ test('Selected outline dragging applies the same delta to all selected sequences
sourceFrame: 12,
startX: -5,
startY: 3,
+ startZ: null,
target: {
clientId: 'client',
propStatus: {status: 'static', codeValue: '-5px 3px'},
@@ -5705,7 +5808,7 @@ test('Selected outline dragging applies the same delta to all selected sequences
deltaY: -4.666667,
});
- expect(lastValues.get(dragStates[0].key)).toBe('17.3px 15.3px');
+ expect(lastValues.get(dragStates[0].key)).toBe('17.3px 15.3px 30px');
expect(lastValues.get(dragStates[1].key)).toBe('2.3px -1.7px');
expect(
getSelectedOutlineDragChanges({
@@ -5718,7 +5821,7 @@ test('Selected outline dragging applies the same delta to all selected sequences
fileName: '/project/src/Comp.tsx',
nodePath: firstNodePath,
fieldKey: 'style.translate',
- value: '17.3px 15.3px',
+ value: '17.3px 15.3px 30px',
defaultValue: JSON.stringify('0px 0px'),
schema,
},
@@ -5794,6 +5897,7 @@ test('Selected outline keyboard nudging moves by one or ten pixels', () => {
sourceFrame: 12,
startX: 10,
startY: 20,
+ startZ: null,
target: {
clientId: 'client',
propStatus: {status: 'static', codeValue: '10px 20px'},
@@ -5937,14 +6041,15 @@ test('Selected outline dragging keyframed translate adds a keyframe at the sourc
sourceFrame: 20,
startX: 50,
startY: 25,
+ startZ: 15,
target: {
clientId: 'client',
propStatus: {
status: 'keyframed',
interpolationFunction: 'interpolate',
keyframes: [
- {frame: 0, value: '0px 0px'},
- {frame: 40, value: '100px 50px'},
+ {frame: 0, value: '0px 0px 15px'},
+ {frame: 40, value: '100px 50px 15px'},
],
easing: [{type: 'linear'}],
clamping: {left: 'extend', right: 'extend'},
@@ -5965,7 +6070,7 @@ test('Selected outline dragging keyframed translate adds a keyframe at the sourc
deltaY: -4,
});
- expect(lastValues.get(dragStates[0].key)).toBe('57px 21px');
+ expect(lastValues.get(dragStates[0].key)).toBe('57px 21px 15px');
expect(
getSelectedOutlineDragChanges({
dragStates,
@@ -5978,7 +6083,7 @@ test('Selected outline dragging keyframed translate adds a keyframe at the sourc
nodePath,
fieldKey: 'style.translate',
sourceFrame: 20,
- value: '57px 21px',
+ value: '57px 21px 15px',
schema,
clientId: 'client',
},
@@ -5986,7 +6091,7 @@ test('Selected outline dragging keyframed translate adds a keyframe at the sourc
expect(
getSelectedOutlineDragChanges({
dragStates,
- lastValues: new Map([[dragStates[0].key, '50px 25px']]),
+ lastValues: new Map([[dragStates[0].key, '50px 25px 15px']]),
}),
).toEqual([]);
});
@@ -6132,6 +6237,8 @@ test('Selected outline corner dragging rotates selected sequences', () => {
key: Internals.makeSequencePropsSubscriptionKey(firstNodePath),
sourceFrame: 12,
startDegrees: 45,
+ startRotation: [0, 0, 45],
+ startValue: '45deg',
target: {
clientId: 'client',
propStatus: {status: 'static', codeValue: '45deg'},
@@ -6140,6 +6247,7 @@ test('Selected outline corner dragging rotates selected sequences', () => {
keyframeDisplayOffset: 30,
nodePath: firstNodePath,
schema,
+ transform3DMode: false,
transformOriginValue: '50% 50%',
},
},
@@ -6148,6 +6256,8 @@ test('Selected outline corner dragging rotates selected sequences', () => {
key: Internals.makeSequencePropsSubscriptionKey(secondNodePath),
sourceFrame: 12,
startDegrees: -10,
+ startRotation: [0, 0, -10],
+ startValue: '-10deg',
target: {
clientId: 'client',
propStatus: {status: 'static', codeValue: '-10deg'},
@@ -6156,6 +6266,7 @@ test('Selected outline corner dragging rotates selected sequences', () => {
keyframeDisplayOffset: 30,
nodePath: secondNodePath,
schema,
+ transform3DMode: false,
transformOriginValue: '50% 50%',
},
},
@@ -6206,6 +6317,8 @@ test('Selected outline corner dragging rounds rotation values', () => {
key: Internals.makeSequencePropsSubscriptionKey(nodePath),
sourceFrame: 12,
startDegrees: 32,
+ startRotation: [0, 0, 32],
+ startValue: '32deg',
target: {
clientId: 'client',
propStatus: {status: 'static', codeValue: '32deg'},
@@ -6214,6 +6327,7 @@ test('Selected outline corner dragging rounds rotation values', () => {
keyframeDisplayOffset: 30,
nodePath,
schema,
+ transform3DMode: false,
transformOriginValue: '50% 50%',
},
},
@@ -6227,6 +6341,95 @@ test('Selected outline corner dragging rounds rotation values', () => {
expect(lastValues.get(dragStates[0].key)).toBe('32.5deg');
});
+test('Selected outline canvas dragging changes X and Y rotation while preserving Z', () => {
+ const schema = {
+ 'style.rotate': {type: 'rotation-css', default: '0deg'},
+ } satisfies InteractivitySchema;
+ const nodePath = makeKey(['body', 0]);
+ const dragStates = [
+ {
+ defaultValue: JSON.stringify('0deg'),
+ key: Internals.makeSequencePropsSubscriptionKey(nodePath),
+ sourceFrame: 12,
+ startDegrees: 30,
+ startRotation: [10, 20, 30],
+ startValue: '0.386017 0.438014 0.811871 38.630009deg',
+ target: {
+ clientId: 'client',
+ propStatus: {
+ status: 'static',
+ codeValue: '0.386017 0.438014 0.811871 38.630009deg',
+ },
+ fieldDefault: '0deg',
+ fieldSchema: schema['style.rotate'],
+ keyframeDisplayOffset: 30,
+ nodePath,
+ schema,
+ transform3DMode: true,
+ transformOriginValue: '50% 50%',
+ },
+ },
+ ] satisfies SelectedOutlineRotationDragState[];
+
+ const lastValues = getSelectedOutline3DRotationDragValues({
+ dragStates,
+ rotationXDeltaDegrees: -15,
+ rotationYDeltaDegrees: 25,
+ });
+ const rotation = parseCssRotationToEuler(lastValues.get(dragStates[0].key)!);
+
+ expect(rotation[0]).toBeCloseTo(-5, 4);
+ expect(rotation[1]).toBeCloseTo(45, 4);
+ expect(rotation[2]).toBeCloseTo(30, 4);
+});
+
+test('Selected outline corner dragging changes Z rotation while preserving X and Y', () => {
+ const schema = {
+ 'style.rotate': {type: 'rotation-css', default: '0deg'},
+ } satisfies InteractivitySchema;
+ const nodePath = makeKey(['body', 0]);
+ const dragStates = [
+ {
+ defaultValue: JSON.stringify('0deg'),
+ key: Internals.makeSequencePropsSubscriptionKey(nodePath),
+ sourceFrame: 12,
+ startDegrees: 38.630009,
+ startRotation: [10, 20, 30],
+ startValue: '0.386017 0.438014 0.811871 38.630009deg',
+ target: {
+ clientId: 'client',
+ propStatus: {
+ status: 'static',
+ codeValue: '0.386017 0.438014 0.811871 38.630009deg',
+ },
+ fieldDefault: '0deg',
+ fieldSchema: schema['style.rotate'],
+ keyframeDisplayOffset: 30,
+ nodePath,
+ schema,
+ transform3DMode: true,
+ transformOriginValue: '50% 50%',
+ },
+ },
+ ] satisfies SelectedOutlineRotationDragState[];
+
+ const lastValues = getSelectedOutlineRotationDragValues({
+ dragStates,
+ rotationDeltaDegrees: 15,
+ });
+ const rotation = parseCssRotationToEuler(lastValues.get(dragStates[0].key)!);
+
+ expect(rotation[0]).toBeCloseTo(10, 4);
+ expect(rotation[1]).toBeCloseTo(20, 4);
+ expect(rotation[2]).toBeCloseTo(45, 4);
+ expect(
+ snapSelectedOutlineRotationDeltaDegrees({
+ dragStates,
+ rotationDeltaDegrees: 8,
+ }),
+ ).toBe(15);
+});
+
test('Selected outline corner dragging snaps rotation to 15 degree increments', () => {
const schema = {
'style.rotate': {type: 'rotation-css', default: '0deg'},
@@ -6238,6 +6441,8 @@ test('Selected outline corner dragging snaps rotation to 15 degree increments',
key: Internals.makeSequencePropsSubscriptionKey(nodePath),
sourceFrame: 12,
startDegrees: 32,
+ startRotation: [0, 0, 32],
+ startValue: '32deg',
target: {
clientId: 'client',
propStatus: {status: 'static', codeValue: '32deg'},
@@ -6246,6 +6451,7 @@ test('Selected outline corner dragging snaps rotation to 15 degree increments',
keyframeDisplayOffset: 30,
nodePath,
schema,
+ transform3DMode: false,
transformOriginValue: '50% 50%',
},
},
@@ -6276,6 +6482,8 @@ test('Selected outline corner dragging snaps selected rotations from the first d
key: Internals.makeSequencePropsSubscriptionKey(firstNodePath),
sourceFrame: 12,
startDegrees: 32,
+ startRotation: [0, 0, 32],
+ startValue: '32deg',
target: {
clientId: 'client',
propStatus: {status: 'static', codeValue: '32deg'},
@@ -6284,6 +6492,7 @@ test('Selected outline corner dragging snaps selected rotations from the first d
keyframeDisplayOffset: 30,
nodePath: firstNodePath,
schema,
+ transform3DMode: false,
transformOriginValue: '50% 50%',
},
},
@@ -6292,6 +6501,8 @@ test('Selected outline corner dragging snaps selected rotations from the first d
key: Internals.makeSequencePropsSubscriptionKey(secondNodePath),
sourceFrame: 12,
startDegrees: -10,
+ startRotation: [0, 0, -10],
+ startValue: '-10deg',
target: {
clientId: 'client',
propStatus: {status: 'static', codeValue: '-10deg'},
@@ -6300,6 +6511,7 @@ test('Selected outline corner dragging snaps selected rotations from the first d
keyframeDisplayOffset: 30,
nodePath: secondNodePath,
schema,
+ transform3DMode: false,
transformOriginValue: '50% 50%',
},
},
@@ -6330,6 +6542,8 @@ test('Selected outline corner dragging keyframed rotation adds a keyframe at the
key: Internals.makeSequencePropsSubscriptionKey(nodePath),
sourceFrame: 20,
startDegrees: 45,
+ startRotation: [0, 0, 45],
+ startValue: '45deg',
target: {
clientId: 'client',
propStatus: {
@@ -6349,6 +6563,7 @@ test('Selected outline corner dragging keyframed rotation adds a keyframe at the
keyframeDisplayOffset: 30,
nodePath,
schema,
+ transform3DMode: false,
transformOriginValue: '50% 50%',
},
},
diff --git a/packages/studio/src/test/timeline-translate-utils.test.ts b/packages/studio/src/test/timeline-translate-utils.test.ts
index e59d4e1381..89b2868d8e 100644
--- a/packages/studio/src/test/timeline-translate-utils.test.ts
+++ b/packages/studio/src/test/timeline-translate-utils.test.ts
@@ -6,20 +6,34 @@ import {
test('parseTranslate normalizes floating point noise', () => {
expect(parseTranslate('10.020000000000001px 30.240000000000002px')).toEqual([
- 10.02, 30.24,
+ 10.02,
+ 30.24,
+ null,
]);
+ expect(
+ parseTranslate(
+ '10.020000000000001px 30.240000000000002px 40.480000000000004px',
+ ),
+ ).toEqual([10.02, 30.24, 40.48]);
});
test('serializeTranslate normalizes floating point noise', () => {
- expect(serializeTranslate(0.1 + 0.2, 10.020000000000001)).toBe('0.3px 10px');
+ expect(serializeTranslate([0.1 + 0.2, 10.020000000000001, null])).toBe(
+ '0.3px 10px',
+ );
+ expect(
+ serializeTranslate([0.1 + 0.2, 10.020000000000001, 20.030000000000001]),
+ ).toBe('0.3px 10px 20px');
});
test('serializeTranslate limits coordinates to one decimal place', () => {
- expect(serializeTranslate(254.854512, 393.565342)).toBe('254.9px 393.6px');
+ expect(serializeTranslate([254.854512, 393.565342, null])).toBe(
+ '254.9px 393.6px',
+ );
});
test('serializeTranslate respects more precise steps', () => {
- expect(serializeTranslate(254.854512, 393.565342, 2)).toBe(
- '254.85px 393.57px',
+ expect(serializeTranslate([254.854512, 393.565342, 12.3456], 2)).toBe(
+ '254.85px 393.57px 12.35px',
);
});