Skip to content

🎥 Make videos programmatically with React

`remotion`: Add direct premounting to Img (#9499)

Jonny Burger4a8cf0217cb3
diff --git a/packages/core/src/Img.tsx b/packages/core/src/Img.tsx
index fdca6eee72..2b99fa95ba 100644
--- a/packages/core/src/Img.tsx
+++ b/packages/core/src/Img.tsx
@@ -15,11 +15,16 @@ import type {
import type {SequenceControls} from './CompositionManager.js';
import type {EffectsProp} from './effects/effect-types.js';
import {addSequenceStackTraces} from './enable-sequence-stack-traces.js';
+import {Freeze} from './freeze.js';
import {getCrossOriginValue} from './get-cross-origin-value.js';
-import type {InteractiveBaseProps} from './Interactive.js';
+import type {
+ InteractiveBaseProps,
+ InteractivePremountProps,
+} from './Interactive.js';
import {
baseSchema,
borderSchema,
+ premountSchema,
transformSchema,
type InteractivitySchema,
} from './interactivity-schema.js';
@@ -29,6 +34,7 @@ import {SequenceContext} from './SequenceContext.js';
import {truncateSrcForLabel} from './truncate-src-for-label.js';
import {useBufferState} from './use-buffer-state.js';
import {useDelayRender} from './use-delay-render.js';
+import {usePremounting} from './use-premounting.js';
import {useRemotionEnvironment} from './use-remotion-environment.js';
import {withInteractivitySchema} from './with-interactivity-schema.js';
@@ -58,7 +64,8 @@ export type ImgProps = NativeImgProps & {
* @deprecated For internal use only
*/
readonly stack?: string;
-} & InteractiveBaseProps;
+} & InteractiveBaseProps &
+ InteractivePremountProps;
type Expected = Omit<
NativeImgProps,
@@ -76,6 +83,10 @@ type ImgContentProps = Omit<
| 'durationInFrames'
| 'freeze'
| 'effects'
+ | 'premountFor'
+ | 'postmountFor'
+ | 'styleWhilePremounted'
+ | 'styleWhilePostmounted'
> & {
readonly refForOutline: React.RefObject<HTMLElement | null>;
};
@@ -343,6 +354,11 @@ const NativeImgInner: React.FC<NativeImgInnerProps> = ({
trimBefore,
durationInFrames,
freeze,
+ premountFor,
+ postmountFor,
+ style,
+ styleWhilePremounted,
+ styleWhilePostmounted,
controls,
outlineRef: refForOutline,
...props
@@ -351,24 +367,54 @@ const NativeImgInner: React.FC<NativeImgInnerProps> = ({
throw new Error('No "src" prop was passed to <Img>.');
}
+ 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',
+ });
+
return (
- <Sequence
- layout="none"
- from={from ?? 0}
- trimBefore={trimBefore}
- durationInFrames={durationInFrames ?? Infinity}
- freeze={freeze}
- _remotionInternalStack={stack}
- _remotionInternalDocumentationLink="https://www.remotion.dev/docs/img"
- _remotionInternalIsMedia={{type: 'image', src}}
- name={name ?? '<Img>'}
- controls={controls}
- showInTimeline={showInTimeline ?? true}
- hidden={hidden}
- outlineRef={refForOutline}
- >
- <ImgContent src={src} refForOutline={refForOutline} {...props} />
- </Sequence>
+ <Freeze frame={freezeFrame} active={isPremountingOrPostmounting}>
+ <Sequence
+ layout="none"
+ from={from ?? 0}
+ trimBefore={trimBefore}
+ durationInFrames={durationInFrames ?? Infinity}
+ freeze={freeze}
+ _remotionInternalStack={stack}
+ _remotionInternalDocumentationLink="https://www.remotion.dev/docs/img"
+ _remotionInternalIsMedia={{type: 'image', src}}
+ _remotionInternalPremountDisplay={effectivePremountFor || null}
+ _remotionInternalPostmountDisplay={effectivePostmountFor || null}
+ _remotionInternalIsPremounting={premountingActive}
+ _remotionInternalIsPostmounting={postmountingActive}
+ name={name ?? '<Img>'}
+ controls={controls}
+ showInTimeline={showInTimeline ?? true}
+ hidden={hidden}
+ outlineRef={refForOutline}
+ >
+ <ImgContent
+ src={src}
+ refForOutline={refForOutline}
+ style={premountingStyle ?? undefined}
+ {...props}
+ />
+ </Sequence>
+ </Freeze>
);
};
@@ -387,6 +433,7 @@ export const imgSchema = {
keyframable: false,
},
...baseSchema,
+ ...premountSchema,
...transformSchema,
...borderSchema,
} as const satisfies InteractivitySchema;
@@ -482,6 +529,10 @@ const ImgInner: React.FC<
trimBefore,
durationInFrames,
freeze,
+ premountFor,
+ postmountFor,
+ styleWhilePremounted,
+ styleWhilePostmounted,
controls,
width,
height,
@@ -510,6 +561,10 @@ const ImgInner: React.FC<
trimBefore={trimBefore}
durationInFrames={durationInFrames}
freeze={freeze}
+ premountFor={premountFor}
+ postmountFor={postmountFor}
+ styleWhilePremounted={styleWhilePremounted}
+ styleWhilePostmounted={styleWhilePostmounted}
controls={controls}
width={width}
height={height}
@@ -559,6 +614,10 @@ const ImgInner: React.FC<
trimBefore={trimBefore}
durationInFrames={durationInFrames}
freeze={freeze}
+ premountFor={premountFor}
+ postmountFor={postmountFor}
+ styleWhilePremounted={styleWhilePremounted}
+ styleWhilePostmounted={styleWhilePostmounted}
hidden={hidden}
name={name ?? '<Img>'}
showInTimeline={showInTimeline}
diff --git a/packages/core/src/test/Img.test.tsx b/packages/core/src/test/Img.test.tsx
index f94782478f..5e3f1fc5ca 100644
--- a/packages/core/src/test/Img.test.tsx
+++ b/packages/core/src/test/Img.test.tsx
@@ -117,10 +117,13 @@ const previewEnvironment: RemotionEnvironment = {
const wrapImg = (
element: React.ReactElement,
environment: RemotionEnvironment = previewEnvironment,
+ currentFrame: number = 0,
) => {
return (
<RemotionEnvironmentContext.Provider value={environment}>
- <WrapSequenceContext>{element}</WrapSequenceContext>
+ <WrapSequenceContext currentFrame={currentFrame}>
+ {element}
+ </WrapSequenceContext>
</RemotionEnvironmentContext.Provider>
);
};
@@ -305,6 +308,93 @@ test('<Img> buffers playback when premounting ends before loading finishes', asy
}
});
+test('<Img> does not pause playback while directly premounted', async () => {
+ const originalDecode = HTMLImageElement.prototype.decode;
+ const restoreNodeEnv = forceNodeEnv('development');
+ const events: string[] = [];
+ let decodeResolver: (() => void) | null = null;
+ HTMLImageElement.prototype.decode = () =>
+ new Promise<void>((resolve) => {
+ decodeResolver = resolve;
+ });
+ const img = (
+ <>
+ <BufferingEvents events={events} />
+ <Img
+ src="blob:http://localhost/test-image"
+ from={10}
+ durationInFrames={20}
+ premountFor={10}
+ pauseWhenLoading
+ />
+ </>
+ );
+
+ try {
+ const {rerender} = render(wrapImg(img, previewEnvironment, 0));
+
+ await waitFor(() => {
+ expect(decodeResolver).not.toBeNull();
+ });
+ expect(events).toEqual([]);
+
+ rerender(wrapImg(img, previewEnvironment, 10));
+
+ await waitFor(() => {
+ expect(events).toEqual(['waiting']);
+ });
+
+ act(() => {
+ decodeResolver?.();
+ });
+
+ await waitFor(() => {
+ expect(events).toEqual(['waiting', 'resume']);
+ });
+ } finally {
+ HTMLImageElement.prototype.decode = originalDecode;
+ restoreNodeEnv();
+ }
+});
+
+test('<Img> does not pause playback while directly postmounted', async () => {
+ const originalDecode = HTMLImageElement.prototype.decode;
+ const restoreNodeEnv = forceNodeEnv('development');
+ const events: string[] = [];
+ let decodeStarted = false;
+ HTMLImageElement.prototype.decode = () => {
+ decodeStarted = true;
+ return new Promise<void>(() => undefined);
+ };
+
+ try {
+ render(
+ wrapImg(
+ <>
+ <BufferingEvents events={events} />
+ <Img
+ src="blob:http://localhost/test-image"
+ from={10}
+ durationInFrames={20}
+ postmountFor={10}
+ pauseWhenLoading
+ />
+ </>,
+ previewEnvironment,
+ 35,
+ ),
+ );
+
+ await waitFor(() => {
+ expect(decodeStarted).toBe(true);
+ });
+ expect(events).toEqual([]);
+ } finally {
+ HTMLImageElement.prototype.decode = originalDecode;
+ restoreNodeEnv();
+ }
+});
+
test('Img with effects renders through the canvas image path', async () => {
const applyCalls: EffectApplyParams<unknown, unknown>[] = [];
const {container} = renderImg(
diff --git a/packages/core/src/test/sequence-register-once.test.tsx b/packages/core/src/test/sequence-register-once.test.tsx
index f907f7f7a4..a24399b9a8 100644
--- a/packages/core/src/test/sequence-register-once.test.tsx
+++ b/packages/core/src/test/sequence-register-once.test.tsx
@@ -6,7 +6,11 @@ import {
animatedImageSchema,
} from '../animated-image/AnimatedImage.js';
import type {TSequence} from '../CompositionManager.js';
-import {Img} from '../Img.js';
+import type {
+ EffectDefinition,
+ EffectDescriptor,
+} from '../effects/effect-types.js';
+import {Img, imgSchema} from '../Img.js';
import {Interactive} from '../Interactive.js';
import {Internals} from '../internals.js';
import type {OverrideIdToNodePaths} from '../sequence-node-path.js';
@@ -47,6 +51,28 @@ type VisualModeOverrides = {
readonly dragOverrides: DragOverrides;
};
+const makeEffect = (): EffectDescriptor<unknown> => {
+ const definition: EffectDefinition<unknown> = {
+ type: 'test-effect',
+ label: 'Test effect',
+ documentationLink: null,
+ backend: '2d',
+ calculateKey: () => 'test-effect',
+ setup: () => ({}),
+ apply: () => undefined,
+ cleanup: () => undefined,
+ schema: {},
+ validateParams: () => undefined,
+ };
+
+ return {
+ definition,
+ effectKey: 'test-effect',
+ params: {},
+ memoized: false,
+ };
+};
+
const SequenceTestWrapperWithVisualModeOverrides: React.FC<
SequenceTestWrapperProps & {
readonly visualModeOverrides: VisualModeOverrides | null;
@@ -491,6 +517,142 @@ test('Named Img components keep the default documentation link', () => {
);
});
+test('Img exposes non-keyframable premounting schema fields', () => {
+ expect(imgSchema.premountFor.keyframable).toBe(false);
+ expect(imgSchema.postmountFor.keyframable).toBe(false);
+});
+
+test('Img hides the image while premounted and postmounted', () => {
+ const premounted = render(
+ <SequenceTestWrapper currentFrame={0} onRegisterSequence={() => undefined}>
+ <Img
+ src="test.png"
+ from={10}
+ durationInFrames={20}
+ premountFor={10}
+ style={{opacity: 0.5}}
+ />
+ </SequenceTestWrapper>,
+ );
+ const premountedStyle = premounted.container
+ .querySelector('img')
+ ?.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}>
+ <Img src="test.png" from={10} durationInFrames={20} postmountFor={10} />
+ </SequenceTestWrapper>,
+ );
+ const postmountedStyle = postmounted.container
+ .querySelector('img')
+ ?.getAttribute('style');
+ expect(postmountedStyle).toContain('display: none');
+ expect(postmountedStyle).toContain('pointer-events: none');
+});
+
+test('Img allows overriding the premount and postmount styles', () => {
+ const premounted = render(
+ <SequenceTestWrapper currentFrame={0} onRegisterSequence={() => undefined}>
+ <Img
+ src="test.png"
+ from={10}
+ durationInFrames={20}
+ premountFor={10}
+ styleWhilePremounted={{display: 'block', opacity: 0.25}}
+ />
+ </SequenceTestWrapper>,
+ );
+ const premountedStyle = premounted.container
+ .querySelector('img')
+ ?.getAttribute('style');
+ expect(premountedStyle).toContain('display: block');
+ expect(premountedStyle).toContain('opacity: 0.25');
+ premounted.unmount();
+
+ const postmounted = render(
+ <SequenceTestWrapper currentFrame={35} onRegisterSequence={() => undefined}>
+ <Img
+ src="test.png"
+ from={10}
+ durationInFrames={20}
+ postmountFor={10}
+ styleWhilePostmounted={{display: 'block', opacity: 0.75}}
+ />
+ </SequenceTestWrapper>,
+ );
+ const postmountedStyle = postmounted.container
+ .querySelector('img')
+ ?.getAttribute('style');
+ expect(postmountedStyle).toContain('display: block');
+ expect(postmountedStyle).toContain('opacity: 0.75');
+});
+
+test('Img registers premount and postmount ranges once', async () => {
+ const registeredSequences: TSequence[] = [];
+
+ render(
+ <SequenceTestWrapper
+ onRegisterSequence={(sequence) => {
+ registeredSequences.push(sequence);
+ }}
+ >
+ <Img
+ src="test.png"
+ from={10}
+ durationInFrames={20}
+ premountFor={10}
+ postmountFor={5}
+ />
+ </SequenceTestWrapper>,
+ );
+
+ await waitFor(() => {
+ expect(registeredSequences).toHaveLength(1);
+ });
+ expect(registeredSequences[0].premountDisplay).toBe(10);
+ expect(registeredSequences[0].postmountDisplay).toBe(5);
+});
+
+test('Img with effects delegates premounting to one CanvasImage owner', async () => {
+ const registeredSequences: TSequence[] = [];
+
+ const rendered = render(
+ <SequenceTestWrapper
+ currentFrame={0}
+ onRegisterSequence={(sequence) => {
+ registeredSequences.push(sequence);
+ }}
+ >
+ <Img
+ src="test.png"
+ width={100}
+ height={50}
+ effects={[makeEffect()]}
+ from={10}
+ durationInFrames={20}
+ premountFor={10}
+ postmountFor={5}
+ />
+ </SequenceTestWrapper>,
+ );
+
+ await waitFor(() => {
+ expect(registeredSequences).toHaveLength(1);
+ });
+ expect(registeredSequences[0].premountDisplay).toBe(10);
+ expect(registeredSequences[0].postmountDisplay).toBe(5);
+ expect(registeredSequences[0].documentationLink).toBe(
+ 'https://www.remotion.dev/docs/img',
+ );
+ expect(
+ rendered.container.querySelector('canvas')?.getAttribute('style'),
+ ).toContain('display: none');
+});
+
test('AnimatedImage registers its canvas ref for the Studio outline', () => {
const registeredSequences: TSequence[] = [];
const ref = React.createRef<HTMLCanvasElement>();
diff --git a/packages/docs/docs/img.mdx b/packages/docs/docs/img.mdx
index 2ee7f20874..d07c8b80d2 100644
--- a/packages/docs/docs/img.mdx
+++ b/packages/docs/docs/img.mdx
@@ -101,6 +101,24 @@ An exponential backoff is being used, with 1000ms delay between the first and se
If set to `true`, pause the Player when the image is loading. See: [Buffer state](/docs/player/buffer-state).
+### `premountFor?`<AvailableFrom v="4.0.497" />
+
+Mounts the image for the specified number of frames before its `from` frame. The image carries `display: none` and is frozen at its first frame while premounted.
+
+Use this prop to let the image load and decode before it becomes visible. See [Premounting](/docs/player/premounting).
+
+### `postmountFor?`<AvailableFrom v="4.0.497" />
+
+Keeps the image mounted for the specified number of frames after its duration has ended. The image is invisible and frozen at its final frame while postmounted.
+
+### `styleWhilePremounted?`<AvailableFrom v="4.0.497" />
+
+CSS styles applied to the image 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 image while it is postmounted. These styles override the default `display: none` and `pointer-events: none` styles.
+
### `delayRenderTimeoutInMilliseconds?`<AvailableFrom v="4.0.140" />
Customize the [timeout](/docs/delay-render#modifying-the-timeout) of the [`delayRender()`](/docs/delay-render) call that this component makes.