Skip to content

🎥 Make videos programmatically with React

`remotion`: Make AbsoluteFill an interactive sequence (#9845)

Jonny Burger5632c1d6b404
diff --git a/packages/core/src/AbsoluteFill.tsx b/packages/core/src/AbsoluteFill.tsx
index 53747a0256..b6a87a1484 100644
--- a/packages/core/src/AbsoluteFill.tsx
+++ b/packages/core/src/AbsoluteFill.tsx
@@ -1,129 +1,111 @@
-import React, {forwardRef, useMemo} from 'react';
+import React, {useCallback, useRef} from 'react';
+import {
+ AbsoluteFillElement,
+ type AbsoluteFillElementProps,
+} from './AbsoluteFillElement.js';
+import type {SequenceControls} from './CompositionManager.js';
+import {addSequenceStackTraces} from './enable-sequence-stack-traces.js';
+import type {InteractiveBaseProps} from './Interactive.js';
+import {
+ backgroundSchema,
+ baseSchema,
+ borderRadiusSchema,
+ borderSchema,
+ textContentSchema,
+ textSchema,
+ transformSchema,
+ type InteractivitySchema,
+} from './interactivity-schema.js';
+import {Sequence} from './Sequence.js';
+import {useUnsafeVideoConfig} from './use-unsafe-video-config.js';
+import {withInteractivitySchema} from './with-interactivity-schema.js';
-const hasTailwindClassName = ({
- className,
- classPrefix,
- type,
-}: {
- className: string | undefined;
- classPrefix: string[];
- type: 'prefix' | 'exact';
-}) => {
- if (!className) {
- return false;
- }
+export type AbsoluteFillProps = Omit<
+ AbsoluteFillElementProps,
+ keyof InteractiveBaseProps
+> &
+ InteractiveBaseProps & {
+ /**
+ * @deprecated For internal use only
+ */
+ readonly stack?: string;
+ };
- if (type === 'exact') {
- const split = className.split(' ');
- return classPrefix.some((token) => {
- return split.some((part) => {
- return (
- part.trim() === token ||
- part.trim().endsWith(`:${token}`) ||
- part.trim().endsWith(`!${token}`)
- );
- });
- });
- }
+export const absoluteFillSchema = {
+ ...baseSchema,
+ ...transformSchema,
+ ...backgroundSchema,
+ ...borderSchema,
+ ...borderRadiusSchema,
+ ...textSchema,
+ ...textContentSchema,
+} as const satisfies InteractivitySchema;
- return classPrefix.some((prefix) => {
- return (
- className.startsWith(prefix) ||
- className.includes(` ${prefix}`) ||
- className.includes(`!${prefix}`) ||
- className.includes(`:${prefix}`)
- );
- });
+const setRef = <ElementType,>(
+ ref: React.Ref<ElementType> | undefined,
+ value: ElementType | null,
+) => {
+ if (typeof ref === 'function') {
+ ref(value);
+ } else if (ref) {
+ ref.current = value;
+ }
};
-const AbsoluteFillRefForwarding: React.ForwardRefRenderFunction<
- HTMLDivElement,
- React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
-> = (props, ref) => {
- const {style, ...other} = props;
+const AbsoluteFillInner: React.FC<
+ AbsoluteFillProps & {readonly controls: SequenceControls | undefined}
+> = ({
+ ref,
+ from,
+ trimBefore,
+ freeze,
+ durationInFrames,
+ hidden,
+ name,
+ showInTimeline,
+ stack,
+ controls,
+ children,
+ ...divProps
+}) => {
+ const videoConfig = useUnsafeVideoConfig();
+ const refForOutline = useRef<HTMLDivElement | null>(null);
+ const callbackRef = useCallback(
+ (element: HTMLDivElement | null) => {
+ refForOutline.current = element;
+ setRef(ref, element);
+ },
+ [ref],
+ );
- const actualStyle = useMemo((): React.CSSProperties => {
- // Make TailwindCSS classes get accepted
- return {
- position: 'absolute',
- top: hasTailwindClassName({
- className: other.className,
- classPrefix: ['top-', 'inset-'],
- type: 'prefix',
- })
- ? undefined
- : 0,
- left: hasTailwindClassName({
- className: other.className,
- classPrefix: ['left-', 'inset-'],
- type: 'prefix',
- })
- ? undefined
- : 0,
- right: hasTailwindClassName({
- className: other.className,
- classPrefix: ['right-', 'inset-'],
- type: 'prefix',
- })
- ? undefined
- : 0,
- bottom: hasTailwindClassName({
- className: other.className,
- classPrefix: ['bottom-', 'inset-'],
- type: 'prefix',
- })
- ? undefined
- : 0,
- width: hasTailwindClassName({
- className: other.className,
- classPrefix: ['w-'],
- type: 'prefix',
- })
- ? undefined
- : '100%',
- height: hasTailwindClassName({
- className: other.className,
- classPrefix: ['h-'],
- type: 'prefix',
- })
- ? undefined
- : '100%',
- display: hasTailwindClassName({
- className: other.className,
- classPrefix: [
- 'block',
- 'inline-block',
- 'inline',
- 'flex',
- 'inline-flex',
- 'flow-root',
- 'grid',
- 'inline-grid',
- 'contents',
- 'list-item',
- 'hidden',
- ],
- type: 'exact',
- })
- ? undefined
- : 'flex',
- flexDirection: hasTailwindClassName({
- className: other.className,
- classPrefix: [
- 'flex-row',
- 'flex-col',
- 'flex-row-reverse',
- 'flex-col-reverse',
- ],
- type: 'exact',
- })
- ? undefined
- : 'column',
- ...style,
- };
- }, [other.className, style]);
+ if (videoConfig === null) {
+ return hidden ? null : (
+ <AbsoluteFillElement ref={callbackRef} {...divProps}>
+ {children}
+ </AbsoluteFillElement>
+ );
+ }
- return <div ref={ref} style={actualStyle} {...other} />;
+ return (
+ <Sequence
+ layout="none"
+ from={from ?? 0}
+ trimBefore={trimBefore}
+ freeze={freeze}
+ durationInFrames={durationInFrames ?? Infinity}
+ hidden={hidden}
+ name={name ?? '<AbsoluteFill>'}
+ showInTimeline={showInTimeline ?? true}
+ controls={controls}
+ _remotionInternalStack={stack}
+ _remotionInternalDocumentationLink="https://www.remotion.dev/docs/absolute-fill"
+ outlineRef={refForOutline}
+ >
+ <AbsoluteFillElement ref={callbackRef} {...divProps}>
+ {children}
+ </AbsoluteFillElement>
+ </Sequence>
+ );
};
/*
@@ -131,4 +113,12 @@ const AbsoluteFillRefForwarding: React.ForwardRefRenderFunction<
* @see [Documentation](https://remotion.dev/docs/absolute-fill)
*/
-export const AbsoluteFill = forwardRef(AbsoluteFillRefForwarding);
+export const AbsoluteFill = withInteractivitySchema({
+ Component: AbsoluteFillInner,
+ componentName: '<AbsoluteFill>',
+ componentIdentity: 'dev.remotion.remotion.AbsoluteFill',
+ schema: absoluteFillSchema,
+ supportsEffects: false,
+});
+
+addSequenceStackTraces(AbsoluteFill);
diff --git a/packages/core/src/AbsoluteFillElement.tsx b/packages/core/src/AbsoluteFillElement.tsx
new file mode 100644
index 0000000000..5aa04eaf69
--- /dev/null
+++ b/packages/core/src/AbsoluteFillElement.tsx
@@ -0,0 +1,134 @@
+import React, {forwardRef, useMemo} from 'react';
+
+const hasTailwindClassName = ({
+ className,
+ classPrefix,
+ type,
+}: {
+ className: string | undefined;
+ classPrefix: string[];
+ type: 'prefix' | 'exact';
+}) => {
+ if (!className) {
+ return false;
+ }
+
+ if (type === 'exact') {
+ const split = className.split(' ');
+ return classPrefix.some((token) => {
+ return split.some((part) => {
+ return (
+ part.trim() === token ||
+ part.trim().endsWith(`:${token}`) ||
+ part.trim().endsWith(`!${token}`)
+ );
+ });
+ });
+ }
+
+ return classPrefix.some((prefix) => {
+ return (
+ className.startsWith(prefix) ||
+ className.includes(` ${prefix}`) ||
+ className.includes(`!${prefix}`) ||
+ className.includes(`:${prefix}`)
+ );
+ });
+};
+
+export type AbsoluteFillElementProps = React.DetailedHTMLProps<
+ React.HTMLAttributes<HTMLDivElement>,
+ HTMLDivElement
+>;
+
+const AbsoluteFillElementRefForwarding: React.ForwardRefRenderFunction<
+ HTMLDivElement,
+ AbsoluteFillElementProps
+> = (props, ref) => {
+ const {style, ...other} = props;
+
+ const actualStyle = useMemo((): React.CSSProperties => {
+ // Make TailwindCSS classes get accepted
+ return {
+ position: 'absolute',
+ top: hasTailwindClassName({
+ className: other.className,
+ classPrefix: ['top-', 'inset-'],
+ type: 'prefix',
+ })
+ ? undefined
+ : 0,
+ left: hasTailwindClassName({
+ className: other.className,
+ classPrefix: ['left-', 'inset-'],
+ type: 'prefix',
+ })
+ ? undefined
+ : 0,
+ right: hasTailwindClassName({
+ className: other.className,
+ classPrefix: ['right-', 'inset-'],
+ type: 'prefix',
+ })
+ ? undefined
+ : 0,
+ bottom: hasTailwindClassName({
+ className: other.className,
+ classPrefix: ['bottom-', 'inset-'],
+ type: 'prefix',
+ })
+ ? undefined
+ : 0,
+ width: hasTailwindClassName({
+ className: other.className,
+ classPrefix: ['w-'],
+ type: 'prefix',
+ })
+ ? undefined
+ : '100%',
+ height: hasTailwindClassName({
+ className: other.className,
+ classPrefix: ['h-'],
+ type: 'prefix',
+ })
+ ? undefined
+ : '100%',
+ display: hasTailwindClassName({
+ className: other.className,
+ classPrefix: [
+ 'block',
+ 'inline-block',
+ 'inline',
+ 'flex',
+ 'inline-flex',
+ 'flow-root',
+ 'grid',
+ 'inline-grid',
+ 'contents',
+ 'list-item',
+ 'hidden',
+ ],
+ type: 'exact',
+ })
+ ? undefined
+ : 'flex',
+ flexDirection: hasTailwindClassName({
+ className: other.className,
+ classPrefix: [
+ 'flex-row',
+ 'flex-col',
+ 'flex-row-reverse',
+ 'flex-col-reverse',
+ ],
+ type: 'exact',
+ })
+ ? undefined
+ : 'column',
+ ...style,
+ };
+ }, [other.className, style]);
+
+ return <div ref={ref} style={actualStyle} {...other} />;
+};
+
+export const AbsoluteFillElement = forwardRef(AbsoluteFillElementRefForwarding);
diff --git a/packages/core/src/Sequence.tsx b/packages/core/src/Sequence.tsx
index 70fe2516b9..3c0f98e31c 100644
--- a/packages/core/src/Sequence.tsx
+++ b/packages/core/src/Sequence.tsx
@@ -8,7 +8,7 @@ import React, {
useRef,
useState,
} from 'react';
-import {AbsoluteFill} from './AbsoluteFill.js';
+import {AbsoluteFillElement} from './AbsoluteFillElement.js';
import type {LoopDisplay, SequenceControls} from './CompositionManager.js';
import type {EffectDefinition} from './effects/effect-types.js';
import {Freeze} from './freeze.js';
@@ -591,13 +591,13 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
{frozenContent === null ? null : other.layout === 'none' ? (
frozenContent
) : (
- <AbsoluteFill
+ <AbsoluteFillElement
ref={sequenceRef}
style={defaultStyle}
className={other.className}
>
{frozenContent}
- </AbsoluteFill>
+ </AbsoluteFillElement>
)}
</SequenceContext.Provider>
);
diff --git a/packages/core/src/test/absolute-fill.test.tsx b/packages/core/src/test/absolute-fill.test.tsx
new file mode 100644
index 0000000000..9e368f0d1e
--- /dev/null
+++ b/packages/core/src/test/absolute-fill.test.tsx
@@ -0,0 +1,15 @@
+import {expect, test} from 'bun:test';
+import {renderToString} from 'react-dom/server';
+import {AbsoluteFill} from '../AbsoluteFill.js';
+
+test('AbsoluteFill renders outside a composition', () => {
+ const markup = renderToString(
+ <AbsoluteFill className="layer" style={{backgroundColor: 'red'}}>
+ Content
+ </AbsoluteFill>,
+ );
+
+ expect(markup).toContain('Content');
+ expect(markup).toContain('class="layer"');
+ expect(markup).toContain('background-color:red');
+});
diff --git a/packages/core/src/test/nested-sequences.test.tsx b/packages/core/src/test/nested-sequences.test.tsx
index 2ab5a49d7d..d745c953ee 100644
--- a/packages/core/src/test/nested-sequences.test.tsx
+++ b/packages/core/src/test/nested-sequences.test.tsx
@@ -145,6 +145,27 @@ test('trimBefore applies to nested sequence timing', () => {
expect(getForFrame(25, content)(/^frame3$/i)).not.toBe(null);
});
+test('AbsoluteFill supports Sequence timing props', () => {
+ const Child = () => {
+ const frame = useCurrentFrame();
+ return <div>{'absolute-fill-frame' + frame}</div>;
+ };
+
+ const content = (
+ <AbsoluteFill from={20} trimBefore={8} durationInFrames={10}>
+ <Child />
+ </AbsoluteFill>
+ );
+
+ expect(getForFrame(19, content)(/^absolute-fill-frame/i)).toBe(null);
+ cleanup();
+ expect(getForFrame(20, content)(/^absolute-fill-frame8$/i)).not.toBe(null);
+ cleanup();
+ expect(getForFrame(29, content)(/^absolute-fill-frame17$/i)).not.toBe(null);
+ cleanup();
+ expect(getForFrame(30, content)(/^absolute-fill-frame/i)).toBe(null);
+});
+
test('Negative offset edge case', () => {
const NestedChild = () => {
const frame = useCurrentFrame();
diff --git a/packages/core/src/test/sequence-register-once.test.tsx b/packages/core/src/test/sequence-register-once.test.tsx
index 54d2392a79..7646dc2f0c 100644
--- a/packages/core/src/test/sequence-register-once.test.tsx
+++ b/packages/core/src/test/sequence-register-once.test.tsx
@@ -1,6 +1,7 @@
import {afterEach, expect, test} from 'bun:test';
-import {cleanup, render, waitFor} from '@testing-library/react';
+import {cleanup, fireEvent, render, waitFor} from '@testing-library/react';
import React, {useCallback, useMemo, useState} from 'react';
+import {AbsoluteFill} from '../AbsoluteFill.js';
import {
AnimatedImage,
animatedImageSchema,
@@ -1192,6 +1193,61 @@ test('Interactive elements register their rendered element for Studio outlines',
);
});
+test('AbsoluteFill is an interactive sequence while preserving its div contract', () => {
+ const registeredSequences: TSequence[] = [];
+ const divRef = React.createRef<HTMLDivElement>();
+ let clickCount = 0;
+
+ const {container} = render(
+ <SequenceTestWrapper
+ currentFrame={4}
+ onRegisterSequence={(sequence) => {
+ registeredSequences.push(sequence);
+ }}
+ >
+ <AbsoluteFill
+ ref={divRef}
+ id="interactive-fill"
+ from={4}
+ durationInFrames={12}
+ style={{backgroundColor: 'red'}}
+ onClick={() => {
+ clickCount++;
+ }}
+ >
+ Hello
+ </AbsoluteFill>
+ </SequenceTestWrapper>,
+ );
+
+ const element = container.querySelector<HTMLDivElement>('#interactive-fill');
+ if (!element) {
+ throw new Error('Expected AbsoluteFill to render its div');
+ }
+
+ fireEvent.click(element);
+
+ expect(container.querySelectorAll('#interactive-fill')).toHaveLength(1);
+ expect(divRef.current).toBe(element);
+ expect(clickCount).toBe(1);
+ expect(registeredSequences).toHaveLength(1);
+ expect(registeredSequences[0]).toMatchObject({
+ displayName: '<AbsoluteFill>',
+ documentationLink: 'https://www.remotion.dev/docs/absolute-fill',
+ from: 4,
+ duration: 12,
+ showInTimeline: true,
+ });
+ expect(registeredSequences[0]?.refForOutline?.current).toBe(element);
+ expect(registeredSequences[0]?.controls?.componentIdentity).toBe(
+ 'dev.remotion.remotion.AbsoluteFill',
+ );
+ expect(registeredSequences[0]?.controls?.schema).toHaveProperty([
+ 'style.backgroundColor',
+ ]);
+ expect(registeredSequences[0]?.controls?.schema).toHaveProperty('children');
+});
+
test('Interactive elements inherit trimBefore from Sequence', () => {
const Frame = () => {
const frame = useCurrentFrame();
diff --git a/packages/core/src/test/with-interactivity-schema-helpers.test.ts b/packages/core/src/test/with-interactivity-schema-helpers.test.ts
index 7a3f0a3a76..574650a46e 100644
--- a/packages/core/src/test/with-interactivity-schema-helpers.test.ts
+++ b/packages/core/src/test/with-interactivity-schema-helpers.test.ts
@@ -1,4 +1,5 @@
import {expect, test} from 'bun:test';
+import {absoluteFillSchema} from '../AbsoluteFill.js';
import {animatedImageSchema} from '../animated-image/AnimatedImage.js';
import {canvasImageSchema} from '../canvas-image/CanvasImage.js';
import type {SequenceControls} from '../CompositionManager.js';
@@ -53,6 +54,7 @@ test('sequenceStyleSchema contains visual style and premount fields', () => {
test('CSS box component schemas expose background and border controls', () => {
for (const schema of [
+ absoluteFillSchema,
sequenceStyleSchema,
imgSchema,
animatedImageSchema,
diff --git a/packages/docs/docs/absolute-fill.mdx b/packages/docs/docs/absolute-fill.mdx
index 121c628219..134b599c7d 100644
--- a/packages/docs/docs/absolute-fill.mdx
+++ b/packages/docs/docs/absolute-fill.mdx
@@ -45,11 +45,35 @@ const MyComp = () => {
The layers that get rendered last appear on top - this is because of how HTML works.
-## Adding a ref
+## API
-You can add a [React ref](https://react.dev/learn/manipulating-the-dom-with-refs) to an `<AbsoluteFill>` from version `v3.2.13` on. If you use TypeScript, you need to type it with `HTMLDivElement`:
+### Inherited props<AvailableFrom v="4.0.501" />
-```tsx twoslash
+`<AbsoluteFill>` inherits [`from`](/docs/sequence#from), [`durationInFrames`](/docs/sequence#durationinframes), [`trimBefore`](/docs/sequence#trimbefore), [`freeze`](/docs/sequence#freeze), [`hidden`](/docs/sequence#hidden), [`name`](/docs/sequence#name) and [`showInTimeline`](/docs/sequence#showintimeline) from [`<Sequence>`](/docs/sequence).
+
+It is registered as a layer in the [Remotion Studio](/docs/studio) timeline.
+
+:::note
+You can still wrap `<AbsoluteFill>` in an outer [`<Sequence>`](/docs/sequence). Timing [cascades](/docs/sequence#cascading) like nested sequences.
+:::
+
+```tsx twoslash title="Clip starting at frame 30, lasting 90 frames"
+import {AbsoluteFill} from 'remotion';
+
+export const MyComp: React.FC = () => {
+ return (
+ <AbsoluteFill from={30} durationInFrames={90}>
+ This layer is visible from frame 30 to 119.
+ </AbsoluteFill>
+ );
+};
+```
+
+### `ref?`
+
+You can add a [React ref](https://react.dev/learn/manipulating-the-dom-with-refs) to an `<AbsoluteFill>` from version `v3.2.13` on. If you use TypeScript, type it with `HTMLDivElement`:
+
+```tsx twoslash title="MyComp.tsx"
import {useRef} from 'react';
import {AbsoluteFill} from 'remotion';
@@ -61,6 +85,10 @@ const MyComp = () => {
};
```
+### Other props
+
+All props of a regular `<div>` element are forwarded, including `className`, `style` and event handlers.
+
## TailwindCSS class detection<AvailableFrom v="4.0.249" />
This component has a `style` object, which has higher importance than `className`'s.
@@ -76,7 +104,7 @@ Review the source code below to see how we detect Tailwind classes.
## Compatibility
-<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering serverSideRendering player studio hideServers/>
+<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering serverSideRendering player studio hideServers />
## See also
diff --git a/packages/skills/skills/remotion-markup/SKILL.md b/packages/skills/skills/remotion-markup/SKILL.md
index 7e4ee2e3cb..4f41b040df 100644
--- a/packages/skills/skills/remotion-markup/SKILL.md
+++ b/packages/skills/skills/remotion-markup/SKILL.md
@@ -119,7 +119,10 @@ export const Empty = () => {
const frame = useCurrentFrame();
return (
- <AbsoluteFill name="Container" style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
+ <AbsoluteFill
+ name="Scene"
+ style={{display: 'flex', justifyContent: 'center', alignItems: 'center', backgroundColor: 'white'}}
+ >
<Interactive.Div
name="Title"
style={{
@@ -153,7 +156,7 @@ export const Empty = () => {
## Delaying, trimming
-Most components (`<Interactive.*>` `<Img>`, `<AnimatedImage>`, `<CanvasImage>`, `<HtmlInCanvas>`, `<Solid>`, `<Sequence>` from `remotion`, `<Video>` and `<Audio>` from `@remotion/media`, `<Gif>`, and more) support the following props:
+Most components (`<AbsoluteFill>`, `<Interactive.*>` `<Img>`, `<AnimatedImage>`, `<CanvasImage>`, `<HtmlInCanvas>`, `<Solid>`, `<Sequence>` from `remotion`, `<Video>` and `<Audio>` from `@remotion/media`, `<Gif>`, and more) support the following props:
### from
@@ -187,8 +190,9 @@ Useful for components whose internal clock should start later:
### Fallback
If a component does not support these props, wrap it in`<Sequence>` from `remotion`, which has them.
+
- `layout="absolute-fill"` makes the Sequence behave like AbsoluteFill
-- `layout="none"` is "headless" mode, no wrapper element is used.
+- `layout="none"` is "headless" mode, no wrapper element is used.
## Maps