Skip to content

🎥 Make videos programmatically with React

Elements: Add basic captions element

JonnyBurgera871e3c73d18
diff --git a/packages/docs/elements/captions/basic-captions/basic-captions.tsx b/packages/docs/elements/captions/basic-captions/basic-captions.tsx
new file mode 100644
index 0000000000..0acd9fed4a
--- /dev/null
+++ b/packages/docs/elements/captions/basic-captions/basic-captions.tsx
@@ -0,0 +1,250 @@
+import type {Caption} from '@remotion/captions';
+import {createTikTokStyleCaptions} from '@remotion/captions';
+import React, {forwardRef, useImperativeHandle, useMemo, useRef} from 'react';
+import {
+ Interactive,
+ Sequence,
+ useCurrentFrame,
+ useVideoConfig,
+ type InteractiveBaseProps,
+ type InteractiveTransformProps,
+ type InteractivitySchema,
+ type SequenceControls,
+ type SequenceProps,
+} from 'remotion';
+
+type BasicCaptionsProps = InteractiveBaseProps &
+ InteractiveTransformProps &
+ Pick<SequenceProps, 'width' | 'height'> & {
+ readonly captions?: Caption[];
+ readonly combineTokensWithinMilliseconds?: number;
+ };
+
+type BasicCaptionsLayerProps = Omit<BasicCaptionsProps, 'captions'> & {
+ readonly callerStyle: React.CSSProperties | null;
+ readonly captions: Caption[];
+};
+
+const defaultCombineTokensWithinMilliseconds = 2000;
+const maximumTextWidth = 800;
+
+const basicCaptionsSchema = {
+ ...Interactive.baseSchema,
+ ...Interactive.captionsSchema,
+ width: {
+ type: 'number',
+ min: 1,
+ step: 1,
+ default: undefined,
+ description: 'Caption area width',
+ hiddenFromList: false,
+ },
+ height: {
+ type: 'number',
+ min: 1,
+ step: 1,
+ default: undefined,
+ description: 'Caption area height',
+ hiddenFromList: false,
+ },
+ combineTokensWithinMilliseconds: {
+ type: 'number',
+ min: 0,
+ step: 50,
+ default: defaultCombineTokensWithinMilliseconds,
+ description: 'Time between caption pages',
+ hiddenFromList: false,
+ },
+ callerStyle: {type: 'hidden'},
+ ...Interactive.transformSchema,
+} as const satisfies InteractivitySchema;
+
+const BasicCaptionsContent: React.FC<{
+ readonly captionAreaWidth: number | null;
+ readonly captions: Caption[];
+ readonly combineTokensWithinMilliseconds: number;
+}> = ({captionAreaWidth, captions, combineTokensWithinMilliseconds}) => {
+ const frame = useCurrentFrame();
+ const {fps} = useVideoConfig();
+ const pages = useMemo(
+ () =>
+ createTikTokStyleCaptions({
+ captions,
+ combineTokensWithinMilliseconds,
+ }).pages,
+ [captions, combineTokensWithinMilliseconds],
+ );
+ const currentTimeMs = (frame / fps) * 1000;
+ const page = pages.find(
+ (candidate) =>
+ currentTimeMs >= candidate.startMs &&
+ currentTimeMs < candidate.startMs + candidate.durationMs,
+ );
+
+ if (!page) {
+ return null;
+ }
+
+ return (
+ <div
+ aria-label={page.text}
+ aria-live="off"
+ role="group"
+ style={{
+ backgroundColor: 'rgba(64, 64, 64, 0.75)',
+ color: '#ffffff',
+ display: '-webkit-box',
+ fontFamily: 'Arial, Helvetica, sans-serif',
+ fontSize: 64,
+ fontWeight: 400,
+ lineHeight: 1.2,
+ maxWidth: Math.min(
+ maximumTextWidth,
+ captionAreaWidth ?? maximumTextWidth,
+ ),
+ overflow: 'hidden',
+ padding: '14px 22px',
+ textAlign: 'center',
+ textWrap: 'balance',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: 2,
+ whiteSpace: 'pre-wrap',
+ }}
+ >
+ {page.text.trim()}
+ </div>
+ );
+};
+
+const BasicCaptionsInner = forwardRef<
+ HTMLDivElement,
+ BasicCaptionsLayerProps & {
+ readonly controls: SequenceControls | undefined;
+ }
+>(
+ (
+ {
+ callerStyle,
+ captions,
+ combineTokensWithinMilliseconds = defaultCombineTokensWithinMilliseconds,
+ controls,
+ height,
+ name,
+ style,
+ width,
+ ...interactiveProps
+ },
+ ref,
+ ) => {
+ const outlineRef = useRef<HTMLDivElement>(null);
+ const {
+ rotate: callerRotate,
+ scale: callerScale,
+ transform: callerTransform,
+ transformBox: callerTransformBox,
+ transformOrigin: callerTransformOrigin,
+ transformStyle: callerTransformStyle,
+ translate: callerTranslate,
+ ...callerContentStyle
+ } = callerStyle ?? {};
+
+ useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);
+
+ return (
+ <Sequence
+ layout="none"
+ {...interactiveProps}
+ controls={controls}
+ name={name ?? '<BasicCaptions>'}
+ outlineRef={outlineRef}
+ >
+ <div
+ style={{
+ height: height ?? '100%',
+ rotate: callerRotate,
+ scale: callerScale,
+ transform: callerTransform,
+ transformBox: callerTransformBox,
+ transformOrigin: callerTransformOrigin,
+ transformStyle: callerTransformStyle,
+ translate: callerTranslate,
+ width: width ?? '100%',
+ }}
+ >
+ <div
+ ref={outlineRef}
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ height: '100%',
+ justifyContent: 'center',
+ width: '100%',
+ ...style,
+ ...callerContentStyle,
+ }}
+ >
+ <BasicCaptionsContent
+ captionAreaWidth={width ?? null}
+ captions={captions}
+ combineTokensWithinMilliseconds={combineTokensWithinMilliseconds}
+ />
+ </div>
+ </div>
+ </Sequence>
+ );
+ },
+);
+
+const BasicCaptionsLayer = Interactive.withSchema({
+ Component: BasicCaptionsInner,
+ componentName: '<BasicCaptions>',
+ componentIdentity: null,
+ schema: basicCaptionsSchema,
+ supportsEffects: false,
+}) as React.FC<BasicCaptionsLayerProps>;
+
+export const BasicCaptions: React.FC<BasicCaptionsProps> = ({
+ captions,
+ style,
+ ...props
+}) => {
+ if (captions) {
+ return (
+ <BasicCaptionsLayer
+ {...props}
+ callerStyle={style ?? null}
+ captions={captions}
+ style={{translate: '0px 0px'}}
+ />
+ );
+ }
+
+ return (
+ <div
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ height: 220,
+ justifyContent: 'center',
+ width: 900,
+ }}
+ >
+ <BasicCaptionsLayer
+ {...props}
+ callerStyle={style ?? null}
+ captions={[
+ {
+ text: 'Simple captions,\nready for every video.',
+ startMs: 0,
+ endMs: 7000,
+ timestampMs: 3500,
+ confidence: null,
+ },
+ ]}
+ height={props.height ?? 220}
+ width={props.width ?? 900}
+ style={{translate: '0px 0px'}}
+ />
+ </div>
+ );
+};
diff --git a/packages/docs/elements/captions/basic-captions/index.mdx b/packages/docs/elements/captions/basic-captions/index.mdx
new file mode 100644
index 0000000000..60cc5b632e
--- /dev/null
+++ b/packages/docs/elements/captions/basic-captions/index.mdx
@@ -0,0 +1,13 @@
+---
+title: Basic Captions
+sidebar_label: Basic
+description: Simple synchronized captions with white text on a translucent gray background.
+image: https://remotion.media/elements/captions-basic-captions-preview.png
+---
+
+import {ElementPage} from '@site/src/components/Elements/ElementPage';
+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';
+
+# Basic Captions
+
+<ElementPage definition={elementDefinitions['captions/basic-captions']} sourceFile="./basic-captions.tsx" />
diff --git a/packages/docs/src/components/Elements/element-definitions.ts b/packages/docs/src/components/Elements/element-definitions.ts
index 105f137afe..1f5bb2559a 100644
--- a/packages/docs/src/components/Elements/element-definitions.ts
+++ b/packages/docs/src/components/Elements/element-definitions.ts
@@ -10,6 +10,7 @@ import {LiquidContours} from '../../../elements/backgrounds/liquid-contours/liqu
import {NotebookPaper} from '../../../elements/backgrounds/notebook-paper/notebook-paper';
import {PaperTexture} from '../../../elements/backgrounds/paper-texture/paper-texture';
import {RotatingStarburst} from '../../../elements/backgrounds/rotating-starburst/rotating-starburst';
+import {BasicCaptions} from '../../../elements/captions/basic-captions/basic-captions';
import {MovingPillCaptions} from '../../../elements/captions/moving-pill-captions/moving-pill-captions';
import {PoppingWordCaptions} from '../../../elements/captions/popping-word-captions/popping-word-captions';
import {WordHighlightCaptions} from '../../../elements/captions/word-highlight-captions/word-highlight-captions';
@@ -815,6 +816,29 @@ const elementImplementations = {
installationMode: 'wrapped',
width: 1920,
},
+ 'captions/basic-captions': {
+ component: BasicCaptions,
+ contributors: [{username: 'JonnyBurger', contribution: null}],
+ description:
+ 'Simple synchronized captions with white text on a translucent gray background.',
+ dependencies: [{name: '@remotion/captions', version: null}],
+ durationInFrames: 210,
+ elementHeight: 220,
+ elementWidth: 900,
+ fps: 30,
+ height: 1080,
+ posterFrame: 75,
+ preview: {
+ previewLayout: 'composition',
+ posterUrl:
+ 'https://remotion.media/elements/captions-basic-captions-preview.png',
+ videoUrl:
+ 'https://remotion.media/elements/captions-basic-captions-preview.mp4',
+ },
+ safeArea: 120,
+ installationMode: 'component-owned-sequence',
+ width: 1920,
+ },
'captions/moving-pill-captions': {
component: MovingPillCaptions,
contributors: [{username: 'JonnyBurger', contribution: null}],
diff --git a/packages/docs/src/components/Elements/element-library-data.ts b/packages/docs/src/components/Elements/element-library-data.ts
index 564b4bada1..da91e45e3a 100644
--- a/packages/docs/src/components/Elements/element-library-data.ts
+++ b/packages/docs/src/components/Elements/element-library-data.ts
@@ -37,6 +37,10 @@ const backgroundOrder: Record<string, number> = {
'backgrounds/liquid-contours': 3,
};
+const captionOrder: Record<string, number> = {
+ 'captions/basic-captions': 0,
+};
+
export const getElementCategoryLabel = (category: ElementCategory) => {
if (category === 'youtube') {
return 'YouTube';
@@ -65,6 +69,15 @@ export const getElementLibrarySections = (
definitions: definitions
.filter((definition) => definition.category === currentCategory)
.sort((a, b) => {
+ if (currentCategory === 'captions') {
+ const orderDifference =
+ (captionOrder[a.slug] ?? Number.MAX_SAFE_INTEGER) -
+ (captionOrder[b.slug] ?? Number.MAX_SAFE_INTEGER);
+ if (orderDifference !== 0) {
+ return orderDifference;
+ }
+ }
+
if (currentCategory === 'backgrounds') {
const orderDifference =
(backgroundOrder[a.slug] ?? Number.MAX_SAFE_INTEGER) -
diff --git a/packages/docs/src/components/Elements/element-registry.ts b/packages/docs/src/components/Elements/element-registry.ts
index 344c812103..790fa7ab72 100644
--- a/packages/docs/src/components/Elements/element-registry.ts
+++ b/packages/docs/src/components/Elements/element-registry.ts
@@ -42,6 +42,10 @@ export const elementRegistry = {
category: 'backgrounds',
displayName: 'Rotating Starburst',
},
+ 'captions/basic-captions': {
+ category: 'captions',
+ displayName: 'Basic Captions',
+ },
'captions/moving-pill-captions': {
category: 'captions',
displayName: 'Moving Pill Captions',
diff --git a/packages/docs/src/test/elements.test.ts b/packages/docs/src/test/elements.test.ts
index 4e7e786cd7..1fa89d69cc 100644
--- a/packages/docs/src/test/elements.test.ts
+++ b/packages/docs/src/test/elements.test.ts
@@ -372,6 +372,10 @@ describe('Element library', () => {
}
}
+ if (section.category === 'captions') {
+ expect(section.definitions[0].slug).toBe('captions/basic-captions');
+ }
+
for (const definition of elementDefinitionList) {
if (definition.category === section.category) {
expect(categoryMarkup).toContain(definition.displayName);
@@ -531,6 +535,7 @@ describe('Elements sidebar', () => {
category: 'captions',
label: 'Captions',
items: [
+ 'captions/basic-captions/index',
'captions/moving-pill-captions/index',
'captions/popping-word-captions/index',
'captions/word-highlight-captions/index',
@@ -671,6 +676,7 @@ describe('Element preview definitions', () => {
.sort();
expect(captionSlugs).toEqual([
+ 'captions/basic-captions',
'captions/moving-pill-captions',
'captions/popping-word-captions',
'captions/word-highlight-captions',
@@ -689,11 +695,27 @@ describe('Element preview definitions', () => {
}
});
+ test('keeps Basic Captions static and limited to two lines', () => {
+ const source = readFileSync(
+ path.join(elementsRoot, 'captions/basic-captions/basic-captions.tsx'),
+ 'utf8',
+ );
+
+ expect(source).toContain("color: '#ffffff'");
+ expect(source).toContain("backgroundColor: 'rgba(64, 64, 64, 0.75)'");
+ expect(source).toContain('fontWeight: 400');
+ expect(source).toContain('WebkitLineClamp: 2');
+ expect(source).not.toContain('borderRadius');
+ expect(source).not.toContain('interpolate');
+ expect(source).not.toContain('spring');
+ });
+
test('only Elements with one interactive timeline item own their Sequence', () => {
const componentOwnedSequenceSlugs = new Set([
'audio/oscilloscope',
'audio/waveform-progress',
'audio/mirrored-spectrum',
+ 'captions/basic-captions',
'captions/moving-pill-captions',
'captions/popping-word-captions',
'captions/word-highlight-captions',