Skip to content

🎥 Make videos programmatically with React

`@remotion/mac-cursors`: Support interactive cursor keyframes (#10330)

Jonny Burgerbfc6ef7f991e
diff --git a/bun.lock b/bun.lock
index beaae0e85f..adae318987 100644
--- a/bun.lock
+++ b/bun.lock
@@ -105,6 +105,7 @@
"@remotion/eslint-config-internal": "workspace:*",
"@remotion/fonts": "workspace:*",
"@remotion/google-fonts": "workspace:*",
+ "@remotion/mac-cursors": "workspace:*",
"@remotion/media": "workspace:*",
"@remotion/media-utils": "workspace:*",
"@remotion/noise": "workspace:*",
diff --git a/packages/brand/package.json b/packages/brand/package.json
index fdded7c496..c24c60fbc9 100644
--- a/packages/brand/package.json
+++ b/packages/brand/package.json
@@ -24,6 +24,7 @@
"@remotion/eslint-config-internal": "workspace:*",
"@remotion/fonts": "workspace:*",
"@remotion/google-fonts": "workspace:*",
+ "@remotion/mac-cursors": "workspace:*",
"@remotion/media": "workspace:*",
"@remotion/media-utils": "workspace:*",
"@remotion/noise": "workspace:*",
diff --git a/packages/brand/public/remotion-capture-editor-starter.mp4 b/packages/brand/public/remotion-capture-editor-starter.mp4
new file mode 100644
index 0000000000..b1d2b36d39
Binary files /dev/null and b/packages/brand/public/remotion-capture-editor-starter.mp4 differ
diff --git a/packages/brand/src/CanvasCapturePreview.tsx b/packages/brand/src/CanvasCapturePreview.tsx
index f0ba706af2..7e1f2dbfe3 100644
--- a/packages/brand/src/CanvasCapturePreview.tsx
+++ b/packages/brand/src/CanvasCapturePreview.tsx
@@ -1,470 +1,157 @@
+import {MacOSCursor} from '@remotion/mac-cursors';
import {Video} from '@remotion/media';
-import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
-import React from 'react';
-import type {CalculateMetadataFunction} from 'remotion';
import {
AbsoluteFill,
- Img,
+ Composition,
+ Easing,
+ interpolate,
staticFile,
useCurrentFrame,
- useVideoConfig,
} from 'remotion';
-import {z} from 'zod';
-type MouseMovement = {
- readonly timeInSeconds: number;
- readonly clientX: number;
- readonly clientY: number;
- readonly pageX: number;
- readonly pageY: number;
- readonly canvasX: number | null;
- readonly canvasY: number | null;
- readonly cursor: string;
-};
-
-type CaptureMetadata = {
- readonly density: number;
- readonly contentRect: {
- readonly left: number;
- readonly top: number;
- readonly width: number;
- readonly height: number;
- };
- readonly canvasSize: {
- readonly width: number;
- readonly height: number;
- };
- readonly viewport: {
- readonly width: number;
- readonly height: number;
- readonly scrollX: number;
- readonly scrollY: number;
- };
-};
-
-type PointerClick = {
- readonly timeInSeconds: number;
- readonly type: 'pointer-down' | 'pointer-up';
-};
-
-type CursorRecording = {
- readonly startedAt: number;
- readonly endedAt: number;
- readonly captureMetadata: CaptureMetadata;
- readonly mouseMovements: MouseMovement[];
- readonly pointerClicks?: PointerClick[];
-};
-
-export const canvasCapturePreviewSchema = z.object({
- videoFile: z.string(),
- cursorScale: z.number(),
- hidden: z.enum(['cursor', 'screen']).nullable(),
-});
-
-export type CanvasCapturePreviewProps = z.infer<
- typeof canvasCapturePreviewSchema
-> & {
- readonly cursorData?: CursorRecording | null;
- readonly width: number | null;
- readonly height: number | null;
-};
-
-const CURSOR_ASSET_BASE_PATH = 'https://remotion.media/mac-cursors';
-
-const macCursorFilenameByCssValue: Record<string, string | null> = {
- alias: 'makealias.svg',
- 'all-scroll': 'move.svg',
- auto: 'default.svg',
- beachball: 'beachball.svg',
- busy: 'busy.svg',
- cell: 'cell.svg',
- 'col-resize': 'resizeleftright.svg',
- 'context-menu': 'contextualmenu.svg',
- contextualmenu: 'contextualmenu.svg',
- copy: 'copy.svg',
- crosshair: 'cross.svg',
- cross: 'cross.svg',
- default: 'default.svg',
- 'e-resize': 'resizeeast.svg',
- 'ew-resize': 'resizeleftright.svg',
- grab: 'handopen.svg',
- grabbing: 'handgrabbing.svg',
- handgrabbing: 'handgrabbing.svg',
- handopen: 'handopen.svg',
- handpointing: 'handpointing.svg',
- help: 'help.svg',
- makealias: 'makealias.svg',
- move: 'move.svg',
- 'n-resize': 'resizenorth.svg',
- 'ne-resize': 'resizenortheast.svg',
- 'nesw-resize': 'resizenortheastsouthwest.svg',
- 'no-drop': 'notallowed.svg',
- none: null,
- 'not-allowed': 'notallowed.svg',
- 'ns-resize': 'resizenorthsouth.svg',
- 'nw-resize': 'resizenorthwest.svg',
- 'nwse-resize': 'resizenorthwestsoutheast.svg',
- pointer: 'handpointing.svg',
- poof: 'poof.svg',
- progress: 'busy.svg',
- 'resize northsouth': 'resize northsouth.svg',
- resizedown: 'resizedown.svg',
- resizeeast: 'resizeeast.svg',
- resizeleft: 'resizeleft.svg',
- resizeleftright: 'resizeleftright.svg',
- resizenorth: 'resizenorth.svg',
- resizenortheast: 'resizenortheast.svg',
- resizenortheastsouthwest: 'resizenortheastsouthwest.svg',
- resizenorthsouth: 'resizenorthsouth.svg',
- resizenorthwest: 'resizenorthwest.svg',
- resizenorthwestsoutheast: 'resizenorthwestsoutheast.svg',
- resizeright: 'resizeright.svg',
- resizesouth: 'resizesouth.svg',
- resizesoutheast: 'resizesoutheast.svg',
- resizesouthwest: 'resizesouthwest.svg',
- resizeup: 'resizeup.svg',
- resizeupdown: 'resizeupdown.svg',
- resizewest: 'resizewest.svg',
- resizewesteast: 'resizewesteast.svg',
- 'row-resize': 'resizenorthsouth.svg',
- 's-resize': 'resizesouth.svg',
- screenshotselection: 'screenshotselection.svg',
- screenshotwindow: 'screenshotwindow.svg',
- 'se-resize': 'resizesoutheast.svg',
- 'sw-resize': 'resizesouthwest.svg',
- text: 'textcursor.svg',
- textcursor: 'textcursor.svg',
- textcursorvertical: 'textcursorvertical.svg',
- 'vertical-text': 'textcursorvertical.svg',
- 'w-resize': 'resizewest.svg',
- wait: 'busy.svg',
- 'zoom-in': 'zoomin.svg',
- 'zoom-out': 'zoomout.svg',
-};
-
-type CursorHotspot = {
- readonly x: number;
- readonly y: number;
-};
-
-// Derived from the official macOS cursor hotspots (HIServices cursor
-// resources + NSCursor), mapped into the 32x32 viewBox of each SVG.
-const macCursorHotspotByFilename: Record<string, CursorHotspot> = {
- 'resize northsouth.svg': {x: 16, y: 16},
- 'beachball.svg': {x: 16, y: 16},
- 'busy.svg': {x: 8, y: 3},
- 'cell.svg': {x: 16, y: 16},
- 'contextualmenu.svg': {x: 9, y: 10},
- 'copy.svg': {x: 8, y: 3},
- 'cross.svg': {x: 16, y: 16},
- 'default.svg': {x: 10, y: 9},
- 'handgrabbing.svg': {x: 15, y: 14},
- 'handopen.svg': {x: 15, y: 14},
- 'handpointing.svg': {x: 14, y: 8},
- 'help.svg': {x: 16, y: 17},
- 'makealias.svg': {x: 18, y: 10},
- 'move.svg': {x: 16, y: 16},
- 'notallowed.svg': {x: 8, y: 3},
- 'poof.svg': {x: 8, y: 3},
- 'resizedown.svg': {x: 16, y: 15},
- 'resizeeast.svg': {x: 15, y: 16},
- 'resizeleft.svg': {x: 19, y: 16},
- 'resizeleftright.svg': {x: 16, y: 16},
- 'resizenorth.svg': {x: 16, y: 18},
- 'resizenortheast.svg': {x: 15, y: 18},
- 'resizenortheastsouthwest.svg': {x: 16, y: 16},
- 'resizenorthsouth.svg': {x: 16, y: 16},
- 'resizenorthwest.svg': {x: 18, y: 18},
- 'resizenorthwestsoutheast.svg': {x: 16, y: 16},
- 'resizeright.svg': {x: 14, y: 16},
- 'resizesouth.svg': {x: 16, y: 15},
- 'resizesoutheast.svg': {x: 15, y: 14},
- 'resizesouthwest.svg': {x: 18, y: 14},
- 'resizeup.svg': {x: 16, y: 18},
- 'resizeupdown.svg': {x: 16, y: 16},
- 'resizewest.svg': {x: 18, y: 16},
- 'resizewesteast.svg': {x: 16, y: 17},
- 'screenshotselection.svg': {x: 16.5, y: 16.5},
- 'screenshotwindow.svg': {x: 16, y: 16},
- 'textcursor.svg': {x: 16.5, y: 16},
- 'textcursorvertical.svg': {x: 16.5, y: 15.5},
- 'zoomin.svg': {x: 14, y: 14},
- 'zoomout.svg': {x: 14, y: 14},
-};
-
-const resolveCursorAsset = (basePath: string, filename: string) => {
- const normalizedBasePath = basePath.endsWith('/')
- ? basePath.slice(0, -1)
- : basePath;
-
- return normalizedBasePath.startsWith('http://') ||
- normalizedBasePath.startsWith('https://')
- ? `${normalizedBasePath}/${encodeURIComponent(filename)}`
- : staticFile(`${normalizedBasePath}/${filename}`);
-};
-
-type UrlCursor = {
- readonly url: string;
- readonly hotspotX: number;
- readonly hotspotY: number;
-};
-
-// Parses the first url(...) entry from a CSS cursor value, e.g.:
-// url("data:image/svg+xml,...") 12 12, alias
-const parseUrlCursor = (cursor: string): UrlCursor | null => {
- const match = cursor.match(
- /^url\(["']([^"']+)["']\)\s+(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)/,
- );
- if (!match) return null;
- return {
- url: match[1],
- hotspotX: Number(match[2]),
- hotspotY: Number(match[3]),
- };
-};
-
-const getNormalizedCursor = (cursor: string) => {
- return cursor.split(',').at(-1)?.trim().toLowerCase() ?? 'auto';
-};
-
-const getMacCursorFilename = (cursor: string) => {
- return (
- macCursorFilenameByCssValue[getNormalizedCursor(cursor)] ?? 'default.svg'
- );
-};
-
-const getMacCursorHotspot = (filename: string) => {
- const hotspot = macCursorHotspotByFilename[filename];
-
- if (!hotspot) {
- throw new Error(`Missing hotspot for Mac cursor asset: ${filename}`);
- }
-
- return hotspot;
-};
-
-const findCursorAtTime = (
- mouseMovements: readonly MouseMovement[],
- timeInSeconds: number,
-) => {
- let low = 0;
- let high = mouseMovements.length - 1;
- let latest: MouseMovement | null = null;
-
- while (low <= high) {
- const middle = Math.floor((low + high) / 2);
- const movement = mouseMovements[middle];
-
- if (movement.timeInSeconds <= timeInSeconds) {
- latest = movement;
- low = middle + 1;
- } else {
- high = middle - 1;
- }
- }
-
- return latest;
-};
-
-const CursorImg: React.FC<{
- readonly src: string;
- readonly hotspotX: number;
- readonly hotspotY: number;
- readonly cursorScale: number;
-}> = ({src, hotspotX, hotspotY, cursorScale}) => {
- return (
- <Img
- src={src}
- style={{
- display: 'block',
- height: 32,
- marginLeft: -hotspotX,
- marginTop: -hotspotY,
- transformOrigin: `${hotspotX}px ${hotspotY}px`,
- width: 32,
- position: 'absolute',
- scale: cursorScale,
- }}
- from={-64}
- />
- );
-};
-
-export const CursorGlyph: React.FC<{
- readonly cursor: string;
- readonly scale: number;
- readonly cursorScale: number;
-}> = ({cursor, scale: _scale, cursorScale}) => {
- const urlCursor = parseUrlCursor(cursor);
-
- if (urlCursor) {
- return (
- <CursorImg
- src={urlCursor.url}
- hotspotX={urlCursor.hotspotX}
- hotspotY={urlCursor.hotspotY}
- cursorScale={cursorScale}
- />
- );
- }
-
- const macCursorFilename = getMacCursorFilename(cursor);
- const hotspot = getMacCursorHotspot(macCursorFilename);
-
- return (
- <CursorImg
- src={resolveCursorAsset(CURSOR_ASSET_BASE_PATH, macCursorFilename)}
- hotspotX={hotspot.x}
- hotspotY={hotspot.y}
- cursorScale={cursorScale}
- />
- );
-};
-
-const CLICK_SCALE = 0.9;
-
-const isPointerDown = (
- pointerClicks: readonly PointerClick[] | undefined,
- timeInSeconds: number,
-) => {
- if (!pointerClicks) {
- return false;
- }
-
- let down = false;
- for (const click of pointerClicks) {
- if (click.timeInSeconds > timeInSeconds) {
- break;
- }
-
- down = click.type === 'pointer-down';
- }
-
- return down;
-};
-
-const CursorOverlay: React.FC<{
- readonly cursorData: CursorRecording;
- readonly cursorScale: number;
-}> = ({cursorData, cursorScale}) => {
+export const CanvasCapturePreview = () => {
const frame = useCurrentFrame();
- const {fps} = useVideoConfig();
- const timeInSeconds = frame / fps;
- const cursor = findCursorAtTime(cursorData.mouseMovements, timeInSeconds);
-
- if (!cursor || cursor.canvasX === null || cursor.canvasY === null) {
- return null;
- }
-
- const scale = cursorData.captureMetadata.density;
- const clickScale = isPointerDown(cursorData.pointerClicks, timeInSeconds)
- ? CLICK_SCALE
- : 1;
- const x = cursor.canvasX;
- const y = cursor.canvasY;
return (
- <div
- style={{
- position: 'absolute',
- left: 0,
- top: 0,
- transform: `translate(${x}px, ${y}px) scale(${clickScale})`,
- pointerEvents: 'none',
- height: 32,
- width: 32,
- }}
- >
- <CursorGlyph
- cursor={cursor.cursor}
- scale={scale}
- cursorScale={cursorScale}
+ <AbsoluteFill>
+ <Video
+ src={staticFile('remotion-capture-editor-starter.mp4')}
+ style={{
+ position: 'absolute',
+ }}
+ />
+ <MacOSCursor
+ cursor={interpolate(
+ frame,
+ [6, 64, 68, 99, 164, 166],
+ ['default', 'auto', 'pointer', 'e-resize', 'auto', 'default'],
+ {
+ easing: Easing.step1,
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ },
+ )}
+ style={{
+ position: 'absolute',
+ left: 0,
+ top: 0,
+ scale: interpolate(
+ frame,
+ [0, 79, 82, 110, 161],
+ [6, 5.4, 6, 5.4, 6],
+ {
+ easing: Easing.step1,
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ },
+ ),
+ translate: interpolate(
+ frame,
+ [
+ 6, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 83,
+ 84, 85, 86, 87, 88, 89, 90, 91, 92, 97, 98, 99, 100, 114, 115,
+ 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128,
+ 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
+ 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 162, 163,
+ 164, 165, 166, 167,
+ ],
+ [
+ '-2016.9375px -1677.375px',
+ '-2016.9375px -1677.375px',
+ '1813.96875px 948.3515625px',
+ '1784.15625px 916.828125px',
+ '1703.2734375px 833.9765625px',
+ '1571.3203125px 718.875px',
+ '1540.0546875px 674.390625px',
+ '1537.40625px 647.2734375px',
+ '1528.7109375px 533.8125px',
+ '1505.953125px 496.6875px',
+ '1500.46875px 484.7109375px',
+ '1498.0078125px 481.359375px',
+ '1498.0078125px 481.359375px',
+ '1497.7734375px 478.7109375px',
+ '1496.4609375px 473.90625px',
+ '1496.2734375px 473.53125px',
+ '1496.2734375px 473.53125px',
+ '1487.0625px 472.4296875px',
+ '1450.828125px 469.546875px',
+ '1429.9453125px 468.4453125px',
+ '1414.171875px 468.4453125px',
+ '1367.4609375px 469.2421875px',
+ '1335.4921875px 471.3984375px',
+ '1313.53125px 472.171875px',
+ '1299.140625px 472.171875px',
+ '1297.828125px 472.453125px',
+ '1297.828125px 472.453125px',
+ '1290.65625px 472.453125px',
+ '1270.8515625px 473.296875px',
+ '1266px 473.296875px',
+ '1266px 473.296875px',
+ '1233.421875px 470.6953125px',
+ '1222.7578125px 470.15625px',
+ '1147.1953125px 470.15625px',
+ '1139.8125px 470.15625px',
+ '1118.4375px 470.15625px',
+ '1096.40625px 470.15625px',
+ '1049.6484375px 470.15625px',
+ '1002.8203125px 470.15625px',
+ '971.859375px 470.0390625px',
+ '954.140625px 469.3359375px',
+ '937.21875px 469.0546875px',
+ '926.34375px 468.609375px',
+ '916.6171875px 468.609375px',
+ '910.875px 468.0234375px',
+ '910.875px 468.0234375px',
+ '916.4296875px 468.796875px',
+ '934.125px 469.640625px',
+ '978.328125px 471.1640625px',
+ '1022.765625px 473.6015625px',
+ '1069.78125px 474.5390625px',
+ '1087.546875px 474.609375px',
+ '1142.390625px 475.59375px',
+ '1149.4453125px 475.0546875px',
+ '1203px 473.5546875px',
+ '1244.15625px 473.625px',
+ '1274.4609375px 474.9609375px',
+ '1297.2421875px 474.9609375px',
+ '1332px 474.9609375px',
+ '1379.3203125px 473.90625px',
+ '1419.75px 473.90625px',
+ '1432.2421875px 473.90625px',
+ '1452.796875px 473.90625px',
+ '1488.3046875px 474.6796875px',
+ '1499.2265625px 474.6796875px',
+ '1515.0703125px 475.9453125px',
+ '1544.1796875px 477.234375px',
+ '1553.53125px 477.5390625px',
+ '1555.2421875px 477.5390625px',
+ '1555.2421875px 477.5390625px',
+ '1550.8125px 477.5390625px',
+ '1473.4453125px 451.6171875px',
+ '1317.140625px 374.5078125px',
+ '-4.3828125px -360.3046875px',
+ '-2614.3125px -2067.7265625px',
+ ],
+ {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ },
+ ),
+ }}
/>
- </div>
+ </AbsoluteFill>
);
};
-const CAPTURE_METADATA_TAG_KEY = 'REMOTION_CAPTURE_DATA';
-
-export const calculateCanvasCapturePreviewMetadata: CalculateMetadataFunction<
- CanvasCapturePreviewProps
-> = async ({props}) => {
- const fps = 30;
- const videoSrc = props.videoFile;
-
- const input = new Input({
- formats: ALL_FORMATS,
- source: new UrlSource(videoSrc, {
- getRetryDelay: () => null,
- }),
- });
-
- const [durationInSeconds, videoTrack, tags] = await Promise.all([
- input.computeDuration(),
- input.getPrimaryVideoTrack(),
- input.getMetadataTags(),
- ]);
-
- const dimensions = videoTrack
- ? {
- width: await videoTrack.getDisplayWidth(),
- height: await videoTrack.getDisplayHeight(),
- }
- : null;
-
- const rawCaptureData = tags.raw?.[CAPTURE_METADATA_TAG_KEY];
- const cursorData =
- typeof rawCaptureData === 'string'
- ? (JSON.parse(rawCaptureData) as CursorRecording)
- : null;
-
- if (!dimensions) {
- throw new Error('Could not determine canvas capture video dimensions.');
- }
-
- return {
- width: dimensions.width,
- height: dimensions.height,
- durationInFrames: Math.ceil(durationInSeconds * fps),
- fps,
- defaultCodec: 'prores',
- defaultProResProfile: '4444',
- defaultPixelFormat: 'yuva444p10le',
- defaultVideoImageFormat: 'png',
- props: {
- ...props,
- cursorData,
- width: dimensions.width,
- height: dimensions.height,
- },
- };
-};
-
-export const CanvasCapturePreview: React.FC<CanvasCapturePreviewProps> = ({
- cursorData,
- cursorScale,
- videoFile,
- width,
- height,
- hidden,
-}) => {
- const showScreen = hidden !== 'screen';
- const showCursor = hidden !== 'cursor';
-
+export const CanvasCaptureComposition = () => {
return (
- <AbsoluteFill>
- {showScreen ? (
- <Video
- src={videoFile}
- style={{
- width: width!,
- height: height!,
- }}
- />
- ) : null}
- {showCursor && cursorData ? (
- <CursorOverlay cursorData={cursorData} cursorScale={cursorScale} />
- ) : null}
- </AbsoluteFill>
+ <Composition
+ id="canvas-capture-promo"
+ component={CanvasCapturePreview}
+ width={1920}
+ height={1080}
+ fps={60}
+ durationInFrames={500}
+ />
);
};
diff --git a/packages/brand/src/Root.tsx b/packages/brand/src/Root.tsx
index 8d3f9859ee..f036b33bf6 100644
--- a/packages/brand/src/Root.tsx
+++ b/packages/brand/src/Root.tsx
@@ -14,11 +14,7 @@ import {
import {Banner} from './Brand/Banner';
import {Comp} from './Brand/Composition';
import {TriangleDemo} from './Brand/TriangleToSquare';
-import {
- CanvasCapturePreview,
- calculateCanvasCapturePreviewMetadata,
- canvasCapturePreviewSchema,
-} from './CanvasCapturePreview';
+import {CanvasCaptureComposition} from './CanvasCapturePreview';
import {
WhatIsRemotion,
whatIsRemotionCalculateMetadata,
@@ -435,23 +431,7 @@ export const RemotionRoot: React.FC = () => {
defaultProps={htmlInCanvasAllEffectsDefaultProps}
calculateMetadata={calculateHtmlInCanvasAllEffectsMetadata}
/>
- <Composition
- id="canvas-capture-promo"
- component={CanvasCapturePreview}
- width={1080}
- height={1080}
- fps={30}
- durationInFrames={120}
- defaultProps={{
- videoFile: staticFile('remotion-studio-canvas-recording.webm'),
- cursorScale: 2.5,
- hidden: null,
- width: null,
- height: null,
- }}
- schema={canvasCapturePreviewSchema}
- calculateMetadata={calculateCanvasCapturePreviewMetadata}
- />
+ <CanvasCaptureComposition />
<Composition
id="canvas-capture-new-sticker"
component={NewSticker}
diff --git a/packages/brand/src/ShipCard.tsx b/packages/brand/src/ShipCard.tsx
index 14731000e8..3a4d8e1025 100644
--- a/packages/brand/src/ShipCard.tsx
+++ b/packages/brand/src/ShipCard.tsx
@@ -1,6 +1,7 @@
import {grayscale} from '@remotion/effects/grayscale';
import {pixelDissolve} from '@remotion/effects/pixel-dissolve';
import {fontFamily, loadFont} from '@remotion/google-fonts/GeistMono';
+import {MacOSCursor} from '@remotion/mac-cursors';
import React from 'react';
import {
Easing,
@@ -11,7 +12,6 @@ import {
staticFile,
useCurrentFrame,
} from 'remotion';
-import {CursorGlyph} from './CanvasCapturePreview';
import {
EffectHeader,
EffectProperties,
@@ -421,7 +421,7 @@ const ShowcaseCursor: React.FC<{
transform: `translate(${point.x}px, ${point.y}px) scale(${clickScale})`,
}}
>
- <CursorGlyph cursor={getCursor(frame)} scale={1} cursorScale={2.5} />
+ <MacOSCursor cursor={getCursor(frame)} style={{scale: 2.5}} />
</div>
);
};
diff --git a/packages/brand/src/effects/CornerPinEffectShowcase.tsx b/packages/brand/src/effects/CornerPinEffectShowcase.tsx
index ea5ce84af6..039943ec61 100644
--- a/packages/brand/src/effects/CornerPinEffectShowcase.tsx
+++ b/packages/brand/src/effects/CornerPinEffectShowcase.tsx
@@ -1,4 +1,5 @@
import {cornerPin} from '@remotion/effects/corner-pin';
+import {MacOSCursor} from '@remotion/mac-cursors';
import React from 'react';
import {
AbsoluteFill,
@@ -9,7 +10,6 @@ import {
staticFile,
useCurrentFrame,
} from 'remotion';
-import {CursorGlyph} from '../CanvasCapturePreview';
import {
EffectHeader,
EffectProperties,
@@ -356,7 +356,7 @@ const ShowcaseCursor: React.FC<{
transform: `translate(${point.x}px, ${point.y}px) scale(${clickScale})`,
}}
>
- <CursorGlyph cursor="default" scale={1} cursorScale={2.5} />
+ <MacOSCursor cursor="default" style={{scale: 2.5}} />
</div>
);
};
diff --git a/packages/brand/src/effects/FxIconComposition.tsx b/packages/brand/src/effects/FxIconComposition.tsx
index 893f27497a..b18dcc7435 100644
--- a/packages/brand/src/effects/FxIconComposition.tsx
+++ b/packages/brand/src/effects/FxIconComposition.tsx
@@ -1,3 +1,4 @@
+import {MacOSCursor} from '@remotion/mac-cursors';
import React from 'react';
import {
AbsoluteFill,
@@ -6,7 +7,6 @@ import {
useCurrentFrame,
useVideoConfig,
} from 'remotion';
-import {CursorGlyph} from '../CanvasCapturePreview';
const TOGGLE_SIZE = 140;
const ICON_SIZE = (TOGGLE_SIZE / 36) * 31;
@@ -113,7 +113,7 @@ export const FxIconComposition: React.FC = () => {
width: 32,
}}
>
- <CursorGlyph cursor="default" scale={1} cursorScale={3.25} />
+ <MacOSCursor cursor="default" style={{scale: 3.25}} />
</div>
</AbsoluteFill>
);
diff --git a/packages/brand/src/effects/PatternEffectShowcase.tsx b/packages/brand/src/effects/PatternEffectShowcase.tsx
index 47942379c9..8cf6eef6cc 100644
--- a/packages/brand/src/effects/PatternEffectShowcase.tsx
+++ b/packages/brand/src/effects/PatternEffectShowcase.tsx
@@ -1,4 +1,5 @@
import {pattern} from '@remotion/effects/pattern';
+import {MacOSCursor} from '@remotion/mac-cursors';
import React from 'react';
import {
Easing,
@@ -9,7 +10,6 @@ import {
staticFile,
useCurrentFrame,
} from 'remotion';
-import {CursorGlyph} from '../CanvasCapturePreview';
import {
EffectHeader,
EffectProperties,
@@ -236,7 +236,7 @@ const ShowcaseCursor: React.FC<{
transform: `translate(${point.x}px, ${point.y}px) scale(${clickScale})`,
}}
>
- <CursorGlyph cursor={getCursor(frame)} scale={1} cursorScale={2.5} />
+ <MacOSCursor cursor={getCursor(frame)} style={{scale: 2.5}} />
</div>
);
};
diff --git a/packages/brand/src/effects/StarburstEffectShowcase.tsx b/packages/brand/src/effects/StarburstEffectShowcase.tsx
index 1fadfa7ef8..8a34cbf576 100644
--- a/packages/brand/src/effects/StarburstEffectShowcase.tsx
+++ b/packages/brand/src/effects/StarburstEffectShowcase.tsx
@@ -1,5 +1,6 @@
import {halftone} from '@remotion/effects/halftone';
import {starburst} from '@remotion/effects/starburst';
+import {MacOSCursor} from '@remotion/mac-cursors';
import React from 'react';
import {
AbsoluteFill,
@@ -8,7 +9,6 @@ import {
interpolate,
useCurrentFrame,
} from 'remotion';
-import {CursorGlyph} from '../CanvasCapturePreview';
const WIDTH = 1080;
const HEIGHT = 1350;
@@ -61,8 +61,6 @@ const ORIGIN_KNOB_RADIUS = 16;
const ORIGIN_KNOB_STROKE_WIDTH = 4;
const CURSOR_IN_FRAME = 0;
const CURSOR_OUT_FRAME = HALFTONE_SHAPE_TWEAK_FRAME + 64;
-const RESIZE_CURSOR_LEAD = 5;
-const RESIZE_CURSOR_HOLD = 12;
const VALUE_DRAG_START_X = 472;
const VALUE_DRAG_END_X = 712;
const STARBURST_TOGGLE_CURSOR_Y = TOP_HEIGHT + EFFECT_HEADER_HEIGHT / 2;
@@ -469,19 +467,6 @@ const isCursorDown = (frame: number) => {
);
};
-const getCursor = (frame: number) => {
- if (
- (frame >= ROTATION_START - RESIZE_CURSOR_LEAD &&
- frame <= ROTATION_START + ROTATION_DURATION + RESIZE_CURSOR_HOLD) ||
- (frame >= HALFTONE_DOT_SIZE_TWEAK_START - RESIZE_CURSOR_LEAD &&
- frame <= HALFTONE_DOT_SIZE_TWEAK_END + RESIZE_CURSOR_HOLD)
- ) {
- return 'resizewesteast';
- }
-
- return 'default';
-};
-
const ShowcaseCursor: React.FC<{
readonly frame: number;
}> = ({frame}) => {
@@ -505,7 +490,19 @@ const ShowcaseCursor: React.FC<{
transform: `translate(${point.x}px, ${point.y}px) scale(${clickScale})`,
}}
>
- <CursorGlyph cursor={getCursor(frame)} scale={1} cursorScale={2.5} />
+ <MacOSCursor
+ cursor={interpolate(
+ frame,
+ [0, 193, 283, 339, 453],
+ ['default', 'resizewesteast', 'default', 'resizewesteast', 'default'],
+ {
+ easing: Easing.step1,
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ },
+ )}
+ style={{scale: 2.5}}
+ />
</div>
);
};
diff --git a/packages/convert/app/components/CanvasCaptureCursor.tsx b/packages/convert/app/components/CanvasCaptureCursor.tsx
index 182fe751e2..a1ea70679c 100644
--- a/packages/convert/app/components/CanvasCaptureCursor.tsx
+++ b/packages/convert/app/components/CanvasCaptureCursor.tsx
@@ -37,16 +37,17 @@ export const CanvasCaptureCursor: React.FC<{
>
<MacOSCursor
cursor={cursor.cursor}
- scale={
- cursorData.captureMetadata.density *
- cursorScale *
- (isCanvasCapturePointerDownAtTime(
- cursorData.pointerClicks,
- timeInSeconds,
- )
- ? cursorPressedScale
- : 1)
- }
+ style={{
+ scale:
+ cursorData.captureMetadata.density *
+ cursorScale *
+ (isCanvasCapturePointerDownAtTime(
+ cursorData.pointerClicks,
+ timeInSeconds,
+ )
+ ? cursorPressedScale
+ : 1),
+ }}
/>
</div>
);
diff --git a/packages/core/src/interpolate.ts b/packages/core/src/interpolate.ts
index 5f98128c87..d98971e0c0 100644
--- a/packages/core/src/interpolate.ts
+++ b/packages/core/src/interpolate.ts
@@ -1,3 +1,4 @@
+import {Easing} from './easing.js';
import {normalizeNumber} from './normalize-number.js';
// Taken from https://github.com/facebook/react-native/blob/0b9ea60b4fee8cacc36e7160e31b91fc114dbc0d/Libraries/Animated/src/nodes/AnimatedInterpolation.js
@@ -866,6 +867,86 @@ const interpolateString = ({
});
};
+const interpolateDiscreteString = ({
+ input,
+ inputRange,
+ outputRange,
+ options,
+}: {
+ input: number;
+ inputRange: readonly number[];
+ outputRange: readonly string[];
+ options: InterpolateOptions | undefined;
+}): string => {
+ if (inputRange.length === 1) {
+ return outputRange[0];
+ }
+
+ for (
+ let segmentIndex = 0;
+ segmentIndex < inputRange.length - 1;
+ segmentIndex++
+ ) {
+ if (
+ resolveEasingForSegment({
+ easing: options?.easing,
+ segmentIndex,
+ }) !== Easing.step1
+ ) {
+ throw new TypeError(
+ 'Non-numeric strings can only be interpolated using Easing.step1',
+ );
+ }
+ }
+
+ const posterizedInput =
+ options?.posterize === undefined
+ ? input
+ : Math.floor(input / options.posterize) * options.posterize;
+ const inputMin = inputRange[0];
+ const inputMax = inputRange[inputRange.length - 1];
+ let resolvedInput = posterizedInput;
+
+ if (resolvedInput < inputMin) {
+ if (options?.extrapolateLeft === 'identity') {
+ throw new TypeError(
+ 'extrapolateLeft: "identity" is not supported for non-numeric strings',
+ );
+ }
+
+ if (options?.extrapolateLeft === 'wrap') {
+ const wrapRange = inputMax - inputMin;
+ resolvedInput =
+ ((((resolvedInput - inputMin) % wrapRange) + wrapRange) % wrapRange) +
+ inputMin;
+ } else {
+ return outputRange[0];
+ }
+ }
+
+ if (resolvedInput > inputMax) {
+ if (options?.extrapolateRight === 'identity') {
+ throw new TypeError(
+ 'extrapolateRight: "identity" is not supported for non-numeric strings',
+ );
+ }
+
+ if (options?.extrapolateRight === 'wrap') {
+ const wrapRange = inputMax - inputMin;
+ resolvedInput =
+ ((((resolvedInput - inputMin) % wrapRange) + wrapRange) % wrapRange) +
+ inputMin;
+ } else {
+ return outputRange[outputRange.length - 1];
+ }
+ }
+
+ const range = findRange(resolvedInput, inputRange);
+ return resolvedInput >= inputRange[range + 1]
+ ? outputRange[range + 1]
+ : outputRange[range];
+};
+
const validateTupleOutputRange = (
outputRange: readonly (readonly unknown[])[],
): number => {
@@ -1104,7 +1185,37 @@ export function interpolate(
);
}
- return interpolateString({input, inputRange, outputRange, options});
+ try {
+ return interpolateString({input, inputRange, outputRange, options});
+ } catch (error) {
+ if (!outputRange.every((output) => typeof output === 'string')) {
+ throw error;
+ }
+
+ const hasNonNumericString = outputRange.some((output) => {
+ try {
+ parseStringInterpolationValue(output);
+ return false;
+ } catch (parseError) {
+ return (
+ parseError instanceof TypeError &&
+ parseError.message.includes(
+ 'not a supported scale, translate, or rotate value',
+ )
+ );
+ }
+ });
+ if (!hasNonNumericString) {
+ throw error;
+ }
+
+ return interpolateDiscreteString({
+ input,
+ inputRange,
+ outputRange,
+ options,
+ });
+ }
}
if (outputRange.every((output) => Array.isArray(output))) {
diff --git a/packages/core/src/test/drag-override-value.test.ts b/packages/core/src/test/drag-override-value.test.ts
index 601631d9dc..f07a1f0bf9 100644
--- a/packages/core/src/test/drag-override-value.test.ts
+++ b/packages/core/src/test/drag-override-value.test.ts
@@ -114,6 +114,32 @@ test('makeKeyframedDragOverride uses linear easing outside the keyframe range',
});
});
+test('makeKeyframedDragOverride can use hold easing outside the keyframe range', () => {
+ const status: CanUpdateSequencePropStatusKeyframed = {
+ ...makeKeyframedStatus(),
+ keyframes: [{frame: 0, value: 'default'}],
+ easing: [],
+ };
+ const override = makeKeyframedDragOverride({
+ status,
+ frame: 60,
+ value: 'ne-resize',
+ defaultEasing: {type: 'step1'},
+ });
+
+ expect(override).toEqual({
+ type: 'keyframed',
+ status: {
+ ...status,
+ keyframes: [
+ {frame: 0, value: 'default'},
+ {frame: 60, value: 'ne-resize'},
+ ],
+ easing: [{type: 'step1'}],
+ },
+ });
+});
+
test('makeKeyframedDragOverride replaces an existing keyframe without changing easing length', () => {
const override = makeKeyframedDragOverride({
status: makeKeyframedStatus(),
diff --git a/packages/core/src/test/interpolate-keyframed-status.test.ts b/packages/core/src/test/interpolate-keyframed-status.test.ts
index f731ff4a6e..c9f76dd136 100644
--- a/packages/core/src/test/interpolate-keyframed-status.test.ts
+++ b/packages/core/src/test/interpolate-keyframed-status.test.ts
@@ -52,6 +52,36 @@ test('holds the previous keyframe value until the segment ends', () => {
).toBe(100);
});
+test('holds non-numeric string keyframes until the segment ends', () => {
+ const status: CanUpdateSequencePropStatusKeyframed = {
+ status: 'keyframed',
+ interpolationFunction: 'interpolate',
+ keyframes: [
+ {frame: 0, value: 'default'},
+ {frame: 60, value: 'ne-resize'},
+ ],
+ easing: [{type: 'step1'}],
+ clamping: {left: 'clamp', right: 'clamp'},
+ posterize: undefined,
+ output: undefined,
+ };
+
+ expect(
+ interpolateKeyframedStatus({
+ forceSpringAllowTail: null,
+ frame: 59,
+ status,
+ }),
+ ).toBe('default');
+ expect(
+ interpolateKeyframedStatus({
+ forceSpringAllowTail: null,
+ frame: 60,
+ status,
+ }),
+ ).toBe('ne-resize');
+});
+
test('interpolates numeric keyframes with perceptual-scale output', () => {
const result = interpolateKeyframedStatus({
forceSpringAllowTail: null,
diff --git a/packages/core/src/test/interpolate.test.ts b/packages/core/src/test/interpolate.test.ts
index f75fcdb1e4..cf5ea6f467 100644
--- a/packages/core/src/test/interpolate.test.ts
+++ b/packages/core/src/test/interpolate.test.ts
@@ -46,6 +46,47 @@ test('Can interpolate a single keyframe', () => {
).toBe(9);
});
+test('Can interpolate non-numeric strings in hold mode', () => {
+ expect(
+ interpolate(0, [0, 100, 200], ['default', 'ne-resize', 'pointer'], {
+ easing: [Easing.step1, Easing.step1],
+ }),
+ ).toBe('default');
+ expect(
+ interpolate(99.999, [0, 100, 200], ['default', 'ne-resize', 'pointer'], {
+ easing: [Easing.step1, Easing.step1],
+ }),
+ ).toBe('default');
+ expect(
+ interpolate(100, [0, 100, 200], ['default', 'ne-resize', 'pointer'], {
+ easing: [Easing.step1, Easing.step1],
+ }),
+ ).toBe('ne-resize');
+ expect(
+ interpolate(200, [0, 100, 200], ['default', 'ne-resize', 'pointer'], {
+ easing: [Easing.step1, Easing.step1],
+ }),
+ ).toBe('pointer');
+});
+
+test('Non-numeric strings require hold mode', () => {
+ expectToThrow(
+ () => interpolate(50, [0, 100], ['default', 'ne-resize']),
+ /Non-numeric strings can only be interpolated using Easing\.step1/,
+ );
+ expectToThrow(
+ () =>
+ interpolate(50, [0, 100], ['default', 'ne-resize'], {
+ easing: Easing.linear,
+ }),
+ /Non-numeric strings can only be interpolated using Easing\.step1/,
+ );
+});
+
+test('A single non-numeric string keyframe does not require easing', () => {
+ expect(interpolate(100, [20], ['default'])).toBe('default');
+});
+
test('Easing array with one keyframe accepts no entries', () => {
expect(
interpolate(0.5, [0], [1], {
diff --git a/packages/core/src/use-schema.ts b/packages/core/src/use-schema.ts
index 12af8b2277..93f033b05b 100644
--- a/packages/core/src/use-schema.ts
+++ b/packages/core/src/use-schema.ts
@@ -182,10 +182,12 @@ export const makeKeyframedDragOverride = ({
status,
frame,
value,
+ defaultEasing = DEFAULT_LINEAR_EASING,
}: {
status: CanUpdateSequencePropStatusKeyframed;
frame: number;
value: unknown;
+ defaultEasing?: CanUpdateSequencePropStatusEasing;
}): DragOverrideValue => {
const existingIndex = status.keyframes.findIndex(
(keyframe) => keyframe.frame === frame,
@@ -210,13 +212,13 @@ export const makeKeyframedDragOverride = ({
});
const easingToDuplicate =
easingIndexToDuplicate === null
- ? DEFAULT_LINEAR_EASING
+ ? defaultEasing
: easing[easingIndexToDuplicate];
easing.splice(insertedKeyframeIndex, 0, easingToDuplicate);
}
while (easing.length < keyframes.length - 1) {
- easing.push(DEFAULT_LINEAR_EASING);
+ easing.push(defaultEasing);
}
if (easing.length > keyframes.length - 1) {
diff --git a/packages/docs/docs/interactivity-schema.mdx b/packages/docs/docs/interactivity-schema.mdx
index 454ebc8200..67ba5a8071 100644
--- a/packages/docs/docs/interactivity-schema.mdx
+++ b/packages/docs/docs/interactivity-schema.mdx
@@ -237,7 +237,9 @@ Controls whether the field can be animated with keyframes.
Default: `true` for `number`, `boolean`, `rotation-css`, `rotation-degrees`, `translate`, `transform-origin`, `scale`, `uv-coordinate` and `color` fields.
-`array`, `enum` and `font-family` fields are not keyframable. Fields inside an `enum` variant schema can still be keyframed according to their own `keyframable` setting.
+`array` and `font-family` fields are not keyframable. Fields inside an `enum` variant schema can still be keyframed according to their own `keyframable` setting.
+
+`enum` fields are not keyframable by default. From <AvailableFrom v="4.0.509" inline />, set `keyframable: true` to enable hold keyframes. Remotion Studio generates [`Easing.step1`](/docs/easing#step1) segments because enum values cannot be blended.
Set `keyframable: false` on a keyframable field to show a static control.
diff --git a/packages/docs/docs/interpolate.mdx b/packages/docs/docs/interpolate.mdx
index b4d775adc5..d9ae4bb7b0 100644
--- a/packages/docs/docs/interpolate.mdx
+++ b/packages/docs/docs/interpolate.mdx
@@ -166,6 +166,21 @@ All values in one interpolation must have the same type.
For each component, units must match.
For missing dimensions, CSS defaults are used: scale defaults to `1`, translate and rotate default to `0`, and transform origin defaults to `50% 50% 0`.
+## Example: Discrete string values<AvailableFrom v="4.0.509" />
+
+Use `Easing.step1` to switch between strings that cannot be blended. The previous value is held until the next keyframe.
+
+```tsx twoslash title="MyComposition.tsx"
+import {Easing, interpolate, useCurrentFrame} from 'remotion';
+
+const frame = useCurrentFrame();
+const cursor = interpolate(frame, [0, 100], ['default', 'ne-resize'], {
+ easing: Easing.step1,
+});
+```
+
+Every segment must use `Easing.step1`. If `easing` is an array, each entry must be `Easing.step1`.
+
## Example: Numeric tuples<AvailableFrom v="4.0.473" />
`outputRange` may contain numeric tuples.
diff --git a/packages/docs/docs/studio/interactivity.mdx b/packages/docs/docs/studio/interactivity.mdx
index 2f4e77910f..5d605649da 100644
--- a/packages/docs/docs/studio/interactivity.mdx
+++ b/packages/docs/docs/studio/interactivity.mdx
@@ -62,6 +62,7 @@ To make a custom component selectable and editable, see [Make a component intera
Studio can edit easing segments when the [`interpolate()`](/docs/interpolate) or [`interpolateColors()`](/docs/interpolate-colors) `easing` option is inline and uses one of these expressions:
- [`Easing.linear`](/docs/easing#linear)
+- [`Easing.step1`](/docs/easing#step1)<AvailableFrom v="4.0.509" inline />
- [`Easing.bezier(x1, y1, x2, y2)`](/docs/easing#bezier) with numeric arguments
- [`Easing.spring()`](/docs/easing#spring) with an inline static config
- Exact Bezier-compatible helpers<AvailableFrom v="4.0.487" inline />: [`Easing.ease`](/docs/easing#ease), [`Easing.quad`](/docs/easing#quad), [`Easing.cubic`](/docs/easing#cubic), [`Easing.back()`](/docs/easing#back), `Easing.back(s)` with a numeric argument, `Easing.poly(1)`, `Easing.poly(2)` and `Easing.poly(3)`
diff --git a/packages/example/src/MacCursors/index.tsx b/packages/example/src/MacCursors/index.tsx
index cc0272caaf..43a07cefaa 100644
--- a/packages/example/src/MacCursors/index.tsx
+++ b/packages/example/src/MacCursors/index.tsx
@@ -1,19 +1,25 @@
import {MacOSCursor} from '@remotion/mac-cursors';
import React from 'react';
-import {AbsoluteFill} from 'remotion';
+import {AbsoluteFill, Easing, interpolate, useCurrentFrame} from 'remotion';
const customCursor = `url("data:image/svg+xml,${encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><circle cx="16" cy="16" r="13" fill="#0b84ff" stroke="white" stroke-width="4"/></svg>',
)}") 16 16, auto`;
export const MacCursorsExample: React.FC = () => {
+ const frame = useCurrentFrame();
+
return (
<AbsoluteFill style={{backgroundColor: '#ddd'}}>
- <MacOSCursor cursor="pointer" scale={4} style={{left: 350, top: 540}} />
+ <MacOSCursor cursor="pointer" style={{left: 350, top: 540, scale: 4}} />
<MacOSCursor
- cursor={customCursor}
- scale={4}
- style={{left: 730, top: 540}}
+ cursor={interpolate(frame, [0, 45], ['pointer', 'custom'], {
+ easing: Easing.step1,
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ })}
+ customCursor={customCursor}
+ style={{left: 730, top: 540, scale: 4}}
/>
</AbsoluteFill>
);
diff --git a/packages/mac-cursors/src/MacOSCursor.tsx b/packages/mac-cursors/src/MacOSCursor.tsx
index 0292b07916..a6217baca3 100644
--- a/packages/mac-cursors/src/MacOSCursor.tsx
+++ b/packages/mac-cursors/src/MacOSCursor.tsx
@@ -1,41 +1,113 @@
import type {CSSProperties} from 'react';
import React from 'react';
-import {Img} from 'remotion';
-import {resolveCursor} from './resolve-cursor';
+import type {
+ InteractiveBaseProps,
+ InteractivitySchema,
+ SequenceControls,
+} from 'remotion';
+import {Img, Interactive, Sequence} from 'remotion';
+import {macOSCursorNames, resolveCursor} from './resolve-cursor';
-export type MacOSCursorProps = {
+export type MacOSCursorProps = InteractiveBaseProps & {
readonly cursor: string;
- readonly scale?: number;
+ readonly customCursor?: string;
readonly className?: string;
readonly style?: CSSProperties;
};
-export const MacOSCursor: React.FC<MacOSCursorProps> = ({
+export const macOSCursorSchema = {
+ cursor: {
+ type: 'enum',
+ default: 'default',
+ description: 'Cursor',
+ keyframable: true,
+ variants: Object.assign(
+ Object.fromEntries<InteractivitySchema>(
+ macOSCursorNames.map((cursor) => [cursor, {}]),
+ ),
+ {
+ custom: {
+ customCursor: {
+ type: 'text-content',
+ default: '',
+ description: 'Custom cursor',
+ keyframable: false,
+ },
+ },
+ },
+ ),
+ },
+ ...Interactive.transformSchema,
+} as const satisfies InteractivitySchema;
+
+const MacOSCursorInner: React.FC<
+ MacOSCursorProps & {readonly controls: SequenceControls | undefined}
+> = ({
cursor,
- scale = 1,
+ customCursor,
className,
style,
+ durationInFrames,
+ from,
+ trimBefore,
+ freeze,
+ hidden,
+ name,
+ showInTimeline,
+ controls,
}) => {
- const resolved = resolveCursor(cursor);
- if (!resolved) {
- return null;
- }
+ const resolved =
+ cursor === 'custom'
+ ? customCursor
+ ? resolveCursor(customCursor)
+ : null
+ : resolveCursor(cursor);
+ const refForOutline = React.useRef<HTMLImageElement | null>(null);
return (
- <Img
- className={className}
- src={resolved.src}
- style={{
- display: 'block',
- position: 'absolute',
- width: resolved.width ?? undefined,
- height: resolved.height ?? undefined,
- marginLeft: -resolved.hotspot.x,
- marginTop: -resolved.hotspot.y,
- transformOrigin: `${resolved.hotspot.x}px ${resolved.hotspot.y}px`,
- scale,
- ...style,
- }}
- />
+ <Sequence
+ layout="none"
+ from={from ?? 0}
+ trimBefore={trimBefore}
+ durationInFrames={durationInFrames ?? Infinity}
+ freeze={freeze}
+ hidden={hidden}
+ name={name ?? '<MacOSCursor>'}
+ showInTimeline={showInTimeline ?? true}
+ controls={controls}
+ outlineRef={refForOutline}
+ >
+ {resolved ? (
+ <Img
+ ref={refForOutline}
+ className={className}
+ src={resolved.src}
+ showInTimeline={false}
+ style={{
+ display: 'block',
+ position: 'absolute',
+ width: resolved.width ?? undefined,
+ height: resolved.height ?? undefined,
+ marginLeft: -resolved.hotspot.x,
+ marginTop: -resolved.hotspot.y,
+ transformOrigin: `${resolved.hotspot.x}px ${resolved.hotspot.y}px`,
+ ...style,
+ }}
+ />
+ ) : null}
+ </Sequence>
);
};
+
+export const MacOSCursor = Interactive.withSchema({
+ Component: MacOSCursorInner,
+ componentName: '<MacOSCursor>',
+ componentIdentity: Interactive._internalMakeRemotionComponentIdentity({
+ packageName: '@remotion/mac-cursors',
+ componentName: 'MacOSCursor',
+ }),
+ schema: macOSCursorSchema,
+ supportsEffects: false,
+}) as React.FC<MacOSCursorProps>;
+
+MacOSCursor.displayName = 'MacOSCursor';
diff --git a/packages/mac-cursors/src/index.ts b/packages/mac-cursors/src/index.ts
index c8b90b1106..93a1d64325 100644
--- a/packages/mac-cursors/src/index.ts
+++ b/packages/mac-cursors/src/index.ts
@@ -1,4 +1,4 @@
-export {MacOSCursor} from './MacOSCursor';
+export {MacOSCursor, macOSCursorSchema} from './MacOSCursor';
export type {MacOSCursorProps} from './MacOSCursor';
-export {resolveCursor} from './resolve-cursor';
+export {macOSCursorNames, resolveCursor} from './resolve-cursor';
export type {ResolvedCursor} from './resolve-cursor';
diff --git a/packages/mac-cursors/src/resolve-cursor.ts b/packages/mac-cursors/src/resolve-cursor.ts
index 77d33ffc33..e46d698def 100644
--- a/packages/mac-cursors/src/resolve-cursor.ts
+++ b/packages/mac-cursors/src/resolve-cursor.ts
@@ -83,6 +83,8 @@ const macCursorFilenameByCssValue: Record<string, string | null> = {
'zoom-out': 'zoomout.svg',
};
+export const macOSCursorNames = Object.keys(macCursorFilenameByCssValue);
+
const macCursorHotspotByFilename: Record<string, CursorHotspot> = {
'beachball.svg': {x: 16, y: 16},
'busy.svg': {x: 8, y: 3},
diff --git a/packages/mac-cursors/src/test/resolve-cursor.test.ts b/packages/mac-cursors/src/test/resolve-cursor.test.ts
index 47f294d444..042ae093fa 100644
--- a/packages/mac-cursors/src/test/resolve-cursor.test.ts
+++ b/packages/mac-cursors/src/test/resolve-cursor.test.ts
@@ -1,4 +1,5 @@
import {expect, test} from 'bun:test';
+import {macOSCursorSchema} from '../MacOSCursor';
import {resolveCursor} from '../resolve-cursor';
test('resolves named, custom, hidden, and unknown cursors', () => {
@@ -20,3 +21,20 @@ test('resolves named, custom, hidden, and unknown cursors', () => {
expect(resolveCursor('none')).toBeNull();
expect(resolveCursor('not-a-real-cursor')?.hotspot).toEqual({x: 10, y: 9});
});
+
+test('cursor schema exposes named cursors as a keyframable enum', () => {
+ expect(macOSCursorSchema.cursor.keyframable).toBe(true);
+ expect(macOSCursorSchema.cursor.variants.default).toEqual({});
+ expect(macOSCursorSchema.cursor.variants['ne-resize']).toEqual({});
+ expect(macOSCursorSchema.cursor.variants.custom).toEqual({
+ customCursor: {
+ type: 'text-content',
+ default: '',
+ description: 'Custom cursor',
+ keyframable: false,
+ },
+ });
+ expect(macOSCursorSchema['style.translate'].type).toBe('translate');
+ expect(macOSCursorSchema['style.scale'].type).toBe('scale');
+ expect(macOSCursorSchema['style.rotate'].type).toBe('rotation-css');
+});
diff --git a/packages/studio-server/src/canvas-capture/generate-canvas-capture-composition.ts b/packages/studio-server/src/canvas-capture/generate-canvas-capture-composition.ts
new file mode 100644
index 0000000000..ccc2343323
--- /dev/null
+++ b/packages/studio-server/src/canvas-capture/generate-canvas-capture-composition.ts
@@ -0,0 +1,222 @@
+import type {CanvasCaptureData} from '@remotion/studio-shared';
+import {formatOutput} from '../codemods/duplicate-composition';
+
+type FramedMouseMovement = CanvasCaptureData['mouseMovements'][number] & {
+ readonly frame: number;
+};
+
+const customCursorRegex = /^\s*url\(/;
+
+const collapseMouseMovementsByFrame = ({
+ data,
+ keyframeFps,
+}: {
+ readonly data: CanvasCaptureData;
+ readonly keyframeFps: number;
+}) => {
+ const movements: FramedMouseMovement[] = [];
+
+ for (const movement of data.mouseMovements) {
+ if (movement.canvasX === null || movement.canvasY === null) {
+ continue;
+ }
+
+ const framedMovement = {
+ ...movement,
+ frame: Math.ceil(movement.timeInSeconds * keyframeFps),
+ };
+ const previous = movements.at(-1);
+ if (previous?.frame === framedMovement.frame) {
+ movements[movements.length - 1] = framedMovement;
+ } else {
+ movements.push(framedMovement);
+ }
+ }
+
+ return movements;
+};
+
+const getCursorName = (cursor: string) => {
+ if (customCursorRegex.test(cursor)) {
+ return 'custom';
+ }
+
+ return cursor.split(',').at(-1)?.trim().toLowerCase() || 'default';
+};
+
+const serialize = (value: unknown) => JSON.stringify(value);
+
+export const generateCanvasCaptureComposition = ({
+ componentName,
+ compositionId,
+ data,
+ durationInFrames,
+ fps,
+ height,
+ keyframeFps,
+ videoFileName,
+ width,
+}: {
+ readonly componentName: string;
+ readonly compositionId: string;
+ readonly data: CanvasCaptureData;
+ readonly durationInFrames: number;
+ readonly fps: number;
+ readonly height: number;
+ readonly keyframeFps: number;
+ readonly videoFileName: string;
+ readonly width: number;
+}) => {
+ const movements = collapseMouseMovementsByFrame({data, keyframeFps});
+ if (movements.length === 0) {
+ throw new Error('The Canvas Capture does not contain cursor movements');
+ }
+
+ const cursorKeyframes = movements.reduce<
+ Array<{readonly frame: number; readonly value: string}>
+ >((keyframes, movement) => {
+ const value = getCursorName(movement.cursor);
+ if (keyframes.at(-1)?.value !== value) {
+ keyframes.push({frame: movement.frame, value});
+ }
+
+ return keyframes;
+ }, []);
+
+ const positionKeyframes: Array<{
+ readonly frame: number;
+ readonly value: string;
+ }> = [];
+ for (const movement of movements) {
+ const previous = positionKeyframes.at(-1);
+ if (previous !== undefined && movement.frame - previous.frame > 1) {
+ positionKeyframes.push({
+ frame: movement.frame - 1,
+ value: previous.value,
+ });
+ }
+
+ positionKeyframes.push({
+ frame: movement.frame,
+ value: `${movement.canvasX}px ${movement.canvasY}px`,
+ });
+ }
+
+ const scaleKeyframes = [
+ {frame: 0, value: data.captureMetadata.density},
+ ...data.pointerClicks.map((click) => ({
+ frame: Math.ceil(click.timeInSeconds * keyframeFps),
+ value:
+ click.type === 'pointer-down'
+ ? data.captureMetadata.density * 0.9
+ : data.captureMetadata.density,
+ })),
+ ].reduce<Array<{readonly frame: number; readonly value: number}>>(
+ (keyframes, keyframe) => {
+ if (keyframes.at(-1)?.frame === keyframe.frame) {
+ keyframes[keyframes.length - 1] = keyframe;
+ } else if (keyframes.at(-1)?.value !== keyframe.value) {
+ keyframes.push(keyframe);
+ }
+
+ return keyframes;
+ },
+ [],
+ );
+
+ const customCursor = movements.find((movement) =>
+ customCursorRegex.test(movement.cursor),
+ )?.cursor;
+ const cursorProp =
+ cursorKeyframes.length === 1
+ ? `cursor=${serialize(cursorKeyframes[0].value)}`
+ : `cursor={interpolate(
+ frame,
+ ${serialize(cursorKeyframes.map((keyframe) => keyframe.frame))},
+ ${serialize(cursorKeyframes.map((keyframe) => keyframe.value))},
+ {
+ easing: Easing.step1,
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ },
+ )}`;
+ const scale =
+ scaleKeyframes.length === 1
+ ? serialize(scaleKeyframes[0].value)
+ : `interpolate(
+ frame,
+ ${serialize(scaleKeyframes.map((keyframe) => keyframe.frame))},
+ ${serialize(scaleKeyframes.map((keyframe) => keyframe.value))},
+ {
+ easing: Easing.step1,
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ },
+ )`;
+ const translate =
+ positionKeyframes.length === 1
+ ? serialize(positionKeyframes[0].value)
+ : `interpolate(
+ frame,
+ ${serialize(positionKeyframes.map((keyframe) => keyframe.frame))},
+ ${serialize(positionKeyframes.map((keyframe) => keyframe.value))},
+ {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ },
+ )`;
+
+ const previewComponentName = componentName.endsWith('Composition')
+ ? `${componentName.slice(0, -'Composition'.length)}Preview`
+ : `${componentName}Preview`;
+
+ return formatOutput(`import {MacOSCursor} from '@remotion/mac-cursors';
+import {Video} from '@remotion/media';
+import {
+ AbsoluteFill,
+ Composition,
+ Easing,
+ interpolate,
+ staticFile,
+ useCurrentFrame,
+} from 'remotion';
+
+export const ${previewComponentName} = () => {
+ const frame = useCurrentFrame();
+
+ return (
+ <AbsoluteFill>
+ <Video
+ src={staticFile(${serialize(videoFileName)})}
+ style={{
+ position: 'absolute',
+ }}
+ />
+ <MacOSCursor
+ ${cursorProp}
+${customCursor === undefined ? '' : `\t\t\t\tcustomCursor=${serialize(customCursor)}\n`} style={{
+ position: 'absolute',
+ left: 0,
+ top: 0,
+ scale: ${scale},
+ translate: ${translate},
+ }}
+ />
+ </AbsoluteFill>
+ );
+};
+
+export const ${componentName} = () => {
+ return (
+ <Composition
+ id=${serialize(compositionId)}
+ component={${previewComponentName}}
+ width={${width}}
+ height={${height}}
+ fps={${fps}}
+ durationInFrames={${durationInFrames}}
+ />
+ );
+};
+`);
+};
diff --git a/packages/studio-server/src/codemods/duplicate-composition.ts b/packages/studio-server/src/codemods/duplicate-composition.ts
index 7ef989e616..0e7efa26f8 100644
--- a/packages/studio-server/src/codemods/duplicate-composition.ts
+++ b/packages/studio-server/src/codemods/duplicate-composition.ts
@@ -69,12 +69,15 @@ export const parseAndApplyCodemod = ({
}
if (codeMod.type === 'new-composition') {
- ensureNamedImport({
- ast: newAst,
- importedName: 'Composition',
- sourcePath: 'remotion',
- localName: 'Composition',
- });
+ if (codeMod.canvasCapture === null) {
+ ensureNamedImport({
+ ast: newAst,
+ importedName: 'Composition',
+ sourcePath: 'remotion',
+ localName: 'Composition',
+ });
+ }
+
ensureNamedImport({
ast: newAst,
importedName: codeMod.componentName,
diff --git a/packages/studio-server/src/codemods/recast-mods.ts b/packages/studio-server/src/codemods/recast-mods.ts
index 42eb355dbf..bea4452de4 100644
--- a/packages/studio-server/src/codemods/recast-mods.ts
+++ b/packages/studio-server/src/codemods/recast-mods.ts
@@ -257,6 +257,20 @@ const jsxAttributeWithExpression = (
const newCompositionElement = (
transformation: Extract<RecastCodemod, {type: 'new-composition'}>,
): JSXElement => {
+ if (transformation.canvasCapture !== null) {
+ return {
+ type: 'JSXElement',
+ openingElement: {
+ type: 'JSXOpeningElement',
+ name: jsxId(transformation.componentName),
+ attributes: [],
+ selfClosing: true,
+ },
+ closingElement: null,
+ children: [],
+ };
+ }
+
return {
type: 'JSXElement',
openingElement: {
diff --git a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts
index 6d5901cff2..83a234a136 100644
--- a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts
+++ b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts
@@ -13,7 +13,9 @@ import type {
import {
getKeyframeInterpolationFunction,
getKeyframeInterpolationFunctionForSchemaField,
+ HOLD_KEYFRAME_EASING,
isKeyframeInterpolationFunction,
+ isSchemaFieldHoldOnly,
isSchemaFieldKeyframable,
LINEAR_KEYFRAME_EASING,
type KeyframeInterpolationFunction,
@@ -633,28 +635,30 @@ const normalizeEasingAfterAddingKeyframe = ({
nextSegmentCount,
insertedKeyframeIndex,
nextKeyframeCount,
+ defaultEasing,
}: {
extraArgs: (ExpressionKind | SpreadElementKind)[];
previousSegmentCount: number;
nextSegmentCount: number;
insertedKeyframeIndex: number;
nextKeyframeCount: number;
+ defaultEasing: KeyframeEasing;
}): {
extraArgs: (ExpressionKind | SpreadElementKind)[];
needsEasingImport: boolean;
} => {
- const options = getInlineOptionsFromExtraArgs(extraArgs);
+ const options =
+ getInlineOptionsFromExtraArgs(extraArgs) ??
+ (extraArgs.length === 0 ? createEmptyOptionsExpression() : null);
if (!options) {
return {extraArgs, needsEasingImport: false};
}
- const easing = getExistingEasingArrayOrNull({
- options,
- segmentCount: previousSegmentCount,
- });
- if (easing === null) {
- return {extraArgs, needsEasingImport: false};
- }
+ const easing =
+ getExistingEasingArrayOrNull({
+ options,
+ segmentCount: previousSegmentCount,
+ }) ?? Array.from({length: previousSegmentCount}, () => defaultEasing);
if (easing.length < nextSegmentCount) {
const isSplittingExistingSegment =
@@ -668,18 +672,19 @@ const normalizeEasingAfterAddingKeyframe = ({
insertedKeyframeIndex,
0,
easingIndexToDuplicate === null
- ? LINEAR_KEYFRAME_EASING
+ ? defaultEasing
: easing[easingIndexToDuplicate],
);
}
while (easing.length < nextSegmentCount) {
- easing.push(LINEAR_KEYFRAME_EASING);
+ easing.push(defaultEasing);
}
+ const needsEasingImport = setEasingOption({options, easing});
return {
extraArgs: getExtraArgsWithOptions({extraArgs, options}),
- needsEasingImport: setEasingOption({options, easing}),
+ needsEasingImport,
};
};
@@ -1051,6 +1056,9 @@ const addKeyframe = ({
const newOutput = parseValueExpression(value);
if (existing) {
+ const defaultEasing = isSchemaFieldHoldOnly({schema, key})
+ ? HOLD_KEYFRAME_EASING
+ : LINEAR_KEYFRAME_EASING;
const existingCalleeName =
existing.callee.type === 'Identifier'
? (existing.callee.name as KeyframeInterpolationFunction)
@@ -1091,6 +1099,7 @@ const addKeyframe = ({
.sort((first, second) => first.frame - second.frame)
.findIndex((keyframe) => keyframe.frame === frame),
nextKeyframeCount: nextKeyframes.length,
+ defaultEasing,
})
: {extraArgs: existing.extraArgs, needsEasingImport: false};
@@ -1349,6 +1358,15 @@ const applyKeyframeOperation = ({
}
if (operation.type === 'easing') {
+ if (
+ isSchemaFieldHoldOnly({schema, key}) &&
+ operation.easing.type !== 'step1'
+ ) {
+ throw new Error(
+ `Cannot update easing: "${key}" only supports Easing.step1`,
+ );
+ }
+
const updated = updateKeyframeEasing({
expression,
segmentIndex: operation.segmentIndex,
diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
index 9b635fa245..f6672f9786 100644
--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts
+++ b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
@@ -5,6 +5,7 @@ import type {
ApplyCodemodRequest,
ApplyCodemodResponse,
} from '@remotion/studio-shared';
+import {generateCanvasCaptureComposition} from '../../canvas-capture/generate-canvas-capture-composition';
import {
applyCodemodToFile,
resolveFilePathFromSymbolicatedStack,
@@ -24,10 +25,26 @@ import {
import {checkIfTypeScriptFile} from './can-update-default-props';
import {withSourceFileWriteQueue} from './source-file-write-queue';
-const formatNewCompositionFile = (componentName: string) => {
+const formatNewCompositionFile = (
+ codemod: Extract<ApplyCodemodRequest['codemod'], {type: 'new-composition'}>,
+) => {
+ if (codemod.canvasCapture !== null) {
+ return generateCanvasCaptureComposition({
+ componentName: codemod.componentName,
+ compositionId: codemod.newId,
+ data: codemod.canvasCapture.data,
+ durationInFrames: codemod.newDurationInFrames,
+ fps: codemod.newFps,
+ height: codemod.newHeight,
+ keyframeFps: codemod.canvasCapture.keyframeFps,
+ videoFileName: codemod.canvasCapture.videoFileName,
+ width: codemod.newWidth,
+ });
+ }
+
return formatOutput(`import React from 'react';
-export const ${componentName}: React.FC = () => {
+export const ${codemod.componentName}: React.FC = () => {
return null;
};
`);
@@ -261,9 +278,7 @@ export const applyCodemodHandler: ApiHandler<
throw new Error('Could not determine the new component file path');
}
- componentFileContents = await formatNewCompositionFile(
- codemod.componentName,
- );
+ componentFileContents = await formatNewCompositionFile(codemod);
snapshots.push({
filePath: componentFilePath,
oldContents: null,
diff --git a/packages/studio-server/src/test/apply-codemod.test.ts b/packages/studio-server/src/test/apply-codemod.test.ts
index b138a29665..136391588e 100644
--- a/packages/studio-server/src/test/apply-codemod.test.ts
+++ b/packages/studio-server/src/test/apply-codemod.test.ts
@@ -165,6 +165,7 @@ test('formats precise log messages for all codemods', () => {
{
codemod: {
type: 'new-composition',
+ canvasCapture: null,
newId: 'FreshVideo',
componentName: 'FreshVideo',
componentImportPath: './FreshVideo',
@@ -626,6 +627,7 @@ test('applyCodemodHandler creates new composition files with undo and redo', asy
input: {
codemod: {
type: 'new-composition',
+ canvasCapture: null,
newId: 'FreshVideo',
componentName: 'FreshVideo',
componentImportPath: './FreshVideo',
@@ -682,11 +684,111 @@ test('applyCodemodHandler creates new composition files with undo and redo', asy
}
});
+test('applyCodemodHandler creates an interactive Canvas Capture composition', async () => {
+ const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));
+ const cleanupFileWatcher = setFileWatcherRegistry(
+ createFileWatcherRegistry(),
+ );
+ const cleanupLiveEvents = setLiveEventsListener({
+ sendEventToClient: () => undefined,
+ sendEventToClientId: () => true,
+ router: () => Promise.resolve(),
+ closeConnections: () => Promise.resolve(),
+ addNewClientListener: () => () => undefined,
+ });
+
+ try {
+ clearUndoRedoStacks();
+ const entryPoint = path.join(remotionRoot, 'Root.tsx');
+ const componentFile = path.join(remotionRoot, 'FreshCapture.tsx');
+ writeFileSync(entryPoint, rootContents);
+
+ const applyResponse = await applyCodemodHandler(
+ getHandlerOptions({
+ input: {
+ codemod: {
+ type: 'new-composition',
+ canvasCapture: {
+ videoFileName: 'capture.mp4',
+ keyframeFps: 30,
+ data: {
+ captureMetadata: {density: 2},
+ mouseMovements: [
+ {
+ timeInSeconds: 0,
+ canvasX: 10,
+ canvasY: 20,
+ cursor: 'default',
+ },
+ {
+ timeInSeconds: 1,
+ canvasX: 30,
+ canvasY: 40,
+ cursor: 'pointer',
+ },
+ ],
+ pointerClicks: [
+ {timeInSeconds: 0.5, type: 'pointer-down'},
+ {timeInSeconds: 0.75, type: 'pointer-up'},
+ ],
+ },
+ },
+ newId: 'FreshCapture',
+ componentName: 'FreshCapture',
+ componentImportPath: './FreshCapture',
+ folderName: null,
+ parentName: null,
+ newDurationInFrames: 90,
+ newFps: 30,
+ newHeight: 720,
+ newWidth: 1280,
+ } satisfies RecastCodemod,
+ dryRun: false,
+ symbolicatedStack: {
+ originalFunctionName: null,
+ originalFileName: 'Root.tsx',
+ originalLineNumber: 9,
+ originalColumnNumber: 4,
+ originalScriptCode: null,
+ },
+ },
+ entryPoint,
+ remotionRoot,
+ }),
+ );
+
+ expect(applyResponse.success).toBe(true);
+ expect(readFileSync(entryPoint, 'utf-8')).toContain(
+ "import {FreshCapture} from './FreshCapture'",
+ );
+ expect(readFileSync(entryPoint, 'utf-8')).toContain('<FreshCapture />');
+ const componentContents = readFileSync(componentFile, 'utf-8');
+ expect(componentContents).toContain(
+ "import {MacOSCursor} from '@remotion/mac-cursors'",
+ );
+ expect(componentContents).toContain("src={staticFile('capture.mp4')}");
+ expect(componentContents).toContain('id="FreshCapture"');
+
+ const undoResponse = await undoHandler(
+ getHandlerOptions({input: {}, entryPoint, remotionRoot}),
+ );
+ expect(undoResponse.success).toBe(true);
+ expect(readFileSync(entryPoint, 'utf-8')).toBe(rootContents);
+ expect(existsSync(componentFile)).toBe(false);
+ } finally {
+ clearUndoRedoStacks();
+ cleanupLiveEvents();
+ cleanupFileWatcher();
+ rmSync(remotionRoot, {recursive: true, force: true});
+ }
+});
+
test('creates a composition in a top-level folder', () => {
const {changesMade, newContents} = parseAndApplyCodemod({
input: folderRootContents,
codeMod: {
type: 'new-composition',
+ canvasCapture: null,
newId: 'FreshVideo',
componentName: 'FreshVideo',
componentImportPath: './FreshVideo',
@@ -715,6 +817,7 @@ test('creates a composition in a nested folder by parent path', () => {
input: folderRootContents,
codeMod: {
type: 'new-composition',
+ canvasCapture: null,
newId: 'FreshVideo',
componentName: 'FreshVideo',
componentImportPath: './FreshVideo',
@@ -782,6 +885,7 @@ test('creates a composition in a self-closing folder', () => {
input: selfClosingFolderRootContents,
codeMod: {
type: 'new-composition',
+ canvasCapture: null,
newId: 'FreshVideo',
componentName: 'FreshVideo',
componentImportPath: './FreshVideo',
diff --git a/packages/studio-server/src/test/fixtures/canvas-capture-composition.txt b/packages/studio-server/src/test/fixtures/canvas-capture-composition.txt
new file mode 100644
index 0000000000..7e1f2dbfe3
--- /dev/null
+++ b/packages/studio-server/src/test/fixtures/canvas-capture-composition.txt
@@ -0,0 +1,157 @@
+import {MacOSCursor} from '@remotion/mac-cursors';
+import {Video} from '@remotion/media';
+import {
+ AbsoluteFill,
+ Composition,
+ Easing,
+ interpolate,
+ staticFile,
+ useCurrentFrame,
+} from 'remotion';
+
+export const CanvasCapturePreview = () => {
+ const frame = useCurrentFrame();
+
+ return (
+ <AbsoluteFill>
+ <Video
+ src={staticFile('remotion-capture-editor-starter.mp4')}
+ style={{
+ position: 'absolute',
+ }}
+ />
+ <MacOSCursor
+ cursor={interpolate(
+ frame,
+ [6, 64, 68, 99, 164, 166],
+ ['default', 'auto', 'pointer', 'e-resize', 'auto', 'default'],
+ {
+ easing: Easing.step1,
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ },
+ )}
+ style={{
+ position: 'absolute',
+ left: 0,
+ top: 0,
+ scale: interpolate(
+ frame,
+ [0, 79, 82, 110, 161],
+ [6, 5.4, 6, 5.4, 6],
+ {
+ easing: Easing.step1,
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ },
+ ),
+ translate: interpolate(
+ frame,
+ [
+ 6, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 83,
+ 84, 85, 86, 87, 88, 89, 90, 91, 92, 97, 98, 99, 100, 114, 115,
+ 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128,
+ 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
+ 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 162, 163,
+ 164, 165, 166, 167,
+ ],
+ [
+ '-2016.9375px -1677.375px',
+ '-2016.9375px -1677.375px',
+ '1813.96875px 948.3515625px',
+ '1784.15625px 916.828125px',
+ '1703.2734375px 833.9765625px',
+ '1571.3203125px 718.875px',
+ '1540.0546875px 674.390625px',
+ '1537.40625px 647.2734375px',
+ '1528.7109375px 533.8125px',
+ '1505.953125px 496.6875px',
+ '1500.46875px 484.7109375px',
+ '1498.0078125px 481.359375px',
+ '1498.0078125px 481.359375px',
+ '1497.7734375px 478.7109375px',
+ '1496.4609375px 473.90625px',
+ '1496.2734375px 473.53125px',
+ '1496.2734375px 473.53125px',
+ '1487.0625px 472.4296875px',
+ '1450.828125px 469.546875px',
+ '1429.9453125px 468.4453125px',
+ '1414.171875px 468.4453125px',
+ '1367.4609375px 469.2421875px',
+ '1335.4921875px 471.3984375px',
+ '1313.53125px 472.171875px',
+ '1299.140625px 472.171875px',
+ '1297.828125px 472.453125px',
+ '1297.828125px 472.453125px',
+ '1290.65625px 472.453125px',
+ '1270.8515625px 473.296875px',
+ '1266px 473.296875px',
+ '1266px 473.296875px',
+ '1233.421875px 470.6953125px',
+ '1222.7578125px 470.15625px',
+ '1147.1953125px 470.15625px',
+ '1139.8125px 470.15625px',
+ '1118.4375px 470.15625px',
+ '1096.40625px 470.15625px',
+ '1049.6484375px 470.15625px',
+ '1002.8203125px 470.15625px',
+ '971.859375px 470.0390625px',
+ '954.140625px 469.3359375px',
+ '937.21875px 469.0546875px',
+ '926.34375px 468.609375px',
+ '916.6171875px 468.609375px',
+ '910.875px 468.0234375px',
+ '910.875px 468.0234375px',
+ '916.4296875px 468.796875px',
+ '934.125px 469.640625px',
+ '978.328125px 471.1640625px',
+ '1022.765625px 473.6015625px',
+ '1069.78125px 474.5390625px',
+ '1087.546875px 474.609375px',
+ '1142.390625px 475.59375px',
+ '1149.4453125px 475.0546875px',
+ '1203px 473.5546875px',
+ '1244.15625px 473.625px',
+ '1274.4609375px 474.9609375px',
+ '1297.2421875px 474.9609375px',
+ '1332px 474.9609375px',
+ '1379.3203125px 473.90625px',
+ '1419.75px 473.90625px',
+ '1432.2421875px 473.90625px',
+ '1452.796875px 473.90625px',
+ '1488.3046875px 474.6796875px',
+ '1499.2265625px 474.6796875px',
+ '1515.0703125px 475.9453125px',
+ '1544.1796875px 477.234375px',
+ '1553.53125px 477.5390625px',
+ '1555.2421875px 477.5390625px',
+ '1555.2421875px 477.5390625px',
+ '1550.8125px 477.5390625px',
+ '1473.4453125px 451.6171875px',
+ '1317.140625px 374.5078125px',
+ '-4.3828125px -360.3046875px',
+ '-2614.3125px -2067.7265625px',
+ ],
+ {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ },
+ ),
+ }}
+ />
+ </AbsoluteFill>
+ );
+};
+
+export const CanvasCaptureComposition = () => {
+ return (
+ <Composition
+ id="canvas-capture-promo"
+ component={CanvasCapturePreview}
+ width={1920}
+ height={1080}
+ fps={60}
+ durationInFrames={500}
+ />
+ );
+};
diff --git a/packages/studio-server/src/test/fixtures/canvas-capture-metadata.json b/packages/studio-server/src/test/fixtures/canvas-capture-metadata.json
new file mode 100644
index 0000000000..ecd75b473d
--- /dev/null
+++ b/packages/studio-server/src/test/fixtures/canvas-capture-metadata.json
@@ -0,0 +1,679 @@
+{
+ "captureMetadata": {
+ "density": 6
+ },
+ "mouseMovements": [
+ {
+ "timeInSeconds": 0.191,
+ "canvasX": -2016.9375,
+ "canvasY": -1677.375,
+ "cursor": "default"
+ },
+ {
+ "timeInSeconds": 2.1282000007629396,
+ "canvasX": 1813.96875,
+ "canvasY": 948.3515625,
+ "cursor": "auto"
+ },
+ {
+ "timeInSeconds": 2.14560000038147,
+ "canvasX": 1805.4375,
+ "canvasY": 937.0078125,
+ "cursor": "auto"
+ },
+ {
+ "timeInSeconds": 2.1602000007629396,
+ "canvasX": 1784.15625,
+ "canvasY": 916.828125,
+ "cursor": "auto"
+ },
+ {
+ "timeInSeconds": 2.1783000001907347,
+ "canvasX": 1742.671875,
+ "canvasY": 874.78125,
+ "cursor": "auto"
+ },
+ {
+ "timeInSeconds": 2.1958000001907347,
+ "canvasX": 1703.2734375,
+ "canvasY": 833.9765625,
+ "cursor": "auto"
+ },
+ {
+ "timeInSeconds": 2.2077000007629395,
+ "canvasX": 1641.6328125,
+ "canvasY": 781.8515625,
+ "cursor": "auto"
+ },
+ {
+ "timeInSeconds": 2.2319000005722045,
+ "canvasX": 1571.3203125,
+ "canvasY": 718.875,
+ "cursor": "auto"
+ },
+ {
+ "timeInSeconds": 2.245300000190735,
+ "canvasX": 1543.59375,
+ "canvasY": 684.09375,
+ "cursor": "auto"
+ },
+ {
+ "timeInSeconds": 2.2624000005722045,
+ "canvasX": 1540.0546875,
+ "canvasY": 674.390625,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.2975,
+ "canvasX": 1537.40625,
+ "canvasY": 647.2734375,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.3132000007629396,
+ "canvasX": 1535.53125,
+ "canvasY": 576.1640625,
+ "cursor": "ns-resize"
+ },
+ {
+ "timeInSeconds": 2.3282000007629393,
+ "canvasX": 1528.7109375,
+ "canvasY": 533.8125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.363,
+ "canvasX": 1505.953125,
+ "canvasY": 496.6875,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.3797000007629396,
+ "canvasX": 1502.2734375,
+ "canvasY": 488.625,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.3951000003814698,
+ "canvasX": 1500.46875,
+ "canvasY": 484.7109375,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.411800000190735,
+ "canvasX": 1498.3359375,
+ "canvasY": 481.78125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.4289000005722046,
+ "canvasX": 1498.0078125,
+ "canvasY": 481.359375,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.4739000005722045,
+ "canvasX": 1498.0078125,
+ "canvasY": 480.9375,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.4905,
+ "canvasX": 1497.7734375,
+ "canvasY": 478.7109375,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.507300000190735,
+ "canvasX": 1497.0234375,
+ "canvasY": 475.78125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.523800000190735,
+ "canvasX": 1496.4609375,
+ "canvasY": 473.90625,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.54060000038147,
+ "canvasX": 1496.2734375,
+ "canvasY": 473.53125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.7743000001907347,
+ "canvasX": 1494.1171875,
+ "canvasY": 473.3203125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.7912000007629394,
+ "canvasX": 1487.0625,
+ "canvasY": 472.4296875,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.81310000038147,
+ "canvasX": 1464.1875,
+ "canvasY": 470.53125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.8302000007629395,
+ "canvasX": 1450.828125,
+ "canvasY": 469.546875,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.8444000005722048,
+ "canvasX": 1437.984375,
+ "canvasY": 468.609375,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.861300000190735,
+ "canvasX": 1429.9453125,
+ "canvasY": 468.4453125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.8787000007629393,
+ "canvasX": 1421.015625,
+ "canvasY": 468.4453125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.8962000007629394,
+ "canvasX": 1414.171875,
+ "canvasY": 468.4453125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.9127000007629396,
+ "canvasX": 1390.8984375,
+ "canvasY": 468.4453125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.928800000190735,
+ "canvasX": 1367.4609375,
+ "canvasY": 469.2421875,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.9456000003814697,
+ "canvasX": 1346.53125,
+ "canvasY": 471.0234375,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.9624000005722047,
+ "canvasX": 1335.4921875,
+ "canvasY": 471.3984375,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.9789000005722044,
+ "canvasX": 1324.9921875,
+ "canvasY": 471.9375,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 2.9956000003814696,
+ "canvasX": 1313.53125,
+ "canvasY": 472.171875,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 3.0124000005722045,
+ "canvasX": 1302,
+ "canvasY": 472.171875,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 3.0297000007629395,
+ "canvasX": 1299.140625,
+ "canvasY": 472.171875,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 3.0464000005722047,
+ "canvasX": 1297.828125,
+ "canvasY": 472.453125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 3.2335,
+ "canvasX": 1297.1953125,
+ "canvasY": 472.453125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 3.2477000007629395,
+ "canvasX": 1293.4921875,
+ "canvasY": 472.453125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 3.2647000007629394,
+ "canvasX": 1290.65625,
+ "canvasY": 472.453125,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 3.279800000190735,
+ "canvasX": 1284.1171875,
+ "canvasY": 473.0390625,
+ "cursor": "pointer"
+ },
+ {
+ "timeInSeconds": 3.2961000003814696,
+ "canvasX": 1270.8515625,
+ "canvasY": 473.296875,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 3.3129000005722045,
+ "canvasX": 1266,
+ "canvasY": 473.296875,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 3.807800000190735,
+ "canvasX": 1256.3203125,
+ "canvasY": 473.203125,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 3.8244000005722047,
+ "canvasX": 1233.421875,
+ "canvasY": 470.6953125,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 3.841300000190735,
+ "canvasX": 1222.7578125,
+ "canvasY": 470.15625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 3.87160000038147,
+ "canvasX": 1185.609375,
+ "canvasY": 470.15625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 3.897,
+ "canvasX": 1147.1953125,
+ "canvasY": 470.15625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 3.9249000005722046,
+ "canvasX": 1139.8125,
+ "canvasY": 470.15625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 3.9512000007629395,
+ "canvasX": 1118.4375,
+ "canvasY": 470.15625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 3.9809000005722046,
+ "canvasX": 1096.40625,
+ "canvasY": 470.15625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.00760000038147,
+ "canvasX": 1049.6484375,
+ "canvasY": 470.15625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.033800000190735,
+ "canvasX": 1015.875,
+ "canvasY": 470.15625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.0555,
+ "canvasX": 1002.8203125,
+ "canvasY": 470.15625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.0745,
+ "canvasX": 980.4375,
+ "canvasY": 470.15625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.091700000762939,
+ "canvasX": 971.859375,
+ "canvasY": 470.0390625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.114,
+ "canvasX": 954.140625,
+ "canvasY": 469.3359375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.1412000007629395,
+ "canvasX": 944.25,
+ "canvasY": 469.3359375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.1578000001907345,
+ "canvasX": 937.21875,
+ "canvasY": 469.0546875,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.174400000572205,
+ "canvasX": 931.5,
+ "canvasY": 468.609375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.19110000038147,
+ "canvasX": 926.34375,
+ "canvasY": 468.609375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.207800000190735,
+ "canvasX": 923.4375,
+ "canvasY": 468.609375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.2245,
+ "canvasX": 916.6171875,
+ "canvasY": 468.609375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.241200000762939,
+ "canvasX": 911.109375,
+ "canvasY": 468.0703125,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.257800000190735,
+ "canvasX": 910.875,
+ "canvasY": 468.0234375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.37510000038147,
+ "canvasX": 911.6015625,
+ "canvasY": 468.0234375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.391900000572204,
+ "canvasX": 916.4296875,
+ "canvasY": 468.796875,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.4085,
+ "canvasX": 924.6796875,
+ "canvasY": 469.640625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.425200000762939,
+ "canvasX": 934.125,
+ "canvasY": 469.640625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.441300000190735,
+ "canvasX": 955.734375,
+ "canvasY": 470.015625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.457800000190735,
+ "canvasX": 978.328125,
+ "canvasY": 471.1640625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.4745,
+ "canvasX": 999.703125,
+ "canvasY": 472.6640625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.4926000003814694,
+ "canvasX": 1022.765625,
+ "canvasY": 473.6015625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.52220000076294,
+ "canvasX": 1069.78125,
+ "canvasY": 474.5390625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.5419000005722046,
+ "canvasX": 1087.546875,
+ "canvasY": 474.609375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.569,
+ "canvasX": 1129.828125,
+ "canvasY": 475.59375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.592800000190735,
+ "canvasX": 1142.390625,
+ "canvasY": 475.59375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.616900000572205,
+ "canvasX": 1149.4453125,
+ "canvasY": 475.0546875,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.642,
+ "canvasX": 1158.8671875,
+ "canvasY": 474.75,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.66360000038147,
+ "canvasX": 1203,
+ "canvasY": 473.5546875,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.691800000190735,
+ "canvasX": 1244.15625,
+ "canvasY": 473.625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.716700000762939,
+ "canvasX": 1274.4609375,
+ "canvasY": 474.9609375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.73860000038147,
+ "canvasX": 1284.9375,
+ "canvasY": 474.9609375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.75810000038147,
+ "canvasX": 1297.2421875,
+ "canvasY": 474.9609375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.774700000762939,
+ "canvasX": 1311.7734375,
+ "canvasY": 474.9609375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.7919000005722046,
+ "canvasX": 1332,
+ "canvasY": 474.9609375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.815300000190735,
+ "canvasX": 1379.3203125,
+ "canvasY": 473.90625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.8386000003814695,
+ "canvasX": 1396.2421875,
+ "canvasY": 473.90625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.864700000762939,
+ "canvasX": 1419.75,
+ "canvasY": 473.90625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.888800000190735,
+ "canvasX": 1432.2421875,
+ "canvasY": 473.90625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.9145,
+ "canvasX": 1452.796875,
+ "canvasY": 473.90625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.9381000003814695,
+ "canvasX": 1465.9453125,
+ "canvasY": 474.4921875,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.96420000076294,
+ "canvasX": 1488.3046875,
+ "canvasY": 474.6796875,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 4.987900000572204,
+ "canvasX": 1499.2265625,
+ "canvasY": 474.6796875,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 5.014700000762939,
+ "canvasX": 1515.0703125,
+ "canvasY": 475.9453125,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 5.038900000572204,
+ "canvasX": 1523.1328125,
+ "canvasY": 475.9453125,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 5.0644000005722045,
+ "canvasX": 1544.1796875,
+ "canvasY": 477.234375,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 5.08920000076294,
+ "canvasX": 1553.53125,
+ "canvasY": 477.5390625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 5.114800000190735,
+ "canvasX": 1555.2421875,
+ "canvasY": 477.5390625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 5.42910000038147,
+ "canvasX": 1550.8125,
+ "canvasY": 477.5390625,
+ "cursor": "e-resize"
+ },
+ {
+ "timeInSeconds": 5.458900000572204,
+ "canvasX": 1473.4453125,
+ "canvasY": 451.6171875,
+ "cursor": "auto"
+ },
+ {
+ "timeInSeconds": 5.47560000038147,
+ "canvasX": 1317.140625,
+ "canvasY": 374.5078125,
+ "cursor": "auto"
+ },
+ {
+ "timeInSeconds": 5.50010000038147,
+ "canvasX": 606.6796875,
+ "canvasY": -3.4921875,
+ "cursor": "auto"
+ },
+ {
+ "timeInSeconds": 5.5255,
+ "canvasX": -4.3828125,
+ "canvasY": -360.3046875,
+ "cursor": "default"
+ },
+ {
+ "timeInSeconds": 5.5421000003814695,
+ "canvasX": -1121.0859375,
+ "canvasY": -1115.859375,
+ "cursor": "default"
+ },
+ {
+ "timeInSeconds": 5.56560000038147,
+ "canvasX": -2614.3125,
+ "canvasY": -2067.7265625,
+ "cursor": "default"
+ }
+ ],
+ "pointerClicks": [
+ {
+ "timeInSeconds": 2.622300000190735,
+ "type": "pointer-down"
+ },
+ {
+ "timeInSeconds": 2.7137000007629393,
+ "type": "pointer-up"
+ },
+ {
+ "timeInSeconds": 3.6594000005722047,
+ "type": "pointer-down"
+ },
+ {
+ "timeInSeconds": 5.351,
+ "type": "pointer-up"
+ }
+ ]
+}
diff --git a/packages/studio-server/src/test/generate-canvas-capture-composition.test.ts b/packages/studio-server/src/test/generate-canvas-capture-composition.test.ts
new file mode 100644
index 0000000000..cc2a3b1ab4
--- /dev/null
+++ b/packages/studio-server/src/test/generate-canvas-capture-composition.test.ts
@@ -0,0 +1,42 @@
+import {expect, test} from 'bun:test';
+import {readFileSync} from 'node:fs';
+import path from 'node:path';
+import {
+ CANVAS_CAPTURE_METADATA_TAG,
+ parseCanvasCaptureData,
+} from '@remotion/studio-shared';
+import {generateCanvasCaptureComposition} from '../canvas-capture/generate-canvas-capture-composition';
+
+test('generates the ideal interactive Canvas Capture composition markup', async () => {
+ const fixtureDirectory = path.join(__dirname, 'fixtures');
+ const metadata = readFileSync(
+ path.join(fixtureDirectory, 'canvas-capture-metadata.json'),
+ 'utf-8',
+ );
+ const data = parseCanvasCaptureData({
+ raw: {[CANVAS_CAPTURE_METADATA_TAG]: metadata},
+ });
+ if (data === null) {
+ throw new Error('Could not parse the Canvas Capture metadata fixture');
+ }
+
+ const generated = await generateCanvasCaptureComposition({
+ componentName: 'CanvasCaptureComposition',
+ compositionId: 'canvas-capture-promo',
+ data,
+ durationInFrames: 500,
+ fps: 60,
+ height: 1080,
+ keyframeFps: 30,
+ videoFileName: 'remotion-capture-editor-starter.mp4',
+ width: 1920,
+ });
+ const expected = readFileSync(
+ path.join(fixtureDirectory, 'canvas-capture-composition.txt'),
+ 'utf-8',
+ )
+ .replaceAll('\r\n', '\n')
+ .replaceAll('\r', '\n');
+
+ expect(generated).toBe(expected);
+});
diff --git a/packages/studio-server/src/test/recast-mods.test.ts b/packages/studio-server/src/test/recast-mods.test.ts
index 2a2f22fc56..0b84deed06 100644
--- a/packages/studio-server/src/test/recast-mods.test.ts
+++ b/packages/studio-server/src/test/recast-mods.test.ts
@@ -292,6 +292,7 @@ test('New composition appends to root and adds imports', () => {
input: compositionInRoot,
codeMod: {
type: 'new-composition',
+ canvasCapture: null,
newId: 'FreshVideo',
componentName: 'FreshVideo',
componentImportPath: './FreshVideo',
diff --git a/packages/studio-server/src/test/update-keyframes.test.ts b/packages/studio-server/src/test/update-keyframes.test.ts
index ac0176b6fd..e93ff1d81f 100644
--- a/packages/studio-server/src/test/update-keyframes.test.ts
+++ b/packages/studio-server/src/test/update-keyframes.test.ts
@@ -993,6 +993,104 @@ test('updateSequenceKeyframes rejects enum fields', async () => {
).rejects.toThrow(/not keyframable/);
});
+test('updateSequenceKeyframes authors enabled enum fields with hold easing', async () => {
+ const input = `import React from 'react';
+import {MacOSCursor} from '@remotion/mac-cursors';
+
+export const Example: React.FC = () => {
+ return <MacOSCursor cursor="default" />;
+};
+`;
+ const schema = {
+ cursor: {
+ type: 'enum',
+ default: 'default',
+ keyframable: true,
+ variants: {
+ default: {},
+ 'ne-resize': {},
+ },
+ },
+ } satisfies InteractivitySchema;
+ const first = await updateSequenceKeyframes({
+ videoConfigValues: null,
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'MacOSCursor cursor')),
+ schema,
+ updates: [
+ {
+ key: 'cursor',
+ operation: {type: 'add', frame: 0, value: 'default'},
+ },
+ ],
+ });
+ const second = await updateSequenceKeyframes({
+ videoConfigValues: null,
+ input: first.output,
+ nodePath: first.updatedNodePath,
+ schema,
+ updates: [
+ {
+ key: 'cursor',
+ operation: {type: 'add', frame: 100, value: 'ne-resize'},
+ },
+ ],
+ });
+
+ expect(second.output).toContain(
+ "cursor={interpolate(frame, [0, 100], ['default', 'ne-resize'], {",
+ );
+ expect(second.output).toContain('easing: [Easing.step1]');
+ expect(second.output).toContain('Easing');
+ expect(second.output).toContain('interpolate');
+ expect(second.output).toContain('useCurrentFrame');
+
+ await expect(
+ updateSequenceKeyframes({
+ videoConfigValues: null,
+ input: second.output,
+ nodePath: second.updatedNodePath,
+ schema,
+ updates: [
+ {
+ key: 'cursor',
+ operation: {
+ type: 'easing',
+ segmentIndex: 0,
+ easing: {type: 'linear'},
+ },
+ },
+ ],
+ }),
+ ).rejects.toThrow(/only supports Easing\.step1/);
+
+ const singleKeyframeInput = `import React from 'react';
+import {MacOSCursor} from '@remotion/mac-cursors';
+import {interpolate, useCurrentFrame} from 'remotion';
+
+export const Example: React.FC = () => {
+ const frame = useCurrentFrame();
+ return <MacOSCursor cursor={interpolate(frame, [0], ['default'])} />;
+};
+`;
+ const fromSingleKeyframe = await updateSequenceKeyframes({
+ videoConfigValues: null,
+ input: singleKeyframeInput,
+ nodePath: lineColumnToNodePath(
+ singleKeyframeInput,
+ getLine(singleKeyframeInput, 'MacOSCursor cursor'),
+ ),
+ schema,
+ updates: [
+ {
+ key: 'cursor',
+ operation: {type: 'add', frame: 100, value: 'ne-resize'},
+ },
+ ],
+ });
+ expect(fromSingleKeyframe.output).toContain('easing: [Easing.step1]');
+});
+
test('updateSequenceKeyframes converts a static value to a single-keyframe interpolation at frame 0', async () => {
const {output, oldValueStrings} = await updateSequenceKeyframes({
videoConfigValues: null,
diff --git a/packages/studio-shared/src/canvas-capture.ts b/packages/studio-shared/src/canvas-capture.ts
new file mode 100644
index 0000000000..70b606c9b1
--- /dev/null
+++ b/packages/studio-shared/src/canvas-capture.ts
@@ -0,0 +1,108 @@
+export const CANVAS_CAPTURE_METADATA_TAG = 'REMOTION_CAPTURE_DATA';
+
+export type CanvasCaptureMouseMovement = {
+ readonly timeInSeconds: number;
+ readonly canvasX: number | null;
+ readonly canvasY: number | null;
+ readonly cursor: string;
+};
+
+export type CanvasCapturePointerClick = {
+ readonly timeInSeconds: number;
+ readonly type: 'pointer-down' | 'pointer-up';
+};
+
+export type CanvasCaptureData = {
+ readonly captureMetadata: {
+ readonly density: number;
+ };
+ readonly mouseMovements: CanvasCaptureMouseMovement[];
+ readonly pointerClicks: CanvasCapturePointerClick[];
+};
+
+const isRecord = (value: unknown): value is Record<string, unknown> => {
+ return typeof value === 'object' && value !== null;
+};
+
+const isFiniteNumber = (value: unknown): value is number => {
+ return typeof value === 'number' && Number.isFinite(value);
+};
+
+export const parseCanvasCaptureData = (
+ metadata: unknown,
+): CanvasCaptureData | null => {
+ if (!isRecord(metadata) || !isRecord(metadata.raw)) {
+ return null;
+ }
+
+ const rawCaptureData = metadata.raw[CANVAS_CAPTURE_METADATA_TAG];
+ if (typeof rawCaptureData !== 'string') {
+ return null;
+ }
+
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawCaptureData);
+ } catch {
+ return null;
+ }
+
+ if (
+ !isRecord(parsed) ||
+ !isRecord(parsed.captureMetadata) ||
+ !isFiniteNumber(parsed.captureMetadata.density) ||
+ parsed.captureMetadata.density <= 0 ||
+ !Array.isArray(parsed.mouseMovements) ||
+ !Array.isArray(parsed.pointerClicks)
+ ) {
+ return null;
+ }
+
+ const mouseMovements: CanvasCaptureMouseMovement[] = [];
+ for (const movement of parsed.mouseMovements) {
+ if (
+ !isRecord(movement) ||
+ !isFiniteNumber(movement.timeInSeconds) ||
+ movement.timeInSeconds < 0 ||
+ (movement.canvasX !== null && !isFiniteNumber(movement.canvasX)) ||
+ (movement.canvasY !== null && !isFiniteNumber(movement.canvasY)) ||
+ typeof movement.cursor !== 'string'
+ ) {
+ return null;
+ }
+
+ mouseMovements.push({
+ timeInSeconds: movement.timeInSeconds,
+ canvasX: movement.canvasX,
+ canvasY: movement.canvasY,
+ cursor: movement.cursor,
+ });
+ }
+
+ const pointerClicks: CanvasCapturePointerClick[] = [];
+ for (const click of parsed.pointerClicks) {
+ if (
+ !isRecord(click) ||
+ !isFiniteNumber(click.timeInSeconds) ||
+ click.timeInSeconds < 0 ||
+ (click.type !== 'pointer-down' && click.type !== 'pointer-up')
+ ) {
+ return null;
+ }
+
+ pointerClicks.push({
+ timeInSeconds: click.timeInSeconds,
+ type: click.type,
+ });
+ }
+
+ return {
+ captureMetadata: {density: parsed.captureMetadata.density},
+ mouseMovements: mouseMovements.sort(
+ (a, b) => a.timeInSeconds - b.timeInSeconds,
+ ),
+ pointerClicks: pointerClicks.sort(
+ (a, b) => a.timeInSeconds - b.timeInSeconds,
+ ),
+ };
+};
diff --git a/packages/studio-shared/src/codemods.ts b/packages/studio-shared/src/codemods.ts
index 061c4fccb8..8c407c5f3d 100644
--- a/packages/studio-shared/src/codemods.ts
+++ b/packages/studio-shared/src/codemods.ts
@@ -1,3 +1,4 @@
+import type {CanvasCaptureData} from './canvas-capture';
import type {EnumPath} from './stringify-default-props';
export type VisualControlChange = {
@@ -24,6 +25,11 @@ export type RecastCodemod =
newWidth: number;
newFps: number;
newDurationInFrames: number;
+ canvasCapture: {
+ readonly videoFileName: string;
+ readonly keyframeFps: number;
+ readonly data: CanvasCaptureData;
+ } | null;
}
| {
type: 'duplicate-composition';
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 414b31b82d..31bfa6a6f1 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -147,6 +147,15 @@ export {
type KeyframeSettings,
} from './api-requests';
export type {BrowserStudioOperations} from './browser-studio-operations';
+export type {
+ CanvasCaptureData,
+ CanvasCaptureMouseMovement,
+ CanvasCapturePointerClick,
+} from './canvas-capture';
+export {
+ CANVAS_CAPTURE_METADATA_TAG,
+ parseCanvasCaptureData,
+} from './canvas-capture';
export type {
SequenceNodePathMutation,
SequenceNodePathRemapping,
@@ -243,6 +252,7 @@ export {
export {
canEditEasingForInterpolationFunction,
getKeyframeInterpolationFunction,
+ isSchemaFieldHoldOnly,
getKeyframeInterpolationFunctionForSchemaField,
isInteractivitySchemaFieldKeyframable,
isKeyframeInterpolationFunction,
diff --git a/packages/studio-shared/src/keyframe-interpolation-function.ts b/packages/studio-shared/src/keyframe-interpolation-function.ts
index efcaa37c82..e766553360 100644
--- a/packages/studio-shared/src/keyframe-interpolation-function.ts
+++ b/packages/studio-shared/src/keyframe-interpolation-function.ts
@@ -16,7 +16,7 @@ const KEYFRAME_FIELD_TYPE_SUPPORT = {
boolean: false,
'remotion-captions': false,
color: true,
- enum: false,
+ enum: true,
'font-family': false,
hidden: true,
number: true,
@@ -40,7 +40,7 @@ const KEYFRAME_FIELD_TYPE_INTERPOLATION = {
boolean: 'unsupported',
'remotion-captions': 'unsupported',
color: 'interpolateColors',
- enum: 'unsupported',
+ enum: 'interpolate',
'font-family': 'unsupported',
hidden: 'infer',
number: 'infer',
@@ -82,6 +82,10 @@ export const isInteractivitySchemaFieldKeyframable = (
return true;
}
+ if (field.type === 'enum') {
+ return field.keyframable === true;
+ }
+
return KEYFRAME_FIELD_TYPE_SUPPORT[field.type] && field.keyframable !== false;
};
@@ -120,6 +124,17 @@ export const isSchemaFieldKeyframable = ({
return isInteractivitySchemaFieldKeyframable(field);
};
+export const isSchemaFieldHoldOnly = ({
+ schema,
+ key,
+}: {
+ schema: InteractivitySchema | null;
+ key: string;
+}): boolean => {
+ const field = schema ? findFieldInSchema(schema, key) : undefined;
+ return field?.type === 'enum' && field.keyframable === true;
+};
+
export const getKeyframeInterpolationFunctionForSchemaField = ({
schema,
key,
diff --git a/packages/studio-shared/src/optimistic-add-keyframe.ts b/packages/studio-shared/src/optimistic-add-keyframe.ts
index 5814024932..692c9e1a76 100644
--- a/packages/studio-shared/src/optimistic-add-keyframe.ts
+++ b/packages/studio-shared/src/optimistic-add-keyframe.ts
@@ -4,9 +4,13 @@ import {
type InteractivitySchema,
type InteractivitySchemaField,
} from 'remotion';
-import {LINEAR_KEYFRAME_EASING} from './keyframe-easing-presets';
+import {
+ HOLD_KEYFRAME_EASING,
+ LINEAR_KEYFRAME_EASING,
+} from './keyframe-easing-presets';
import {
getKeyframeInterpolationFunction,
+ isSchemaFieldHoldOnly,
isSchemaFieldKeyframable,
} from './keyframe-interpolation-function';
@@ -43,6 +47,12 @@ const addKeyframeToPropStatus = ({
schema: InteractivitySchema | null;
}): CanUpdateSequencePropStatus => {
if (status.status === 'keyframed') {
+ const defaultEasing = isSchemaFieldHoldOnly({
+ schema,
+ key: fieldKey,
+ })
+ ? HOLD_KEYFRAME_EASING
+ : LINEAR_KEYFRAME_EASING;
const existingIndex = status.keyframes.findIndex(
(kf) => kf.frame === frame,
);
@@ -71,11 +81,11 @@ const addKeyframeToPropStatus = ({
});
const easingToDuplicate =
easingIndexToDuplicate === null
- ? LINEAR_KEYFRAME_EASING
+ ? defaultEasing
: easing[easingIndexToDuplicate];
easing.splice(insertedKeyframeIndex, 0, easingToDuplicate);
while (easing.length < keyframes.length - 1) {
- easing.push(LINEAR_KEYFRAME_EASING);
+ easing.push(defaultEasing);
}
return {
diff --git a/packages/studio-shared/src/test/canvas-capture.test.ts b/packages/studio-shared/src/test/canvas-capture.test.ts
new file mode 100644
index 0000000000..d1e8fed9f5
--- /dev/null
+++ b/packages/studio-shared/src/test/canvas-capture.test.ts
@@ -0,0 +1,62 @@
+import {expect, test} from 'bun:test';
+import {
+ CANVAS_CAPTURE_METADATA_TAG,
+ parseCanvasCaptureData,
+} from '../canvas-capture';
+
+test('parses Canvas Capture cursor and pointer metadata', () => {
+ const parsed = parseCanvasCaptureData({
+ raw: {
+ [CANVAS_CAPTURE_METADATA_TAG]: JSON.stringify({
+ captureMetadata: {density: 2},
+ mouseMovements: [
+ {
+ timeInSeconds: 1,
+ canvasX: 20,
+ canvasY: 30,
+ cursor: 'pointer',
+ },
+ ],
+ pointerClicks: [
+ {timeInSeconds: 1.2, type: 'pointer-down'},
+ {timeInSeconds: 1.4, type: 'pointer-up'},
+ ],
+ }),
+ },
+ });
+
+ expect(parsed).toEqual({
+ captureMetadata: {density: 2},
+ mouseMovements: [
+ {
+ timeInSeconds: 1,
+ canvasX: 20,
+ canvasY: 30,
+ cursor: 'pointer',
+ },
+ ],
+ pointerClicks: [
+ {timeInSeconds: 1.2, type: 'pointer-down'},
+ {timeInSeconds: 1.4, type: 'pointer-up'},
+ ],
+ });
+});
+
+test('rejects malformed Canvas Capture metadata', () => {
+ expect(parseCanvasCaptureData(null)).toBeNull();
+ expect(
+ parseCanvasCaptureData({
+ raw: {[CANVAS_CAPTURE_METADATA_TAG]: '{invalid'},
+ }),
+ ).toBeNull();
+ expect(
+ parseCanvasCaptureData({
+ raw: {
+ [CANVAS_CAPTURE_METADATA_TAG]: JSON.stringify({
+ captureMetadata: {density: 2},
+ mouseMovements: [],
+ }),
+ },
+ }),
+ ).toBeNull();
+});
diff --git a/packages/studio-shared/src/test/keyframe-interpolation-function.test.ts b/packages/studio-shared/src/test/keyframe-interpolation-function.test.ts
index 76f721b884..d17b4aa032 100644
--- a/packages/studio-shared/src/test/keyframe-interpolation-function.test.ts
+++ b/packages/studio-shared/src/test/keyframe-interpolation-function.test.ts
@@ -5,6 +5,7 @@ import {
canEditEasingForInterpolationFunction,
getKeyframeInterpolationFunctionForSchemaField,
isInteractivitySchemaFieldKeyframable,
+ isSchemaFieldHoldOnly,
isSchemaFieldKeyframable,
} from '../keyframe-interpolation-function';
@@ -56,7 +57,7 @@ test('field type keyframe support is explicit', () => {
).toBe(false);
});
-test('isSchemaFieldKeyframable rejects enum fields', () => {
+test('enum fields are keyframable and hold-only when explicitly enabled', () => {
const schema = {
layout: {
type: 'enum',
@@ -69,7 +70,27 @@ test('isSchemaFieldKeyframable rejects enum fields', () => {
},
} satisfies InteractivitySchema;
+ expect(isSchemaFieldKeyframable({schema, key: 'layout'})).toBe(true);
+ expect(isSchemaFieldHoldOnly({schema, key: 'layout'})).toBe(true);
+ expect(
+ getKeyframeInterpolationFunctionForSchemaField({schema, key: 'layout'}),
+ ).toBe('interpolate');
+});
+
+test('enum fields are not keyframable by default', () => {
+ const schema = {
+ layout: {
+ type: 'enum',
+ default: 'absolute-fill',
+ variants: {
+ 'absolute-fill': {},
+ none: {},
+ },
+ },
+ } satisfies InteractivitySchema;
+
expect(isSchemaFieldKeyframable({schema, key: 'layout'})).toBe(false);
+ expect(isSchemaFieldHoldOnly({schema, key: 'layout'})).toBe(false);
});
test('isSchemaFieldKeyframable rejects explicitly disabled fields', () => {
diff --git a/packages/studio-shared/src/test/optimistic-add-keyframe.test.ts b/packages/studio-shared/src/test/optimistic-add-keyframe.test.ts
index 8db7e71141..0e3abe3fc4 100644
--- a/packages/studio-shared/src/test/optimistic-add-keyframe.test.ts
+++ b/packages/studio-shared/src/test/optimistic-add-keyframe.test.ts
@@ -220,6 +220,57 @@ test('optimisticAddSequenceKeyframe ignores enum fields', () => {
expect(updated).toEqual(previous);
});
+test('optimisticAddSequenceKeyframe uses hold easing for enabled enum fields', () => {
+ const schema = {
+ cursor: {
+ type: 'enum',
+ default: 'default',
+ keyframable: true,
+ variants: {
+ default: {},
+ 'ne-resize': {},
+ },
+ },
+ } satisfies InteractivitySchema;
+ const initial: CanUpdateSequencePropsResponse = {
+ canUpdate: true,
+ props: {
+ cursor: {status: 'static', codeValue: 'default'},
+ },
+ effects: [],
+ };
+ const withFirstKeyframe = optimisticAddSequenceKeyframe({
+ previous: initial,
+ fieldKey: 'cursor',
+ frame: 0,
+ value: 'default',
+ schema,
+ });
+ const withSecondKeyframe = optimisticAddSequenceKeyframe({
+ previous: withFirstKeyframe,
+ fieldKey: 'cursor',
+ frame: 100,
+ value: 'ne-resize',
+ schema,
+ });
+
+ if (!withSecondKeyframe.canUpdate) {
+ throw new Error('expected updateable sequence');
+ }
+
+ const status = withSecondKeyframe.props.cursor;
+ if (!status || status.status !== 'keyframed') {
+ throw new Error('expected keyframed status');
+ }
+
+ expect(status.interpolationFunction).toBe('interpolate');
+ expect(status.keyframes).toEqual([
+ {frame: 0, value: 'default'},
+ {frame: 100, value: 'ne-resize'},
+ ]);
+ expect(status.easing).toEqual([{type: 'step1'}]);
+});
+
test('optimisticAddSequenceKeyframe appends a keyframe to an existing interpolation', () => {
const previous: CanUpdateSequencePropsResponse = {
canUpdate: true,
diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsx
index 07d9c35e91..6f9253f786 100644
--- a/packages/studio/src/components/Canvas.tsx
+++ b/packages/studio/src/components/Canvas.tsx
@@ -23,6 +23,7 @@ import {
} from '../helpers/colors';
import type {AssetMetadata} from '../helpers/get-asset-metadata';
import {getAssetMetadata} from '../helpers/get-asset-metadata';
+import {getCanvasCaptureImport} from '../helpers/get-canvas-capture-import';
import {
applyZoomAroundFocalPoint,
getCenterPointWhileScrolling,
@@ -46,6 +47,7 @@ import {canvasRef} from '../state/canvas-ref';
import {EditorShowGuidesContext} from '../state/editor-guides';
import {EditorSnappingContext} from '../state/editor-snapping';
import {EditorZoomGesturesContext} from '../state/editor-zoom-gestures';
+import {SetSelectedModalContext} from '../state/modals';
import {callApi} from './call-api';
import {
getCompositionDropPreviewBox,
@@ -53,7 +55,7 @@ import {
type CompositionDropPreview,
} from './composition-drop-preview';
import {useConfirmationDialog} from './ConfirmationDialog';
-import {isSupportedDropEvent} from './drop-handler-data';
+import {isFileDragEvent, isSupportedDropEvent} from './drop-handler-data';
import EditorGuides from './EditorGuides';
import {EditorRulers} from './EditorRuler';
import {useIsRulerVisible} from './EditorRuler/use-is-ruler-visible';
@@ -213,6 +215,7 @@ export const Canvas: React.FC<{
const keybindings = useKeybinding();
const confirm = useConfirmationDialog();
const chooseSvgImportMode = useSvgImportDialog();
+ const {setSelectedModal} = useContext(SetSelectedModalContext);
const config = Internals.useUnsafeVideoConfig();
const areRulersVisible = useIsRulerVisible();
const {editorShowGuides} = useContext(EditorShowGuidesContext);
@@ -959,14 +962,17 @@ export const Canvas: React.FC<{
return;
}
- if (!canDropAssets && !cannotAddSequence) {
+ const mayBeCanvasCapture =
+ isFileDragEvent(event) && !window.remotion_isReadOnlyStudio;
+ if (!canDropAssets && !cannotAddSequence && !mayBeCanvasCapture) {
setCompositionDropPreview(null);
return;
}
event.preventDefault();
if (event.dataTransfer) {
- event.dataTransfer.dropEffect = canDropAssets ? 'copy' : 'none';
+ event.dataTransfer.dropEffect =
+ canDropAssets || mayBeCanvasCapture ? 'copy' : 'none';
}
if (
@@ -1083,6 +1089,30 @@ export const Canvas: React.FC<{
return;
}
+ if (isFileDragEvent(event) && !window.remotion_isReadOnlyStudio) {
+ event.preventDefault();
+ event.stopPropagation();
+ const files = Array.from(event.dataTransfer?.files ?? []);
+ if (files.length === 1) {
+ setIsAddingAsset(true);
+ try {
+ const canvasCapture = await getCanvasCaptureImport(files[0]);
+ if (canvasCapture !== null) {
+ setSelectedModal({
+ type: 'new-comp',
+ canvasCapture,
+ folderName: null,
+ parentName: null,
+ stack: null,
+ });
+ return;
+ }
+ } finally {
+ setIsAddingAsset(false);
+ }
+ }
+ }
+
if (cannotAddSequence) {
event.preventDefault();
event.stopPropagation();
@@ -1184,6 +1214,7 @@ export const Canvas: React.FC<{
editorSnapping,
previewSize,
size,
+ setSelectedModal,
],
);
diff --git a/packages/studio/src/components/Modals.tsx b/packages/studio/src/components/Modals.tsx
index 8c86c90504..0b2a542f0f 100644
--- a/packages/studio/src/components/Modals.tsx
+++ b/packages/studio/src/components/Modals.tsx
@@ -58,6 +58,7 @@ export const Modals: React.FC<{
folderName={modalContextType.folderName}
parentName={modalContextType.parentName}
stack={modalContextType.stack}
+ canvasCapture={modalContextType.canvasCapture}
/>
)}
{modalContextType && modalContextType.type === 'new-folder' && (
diff --git a/packages/studio/src/components/NewComposition/NewComposition.tsx b/packages/studio/src/components/NewComposition/NewComposition.tsx
index b1c80301bf..d2fc190fe4 100644
--- a/packages/studio/src/components/NewComposition/NewComposition.tsx
+++ b/packages/studio/src/components/NewComposition/NewComposition.tsx
@@ -7,10 +7,14 @@ import React, {
useState,
} from 'react';
import {Internals} from 'remotion';
+import {getStaticFiles} from '../../api/get-static-files';
+import {writeStaticFile} from '../../api/write-static-file';
+import {installRequiredPackages} from '../../helpers/install-required-package';
import {
getUniqueCompositionName,
useCreateComposition,
} from '../../helpers/use-create-composition';
+import type {CanvasCaptureImport} from '../../state/modals';
import {Spacing} from '../layout';
import {ModalFooterContainer} from '../ModalFooter';
import {ModalHeader} from '../ModalHeader';
@@ -40,7 +44,8 @@ const NewCompositionLoaded: React.FC<{
readonly folderName: string | null;
readonly parentName: string | null;
readonly stack: string | null;
-}> = ({folderName, parentName, stack}) => {
+ readonly canvasCapture: CanvasCaptureImport | null;
+}> = ({canvasCapture, folderName, parentName, stack}) => {
const {compositions} = useContext(Internals.CompositionManager);
const resolvedComposition = Internals.useResolvedVideoConfig(null);
const initialComposition =
@@ -48,7 +53,19 @@ const NewCompositionLoaded: React.FC<{
resolvedComposition?.type === 'success-and-refreshing'
? resolvedComposition.result
: null;
- const initialDimensions = getNewCompositionDefaults(initialComposition);
+ const defaults = getNewCompositionDefaults(initialComposition);
+ const initialDimensions =
+ canvasCapture === null
+ ? defaults
+ : {
+ durationInFrames: Math.max(
+ 1,
+ Math.ceil(canvasCapture.durationInSeconds * 30),
+ ),
+ fps: 30,
+ height: canvasCapture.height,
+ width: canvasCapture.width,
+ };
const [newId, setName] = useState(() =>
getUniqueCompositionName(compositions),
);
@@ -135,8 +152,47 @@ const NewCompositionLoaded: React.FC<{
parentName,
selectedFrameRate,
size,
+ canvasCapture:
+ canvasCapture === null
+ ? null
+ : {data: canvasCapture.data, videoFileName: canvasCapture.file.name},
});
+ const createCanvasCaptureComposition = useCallback(
+ async ({
+ signal,
+ symbolicatedStack,
+ }: Parameters<typeof createComposition>[0]) => {
+ if (canvasCapture !== null) {
+ const existingFile = getStaticFiles().find(
+ (file) => file.name === canvasCapture.file.name,
+ );
+ if (
+ existingFile !== undefined &&
+ existingFile.sizeInBytes !== canvasCapture.file.size
+ ) {
+ throw new Error(
+ `File with name ${canvasCapture.file.name} already exists and is different`,
+ );
+ }
+
+ await installRequiredPackages([
+ {name: '@remotion/media', version: null},
+ {name: '@remotion/mac-cursors', version: null},
+ ]);
+ if (existingFile === undefined) {
+ await writeStaticFile({
+ contents: await canvasCapture.file.arrayBuffer(),
+ filePath: canvasCapture.file.name,
+ });
+ }
+ }
+
+ return createComposition({signal, symbolicatedStack});
+ },
+ [canvasCapture, createComposition],
+ );
+
const onSubmit: React.FormEventHandler<HTMLFormElement> = useCallback((e) => {
e.preventDefault();
}, []);
@@ -283,7 +339,7 @@ const NewCompositionLoaded: React.FC<{
valid={valid}
onSuccess={null}
applyCodemod={({signal, symbolicatedStack}) =>
- createComposition({
+ createCanvasCaptureComposition({
signal,
symbolicatedStack,
})
@@ -300,10 +356,12 @@ export const NewComposition: React.FC<{
readonly folderName: string | null;
readonly parentName: string | null;
readonly stack: string | null;
-}> = ({folderName, parentName, stack}) => {
+ readonly canvasCapture: CanvasCaptureImport | null;
+}> = ({canvasCapture, folderName, parentName, stack}) => {
return (
<DismissableModal>
<NewCompositionLoaded
+ canvasCapture={canvasCapture}
folderName={folderName}
parentName={parentName}
stack={stack}
diff --git a/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx b/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx
index 7ba65ed0d2..2070f63127 100644
--- a/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineEffectPropItem.tsx
@@ -1,4 +1,5 @@
import {
+ isSchemaFieldHoldOnly,
isSchemaFieldKeyframable,
optimisticUpdateForEffectPropStatuses,
} from '@remotion/studio-shared';
@@ -111,6 +112,12 @@ export const TimelineEffectPropValue: React.FC<{
status: propStatus,
frame: sourceFrame,
value,
+ defaultEasing: isSchemaFieldHoldOnly({
+ schema: field.effectSchema,
+ key: field.key,
+ })
+ ? {type: 'step1'}
+ : undefined,
})
: Internals.makeStaticDragOverride(value);
@@ -123,6 +130,7 @@ export const TimelineEffectPropValue: React.FC<{
},
[
field.effectIndex,
+ field.effectSchema,
field.key,
nodePath,
propStatus,
diff --git a/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx b/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
index f9584361ce..e03ee322fe 100644
--- a/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
@@ -1,4 +1,7 @@
-import {isSchemaFieldKeyframable} from '@remotion/studio-shared';
+import {
+ isSchemaFieldHoldOnly,
+ isSchemaFieldKeyframable,
+} from '@remotion/studio-shared';
import React, {useCallback, useContext, useMemo} from 'react';
import type {
CanUpdateSequencePropStatus,
@@ -346,10 +349,16 @@ const TimelineSequenceKeyframedValueUnmemoized: React.FC<
status: propStatus,
frame: sourceFrame,
value,
+ defaultEasing: isSchemaFieldHoldOnly({
+ schema,
+ key: field.key,
+ })
+ ? {type: 'step1'}
+ : undefined,
}),
);
},
- [propStatus, field.key, nodePath, setDragOverrides],
+ [propStatus, field.key, nodePath, schema, setDragOverrides],
);
const onKeyframedDragEnd = useCallback(() => {
diff --git a/packages/studio/src/components/Timeline/update-selected-easing.ts b/packages/studio/src/components/Timeline/update-selected-easing.ts
index a2f15b4778..bc8fdc90e8 100644
--- a/packages/studio/src/components/Timeline/update-selected-easing.ts
+++ b/packages/studio/src/components/Timeline/update-selected-easing.ts
@@ -1,5 +1,6 @@
import {
canEditEasingForInterpolationFunction,
+ isSchemaFieldHoldOnly,
LINEAR_KEYFRAME_EASING,
} from '@remotion/studio-shared';
export {canEditEasingForInterpolationFunction} from '@remotion/studio-shared';
@@ -94,6 +95,10 @@ export const getSelectedEasingUpdate = ({
)?.[field.fieldKey];
if (
sequencePropStatus?.status !== 'keyframed' ||
+ isSchemaFieldHoldOnly({
+ schema: sequence.controls.schema,
+ key: field.fieldKey,
+ }) ||
!canEditEasingForInterpolationFunction(
sequencePropStatus.interpolationFunction,
)
@@ -131,6 +136,10 @@ export const getSelectedEasingUpdate = ({
: null;
if (
effectPropStatus?.status !== 'keyframed' ||
+ isSchemaFieldHoldOnly({
+ schema: effect.schema,
+ key: field.fieldKey,
+ }) ||
!canEditEasingForInterpolationFunction(
effectPropStatus.interpolationFunction,
)
diff --git a/packages/studio/src/components/folder-menu-items.ts b/packages/studio/src/components/folder-menu-items.ts
index b5dd6d4003..ac150ad94d 100644
--- a/packages/studio/src/components/folder-menu-items.ts
+++ b/packages/studio/src/components/folder-menu-items.ts
@@ -111,6 +111,7 @@ export const getFolderMenuItems = ({
folderName: folder.name,
parentName: folder.parent,
stack: folder.stack,
+ canvasCapture: null,
});
},
quickSwitcherLabel: 'New composition in folder...',
diff --git a/packages/studio/src/components/root-composition-menu-items.ts b/packages/studio/src/components/root-composition-menu-items.ts
index 6dbaf4cd31..dc9df7c5fe 100644
--- a/packages/studio/src/components/root-composition-menu-items.ts
+++ b/packages/studio/src/components/root-composition-menu-items.ts
@@ -24,6 +24,7 @@ export const getRootCompositionMenuItems = ({
folderName: null,
parentName: null,
stack: null,
+ canvasCapture: null,
});
},
quickSwitcherLabel: 'New composition...',
diff --git a/packages/studio/src/helpers/get-canvas-capture-import.ts b/packages/studio/src/helpers/get-canvas-capture-import.ts
new file mode 100644
index 0000000000..669eca858e
--- /dev/null
+++ b/packages/studio/src/helpers/get-canvas-capture-import.ts
@@ -0,0 +1,44 @@
+import {parseCanvasCaptureData} from '@remotion/studio-shared';
+import {ALL_FORMATS, BlobSource, Input} from 'mediabunny';
+
+export const getCanvasCaptureImport = async (file: File) => {
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(file),
+ });
+
+ try {
+ const [metadata, videoTrack] = await Promise.all([
+ input.getMetadataTags(),
+ input.getPrimaryVideoTrack(),
+ ]);
+ const data = parseCanvasCaptureData(metadata);
+ if (data === null || videoTrack === null) {
+ return null;
+ }
+
+ const [durationFromMetadata, width, height] = await Promise.all([
+ input.getDurationFromMetadata(),
+ videoTrack.getDisplayWidth(),
+ videoTrack.getDisplayHeight(),
+ ]);
+ const durationInSeconds =
+ durationFromMetadata ?? (await input.computeDuration([videoTrack]));
+ if (
+ !Number.isFinite(durationInSeconds) ||
+ durationInSeconds <= 0 ||
+ !Number.isFinite(width) ||
+ width <= 0 ||
+ !Number.isFinite(height) ||
+ height <= 0
+ ) {
+ return null;
+ }
+
+ return {data, durationInSeconds, file, height, width};
+ } catch {
+ return null;
+ } finally {
+ input.dispose();
+ }
+};
diff --git a/packages/studio/src/helpers/use-create-composition.ts b/packages/studio/src/helpers/use-create-composition.ts
index 2b6fdee31d..92fc045dab 100644
--- a/packages/studio/src/helpers/use-create-composition.ts
+++ b/packages/studio/src/helpers/use-create-composition.ts
@@ -1,4 +1,5 @@
import type {
+ CanvasCaptureData,
RecastCodemod,
SymbolicatedStackFrame,
} from '@remotion/studio-shared';
@@ -68,6 +69,7 @@ export const useCreateComposition = ({
parentName,
selectedFrameRate,
size,
+ canvasCapture,
}: {
compositions: _InternalTypes['AnyComposition'][];
durationInFrames: number;
@@ -79,6 +81,10 @@ export const useCreateComposition = ({
width: number;
height: number;
};
+ canvasCapture: {
+ readonly data: CanvasCaptureData;
+ readonly videoFileName: string;
+ } | null;
}) => {
const selectComposition = useSelectComposition();
const componentName = useMemo(() => toPascalCase(newId), [newId]);
@@ -107,8 +113,17 @@ export const useCreateComposition = ({
componentImportPath: `./${componentName}`,
folderName,
parentName,
+ canvasCapture:
+ canvasCapture === null
+ ? null
+ : {
+ data: canvasCapture.data,
+ keyframeFps: Number(selectedFrameRate),
+ videoFileName: canvasCapture.videoFileName,
+ },
};
}, [
+ canvasCapture,
componentName,
durationInFrames,
folderName,
diff --git a/packages/studio/src/helpers/use-menu-structure.tsx b/packages/studio/src/helpers/use-menu-structure.tsx
index cd49e64291..139b9efba2 100644
--- a/packages/studio/src/helpers/use-menu-structure.tsx
+++ b/packages/studio/src/helpers/use-menu-structure.tsx
@@ -84,6 +84,7 @@ const getFileMenu = ({
folderName: null,
parentName: null,
stack: null,
+ canvasCapture: null,
});
},
type: 'item' as const,
diff --git a/packages/studio/src/state/modals.ts b/packages/studio/src/state/modals.ts
index cfb68fe712..78634b0a0f 100644
--- a/packages/studio/src/state/modals.ts
+++ b/packages/studio/src/state/modals.ts
@@ -11,7 +11,11 @@ import type {
X264Preset,
} from '@remotion/renderer';
import type {HardwareAccelerationOption} from '@remotion/renderer/client';
-import type {PackageManager, RenderDefaults} from '@remotion/studio-shared';
+import type {
+ CanvasCaptureData,
+ PackageManager,
+ RenderDefaults,
+} from '@remotion/studio-shared';
import type {
RenderStillOnWebImageFormat,
WebRendererAudioCodec,
@@ -135,12 +139,21 @@ export type AddEffectModalState = {
clientId: string;
};
+export type CanvasCaptureImport = {
+ readonly data: CanvasCaptureData;
+ readonly durationInSeconds: number;
+ readonly file: File;
+ readonly height: number;
+ readonly width: number;
+};
+
export type ModalState =
| {
type: 'new-comp';
folderName: string | null;
parentName: string | null;
stack: string | null;
+ canvasCapture: CanvasCaptureImport | null;
}
| {
type: 'new-folder';
diff --git a/packages/studio/src/test/canvas-capture-import.test.ts b/packages/studio/src/test/canvas-capture-import.test.ts
new file mode 100644
index 0000000000..394ffa46fc
--- /dev/null
+++ b/packages/studio/src/test/canvas-capture-import.test.ts
@@ -0,0 +1,30 @@
+import {expect, test} from 'bun:test';
+import {readFileSync} from 'node:fs';
+import path from 'node:path';
+import {getCanvasCaptureImport} from '../helpers/get-canvas-capture-import';
+
+test('reads composition defaults and interactions from a Canvas Capture video', async () => {
+ const fileContents = readFileSync(
+ path.join(
+ __dirname,
+ '../../../brand/public/remotion-capture-editor-starter.mp4',
+ ),
+ );
+ const bytes = new Uint8Array(fileContents.length);
+ bytes.set(fileContents);
+ const file = new File([bytes], 'canvas-capture.mp4', {
+ type: 'video/mp4',
+ });
+ const result = await getCanvasCaptureImport(file);
+
+ if (result === null) {
+ throw new Error('Expected Canvas Capture metadata');
+ }
+
+ expect(result.width).toBe(3026);
+ expect(result.height).toBe(1386);
+ expect(result.durationInSeconds).toBeCloseTo(8.7255, 4);
+ expect(result.data.captureMetadata.density).toBe(6);
+ expect(result.data.mouseMovements.length).toBeGreaterThan(50);
+ expect(result.data.pointerClicks).toHaveLength(4);
+});
diff --git a/packages/studio/src/test/root-composition-menu-items.test.ts b/packages/studio/src/test/root-composition-menu-items.test.ts
index cfe47811e1..cae7d57a4d 100644
--- a/packages/studio/src/test/root-composition-menu-items.test.ts
+++ b/packages/studio/src/test/root-composition-menu-items.test.ts
@@ -35,6 +35,7 @@ test('root composition menu creates compositions and folders at the root', () =>
folderName: null,
parentName: null,
stack: null,
+ canvasCapture: null,
},
{type: 'new-folder', parentName: null, stack: null},
]);