🎥 Make videos programmatically with React
`remotion`: Add direct premounting to AnimatedImage (#9463)
Jonny Burger0543b57d4325
diff --git a/packages/core/src/animated-image/AnimatedImage.tsx b/packages/core/src/animated-image/AnimatedImage.tsxindex 15ef785b05..85dccbf6b8 100644--- a/packages/core/src/animated-image/AnimatedImage.tsx+++ b/packages/core/src/animated-image/AnimatedImage.tsx@@ -15,15 +15,18 @@ import {useMemoizedEffects,} from '../effects/use-memoized-effects.js';import {addSequenceStackTraces} from '../enable-sequence-stack-traces.js';+import {Freeze} from '../freeze.js';import {baseSchema,borderSchema,+ premountSchema,transformSchema,type InteractivitySchema,} from '../interactivity-schema.js';import {Sequence} from '../Sequence.js';import {useCurrentFrame} from '../use-current-frame.js';import {useDelayRender} from '../use-delay-render.js';+import {usePremounting} from '../use-premounting.js';import {useVideoConfig} from '../use-video-config.js';import {withInteractivitySchema} from '../with-interactivity-schema.js';import type {AnimatedImageCanvasRef} from './canvas';@@ -47,6 +50,7 @@ export const animatedImageSchema = {keyframable: false,},...baseSchema,+ ...premountSchema,playbackRate: {type: 'number',min: 0,@@ -296,6 +300,11 @@ const AnimatedImageInner = ({className,style,durationInFrames,+ from,+ premountFor,+ postmountFor,+ styleWhilePremounted,+ styleWhilePostmounted,requestInit,effects = [],controls,@@ -312,6 +321,24 @@ const AnimatedImageInner = ({useImperativeHandle(ref, () => {return actualRef.current as HTMLCanvasElement;}, []);+ const {+ effectivePostmountFor,+ effectivePremountFor,+ freezeFrame,+ isPremountingOrPostmounting,+ postmountingActive,+ premountingActive,+ premountingStyle,+ } = usePremounting({+ from: from ?? 0,+ durationInFrames: durationInFrames ?? Infinity,+ premountFor: premountFor ?? null,+ postmountFor: postmountFor ?? null,+ style: style ?? null,+ styleWhilePremounted: styleWhilePremounted ?? null,+ styleWhilePostmounted: styleWhilePostmounted ?? null,+ hideWhilePremounted: 'display-none',+ });const canvasProps = getCanvasPropsFromSequenceProps(sequenceProps);@@ -325,29 +352,36 @@ const AnimatedImageInner = ({loopBehavior,id,className,- style,+ style: premountingStyle ?? undefined,requestInit,...canvasProps,};return (- <Sequence- layout="none"- durationInFrames={durationInFrames}- name="<AnimatedImage>"- _remotionInternalDocumentationLink="https://www.remotion.dev/docs/animatedimage"- controls={controls}- _remotionInternalEffects={memoizedEffectDefinitions}- {...sequenceProps}- outlineRef={actualRef}- >- <AnimatedImageContent- {...animatedImageProps}- ref={actualRef}- effects={effects}+ <Freeze frame={freezeFrame} active={isPremountingOrPostmounting}>+ <Sequence+ layout="none"+ from={from ?? 0}+ durationInFrames={durationInFrames ?? Infinity}+ name="<AnimatedImage>"+ _remotionInternalDocumentationLink="https://www.remotion.dev/docs/animatedimage"controls={controls}- />- </Sequence>+ _remotionInternalEffects={memoizedEffectDefinitions}+ _remotionInternalPremountDisplay={effectivePremountFor || null}+ _remotionInternalPostmountDisplay={effectivePostmountFor || null}+ _remotionInternalIsPremounting={premountingActive}+ _remotionInternalIsPostmounting={postmountingActive}+ {...sequenceProps}+ outlineRef={actualRef}+ >+ <AnimatedImageContent+ {...animatedImageProps}+ ref={actualRef}+ effects={effects}+ controls={controls}+ />+ </Sequence>+ </Freeze>);};diff --git a/packages/core/src/animated-image/props.ts b/packages/core/src/animated-image/props.tsindex e10c76afb5..0f50333581 100644--- a/packages/core/src/animated-image/props.ts+++ b/packages/core/src/animated-image/props.ts@@ -1,6 +1,9 @@import type {ImageFit} from '../calculate-image-fit.js';import type {EffectsProp} from '../effects/effect-types.js';-import type {InteractiveBaseProps} from '../Interactive.js';+import type {+ InteractiveBaseProps,+ InteractivePremountProps,+} from '../Interactive.js';export type RemotionAnimatedImageLoopBehavior =| 'loop'@@ -25,6 +28,7 @@ export type RemotionAnimatedImageProps = {} & AnimatedImageCanvasProps;export type AnimatedImageProps = InteractiveBaseProps &+ InteractivePremountProps &RemotionAnimatedImageProps & {readonly effects?: EffectsProp;};diff --git a/packages/core/src/canvas-image/CanvasImage.tsx b/packages/core/src/canvas-image/CanvasImage.tsxindex f45ae62515..87f2abb349 100644--- a/packages/core/src/canvas-image/CanvasImage.tsx+++ b/packages/core/src/canvas-image/CanvasImage.tsx@@ -24,7 +24,6 @@ import {baseSchema,borderSchema,premountSchema,- premountStyleSchema,transformSchema,type InteractivitySchema,} from '../interactivity-schema.js';@@ -41,7 +40,6 @@ import type {CanvasImageCanvasProps, CanvasImageProps} from './props.js';export const canvasImageSchema = {...baseSchema,...premountSchema,- ...premountStyleSchema,fit: {type: 'enum',default: 'fill',diff --git a/packages/core/src/interactivity-schema.ts b/packages/core/src/interactivity-schema.tsindex 4ff59e5a34..4b70c95b8b 100644--- a/packages/core/src/interactivity-schema.ts+++ b/packages/core/src/interactivity-schema.ts@@ -396,18 +396,8 @@ export const premountSchema = {},} as const satisfies InteractivitySchema;-export const premountStyleSchema = {- styleWhilePremounted: {- type: 'hidden',- },- styleWhilePostmounted: {- type: 'hidden',- },-} as const satisfies InteractivitySchema;-export const sequencePremountSchema = {...premountSchema,- ...premountStyleSchema,} as const satisfies InteractivitySchema;export const sequenceStyleSchema = {diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.tsindex ca5cfde4a1..0f8168003d 100644--- a/packages/core/src/internals.ts+++ b/packages/core/src/internals.ts@@ -98,7 +98,6 @@ import {fromField,hiddenField,premountSchema,- premountStyleSchema,sequencePremountSchema,sequenceSchema,sequenceStyleSchema,@@ -311,7 +310,6 @@ export const Internals = {textSchema,transformSchema,premountSchema,- premountStyleSchema,flattenActiveSchema,getFlatSchemaWithAllKeys,RemotionRootContexts,diff --git a/packages/core/src/test/animated-image.test.tsx b/packages/core/src/test/animated-image.test.tsxnew file mode 100644index 0000000000..0688b90f86--- /dev/null+++ b/packages/core/src/test/animated-image.test.tsx@@ -0,0 +1,82 @@+import {afterEach, expect, test} from 'bun:test';+import {act, cleanup, render} from '@testing-library/react';+import React from 'react';+import type {AnimatedImageCanvasRef} from '../animated-image/canvas.js';+import {Canvas} from '../animated-image/canvas.js';++let previousGetContextDescriptor: PropertyDescriptor | undefined;++afterEach(() => {+ cleanup();+ if (previousGetContextDescriptor) {+ Object.defineProperty(+ HTMLCanvasElement.prototype,+ 'getContext',+ previousGetContextDescriptor,+ );+ previousGetContextDescriptor = undefined;+ }+});++test('AnimatedImage retains a frame drawn while its canvas is hidden', async () => {+ const pixels = new WeakMap<HTMLCanvasElement, string>();+ previousGetContextDescriptor = Object.getOwnPropertyDescriptor(+ HTMLCanvasElement.prototype,+ 'getContext',+ );+ Object.defineProperty(HTMLCanvasElement.prototype, 'getContext', {+ configurable: true,+ value(this: HTMLCanvasElement, kind: string) {+ if (kind !== '2d') {+ return null;+ }++ return {+ canvas: this,+ clearRect: () => pixels.delete(this),+ drawImage: (source: CanvasImageSource) => {+ if (source instanceof HTMLCanvasElement) {+ const pixel = pixels.get(source);+ if (pixel) {+ pixels.set(this, pixel);+ }++ return;+ }++ pixels.set(this, (source as unknown as {pixel: string}).pixel);+ },+ } as unknown as CanvasRenderingContext2D;+ },+ });++ const ref = React.createRef<AnimatedImageCanvasRef>();+ const rendered = render(+ <Canvas ref={ref} fit="fill" effects={[]} style={{display: 'none'}} />,+ );+ const canvas = rendered.container.querySelector('canvas');+ if (!canvas) {+ throw new Error('Expected a canvas');+ }++ const frame = {+ displayWidth: 2,+ displayHeight: 1,+ pixel: 'initial-frame',+ } as unknown as VideoFrame;++ await act(async () => {+ await ref.current?.draw(frame);+ });++ expect(canvas.style.display).toBe('none');+ expect(pixels.get(canvas)).toBe('initial-frame');++ rendered.rerender(+ <Canvas ref={ref} fit="fill" effects={[]} style={{display: 'block'}} />,+ );++ expect(rendered.container.querySelector('canvas')).toBe(canvas);+ expect(canvas.style.display).toBe('block');+ expect(pixels.get(canvas)).toBe('initial-frame');+});diff --git a/packages/core/src/test/canvas-image.test.tsx b/packages/core/src/test/canvas-image.test.tsxindex 2d7ad890b0..0e55b084b3 100644--- a/packages/core/src/test/canvas-image.test.tsx+++ b/packages/core/src/test/canvas-image.test.tsx@@ -279,8 +279,6 @@ test('<CanvasImage> registers its canvas as the outline ref', async () => {test('<CanvasImage> exposes non-keyframable premounting schema fields', () => {expect(canvasImageSchema.premountFor.keyframable).toBe(false);expect(canvasImageSchema.postmountFor.keyframable).toBe(false);- expect(canvasImageSchema.styleWhilePremounted.type).toBe('hidden');- expect(canvasImageSchema.styleWhilePostmounted.type).toBe('hidden');});test('<CanvasImage> hides the canvas while premounted and postmounted', async () => {diff --git a/packages/core/src/test/find-props-to-delete.test.ts b/packages/core/src/test/find-props-to-delete.test.tsindex beda397e49..92e24f2ea2 100644--- a/packages/core/src/test/find-props-to-delete.test.ts+++ b/packages/core/src/test/find-props-to-delete.test.ts@@ -44,8 +44,6 @@ test('find right values to delete when upgrading a discriminated union', () => {'style.borderColor','premountFor','postmountFor',- 'styleWhilePremounted',- 'styleWhilePostmounted',]);expect(diff --git a/packages/core/src/test/sequence-register-once.test.tsx b/packages/core/src/test/sequence-register-once.test.tsxindex 19e3d11f2f..f907f7f7a4 100644--- a/packages/core/src/test/sequence-register-once.test.tsx+++ b/packages/core/src/test/sequence-register-once.test.tsx@@ -1,7 +1,10 @@import {afterEach, expect, test} from 'bun:test';import {cleanup, render, waitFor} from '@testing-library/react';import React, {useCallback, useMemo, useState} from 'react';-import {AnimatedImage} from '../animated-image/index.js';+import {+ AnimatedImage,+ animatedImageSchema,+} from '../animated-image/AnimatedImage.js';import type {TSequence} from '../CompositionManager.js';import {Img} from '../Img.js';import {Interactive} from '../Interactive.js';@@ -509,6 +512,116 @@ test('AnimatedImage registers its canvas ref for the Studio outline', () => {expect(ref.current).toBe(refForOutline.current);});+test('AnimatedImage exposes non-keyframable premounting schema fields', () => {+ expect(animatedImageSchema.premountFor.keyframable).toBe(false);+ expect(animatedImageSchema.postmountFor.keyframable).toBe(false);+});++test('AnimatedImage hides the canvas while premounted and postmounted', () => {+ const premounted = render(+ <SequenceTestWrapper currentFrame={0} onRegisterSequence={() => undefined}>+ <AnimatedImage+ src="test.gif"+ from={10}+ durationInFrames={20}+ premountFor={10}+ style={{opacity: 0.5}}+ onError={() => undefined}+ />+ </SequenceTestWrapper>,+ );+ const premountedStyle = premounted.container+ .querySelector('canvas')+ ?.getAttribute('style');+ expect(premountedStyle).toContain('display: none');+ expect(premountedStyle).toContain('pointer-events: none');+ expect(premountedStyle).toContain('opacity: 0.5');+ premounted.unmount();++ const postmounted = render(+ <SequenceTestWrapper currentFrame={35} onRegisterSequence={() => undefined}>+ <AnimatedImage+ src="test.gif"+ from={10}+ durationInFrames={20}+ postmountFor={10}+ onError={() => undefined}+ />+ </SequenceTestWrapper>,+ );+ const postmountedStyle = postmounted.container+ .querySelector('canvas')+ ?.getAttribute('style');+ expect(postmountedStyle).toContain('display: none');+ expect(postmountedStyle).toContain('pointer-events: none');+});++test('AnimatedImage allows overriding the premount and postmount styles', () => {+ const premounted = render(+ <SequenceTestWrapper currentFrame={0} onRegisterSequence={() => undefined}>+ <AnimatedImage+ src="test.gif"+ from={10}+ durationInFrames={20}+ premountFor={10}+ styleWhilePremounted={{display: 'block', opacity: 0.25}}+ onError={() => undefined}+ />+ </SequenceTestWrapper>,+ );+ const premountedStyle = premounted.container+ .querySelector('canvas')+ ?.getAttribute('style');+ expect(premountedStyle).toContain('display: block');+ expect(premountedStyle).toContain('opacity: 0.25');+ premounted.unmount();++ const postmounted = render(+ <SequenceTestWrapper currentFrame={35} onRegisterSequence={() => undefined}>+ <AnimatedImage+ src="test.gif"+ from={10}+ durationInFrames={20}+ postmountFor={10}+ styleWhilePostmounted={{display: 'block', opacity: 0.75}}+ onError={() => undefined}+ />+ </SequenceTestWrapper>,+ );+ const postmountedStyle = postmounted.container+ .querySelector('canvas')+ ?.getAttribute('style');+ expect(postmountedStyle).toContain('display: block');+ expect(postmountedStyle).toContain('opacity: 0.75');+});++test('AnimatedImage registers premount and postmount ranges once', async () => {+ const registeredSequences: TSequence[] = [];++ render(+ <SequenceTestWrapper+ onRegisterSequence={(sequence) => {+ registeredSequences.push(sequence);+ }}+ >+ <AnimatedImage+ src="test.gif"+ from={10}+ durationInFrames={20}+ premountFor={10}+ postmountFor={5}+ onError={() => undefined}+ />+ </SequenceTestWrapper>,+ );++ await waitFor(() => {+ expect(registeredSequences).toHaveLength(1);+ });+ expect(registeredSequences[0].premountDisplay).toBe(10);+ expect(registeredSequences[0].postmountDisplay).toBe(5);+});+test('AnimatedImage remains visible with a negative offset', () => {const {container} = render(<SequenceTestWrapperdiff --git a/packages/core/src/test/with-interactivity-schema-helpers.test.ts b/packages/core/src/test/with-interactivity-schema-helpers.test.tsindex 38bb75cfb9..684910bcfd 100644--- a/packages/core/src/test/with-interactivity-schema-helpers.test.ts+++ b/packages/core/src/test/with-interactivity-schema-helpers.test.ts@@ -151,8 +151,6 @@ test('getFlatSchema(sequenceSchema) exposes every variant key', () => {'style.borderColor','premountFor','postmountFor',- 'styleWhilePremounted',- 'styleWhilePostmounted','durationInFrames','from','freeze',diff --git a/packages/docs/docs/animatedimage.mdx b/packages/docs/docs/animatedimage.mdxindex 5c3316dfa1..057f7e5e40 100644--- a/packages/docs/docs/animatedimage.mdx+++ b/packages/docs/docs/animatedimage.mdx@@ -72,6 +72,24 @@ Must be one of these values:Allows to pass in custom CSS styles. You may not pass `width` and `height`, instead use the props `width` and `height` to set the size of the image.+### `premountFor?`<AvailableFrom v="4.0.497" />++Mounts the canvas for the specified number of frames before its `from` frame. The canvas carries `display: none` and is frozen at its first frame while premounted.++Use this prop to let the animated image load, initialize its decoder, and decode its initial frame before it becomes visible. See [Premounting](/docs/player/premounting).++### `postmountFor?`<AvailableFrom v="4.0.497" />++Keeps the canvas mounted for the specified number of frames after its duration has ended. The canvas is invisible and frozen at its final frame while postmounted.++### `styleWhilePremounted?`<AvailableFrom v="4.0.497" />++CSS styles applied to the canvas while it is premounted. These styles override the default `display: none` and `pointer-events: none` styles.++### `styleWhilePostmounted?`<AvailableFrom v="4.0.497" />++CSS styles applied to the canvas while it is postmounted. These styles override the default `display: none` and `pointer-events: none` styles.+### `loopBehavior?`The looping behavior of the animated image. Can be one of these values:diff --git a/packages/docs/docs/interactive.mdx b/packages/docs/docs/interactive.mdxindex b03a247205..862cf9659b 100644--- a/packages/docs/docs/interactive.mdx+++ b/packages/docs/docs/interactive.mdx@@ -116,9 +116,9 @@ Use it for components that accept a `style` prop and render a border.Controls for mounting behavior:-`premountFor`, `postmountFor`, `styleWhilePremounted` and `styleWhilePostmounted`.+`premountFor` and `postmountFor`.-Use it for components that forward these props to a `<Sequence>` with `layout="absolute-fill"`.+Use it for components that forward these props to a `<Sequence>`.### `Interactive.sequenceSchema`<AvailableFrom v="4.0.479" />diff --git a/packages/docs/docs/interactivity-schema.mdx b/packages/docs/docs/interactivity-schema.mdxindex 65422c5771..14be7120d9 100644--- a/packages/docs/docs/interactivity-schema.mdx+++ b/packages/docs/docs/interactivity-schema.mdx@@ -57,7 +57,7 @@ The longhand properties are used rather than the `border` shorthand, because Rea### `Interactive.premountSchema`-Mounting props: `premountFor`, `postmountFor`, `styleWhilePremounted` and `styleWhilePostmounted`.+Mounting props: `premountFor` and `postmountFor`.These schemas are for component props. Effects created with [`createEffect()`](/docs/create-effect) should define only their own effect parameters.diff --git a/packages/docs/docs/studio/make-component-interactive.mdx b/packages/docs/docs/studio/make-component-interactive.mdxindex c5214adcd0..51065955b7 100644--- a/packages/docs/docs/studio/make-component-interactive.mdx+++ b/packages/docs/docs/studio/make-component-interactive.mdx@@ -284,7 +284,7 @@ Use it when the component accepts a `style` prop and applies it to the rendered### `Interactive.premountSchema`-Use it when the component forwards `premountFor`, `postmountFor`, `styleWhilePremounted` and `styleWhilePostmounted` to a `<Sequence>` with `layout="absolute-fill"`.+Use it when the component forwards `premountFor` and `postmountFor` to a `<Sequence>`.## See alsodiff --git a/packages/gif/src/Gif.tsx b/packages/gif/src/Gif.tsxindex 9ad2c1b3d9..e0bd0b4c17 100644--- a/packages/gif/src/Gif.tsx+++ b/packages/gif/src/Gif.tsx@@ -32,7 +32,6 @@ export type GifProps = InteractiveBaseProps &export const gifSchema: InteractivitySchema = {...Internals.baseSchema,...Internals.premountSchema,- ...Internals.premountStyleSchema,playbackRate: {type: 'number',min: 0,diff --git a/packages/gif/src/test/Gif.test.tsx b/packages/gif/src/test/Gif.test.tsxindex 28d0f3e852..af5c064759 100644--- a/packages/gif/src/test/Gif.test.tsx+++ b/packages/gif/src/test/Gif.test.tsx@@ -226,8 +226,6 @@ test('<Gif> registers its canvas as the outline ref', async () => {test('<Gif> exposes non-keyframable premounting schema fields', () => {expect(gifSchema.premountFor).toMatchObject({keyframable: false});expect(gifSchema.postmountFor).toMatchObject({keyframable: false});- expect(gifSchema.styleWhilePremounted.type).toBe('hidden');- expect(gifSchema.styleWhilePostmounted.type).toBe('hidden');});test('<Gif> hides the canvas while premounted and postmounted', () => {diff --git a/packages/media/src/video/video.tsx b/packages/media/src/video/video.tsxindex e4f5bc61bf..2dd2f15a80 100644--- a/packages/media/src/video/video.tsx+++ b/packages/media/src/video/video.tsx@@ -27,7 +27,6 @@ export const videoSchema: InteractivitySchema = {},...Internals.baseSchema,...Internals.premountSchema,- ...Internals.premountStyleSchema,volume: {type: 'number',min: 0,diff --git a/packages/studio-server/src/test/discriminated-union-update.test.ts b/packages/studio-server/src/test/discriminated-union-update.test.tsindex 29b9e7235c..907e08c78e 100644--- a/packages/studio-server/src/test/discriminated-union-update.test.ts+++ b/packages/studio-server/src/test/discriminated-union-update.test.ts@@ -128,7 +128,7 @@ test('Should remove variant-specific props when switching enum value', async ()expect(await prettify(update.serialized)).toBe(await prettify(expected));});-test('Should remove premountFor and styleWhile* when switching to layout="none"', async () => {+test('Should remove premountFor and preserve styleWhile* when switching to layout="none"', async () => {const file = readFileSync(path.join(__dirname, 'snapshots', 'discriminated-union-with-premount.tsx'),'utf-8',diff --git a/packages/studio-server/src/test/get-all-schema-keys.test.ts b/packages/studio-server/src/test/get-all-schema-keys.test.tsindex f18b41bb3e..752b342ef9 100644--- a/packages/studio-server/src/test/get-all-schema-keys.test.ts+++ b/packages/studio-server/src/test/get-all-schema-keys.test.ts@@ -24,8 +24,6 @@ test('getAllSchemaKeys returns every key across all enum variants', () => {'style.borderColor','premountFor','postmountFor',- 'styleWhilePremounted',- 'styleWhilePostmounted','durationInFrames','from','trimBefore',diff --git a/packages/studio-server/src/test/snapshots/discriminated-union-with-premount-expected.tsx b/packages/studio-server/src/test/snapshots/discriminated-union-with-premount-expected.tsxindex c7d46caf46..13e2bfc6d1 100644--- a/packages/studio-server/src/test/snapshots/discriminated-union-with-premount-expected.tsx+++ b/packages/studio-server/src/test/snapshots/discriminated-union-with-premount-expected.tsx@@ -1,3 +1,9 @@export const ControlsShowcase: React.FC = () => {- return <Sequence layout={'none'}></Sequence>;+ return (+ <Sequence+ styleWhilePostmounted={{opacity: 0}}+ styleWhilePremounted={{opacity: 0}}+ layout={'none'}+ ></Sequence>+ );};