Skip to content

🎥 Make videos programmatically with React

5.8 KB
Raw Blame
import {Video} from '@remotion/media';
import {Player} from '@remotion/player';
import React, {useMemo, useState, type ComponentType} from 'react';
import {AbsoluteFill} from 'remotion';
import {useHtmlInCanvasDocsDemoBranch} from '../../../components/demos/useHtmlInCanvasDocsDemoBranch';
import type {
	ElementBackgroundTheme,
	ElementPreviewLayout,
} from './element-definitions';
import {ELEMENT_PREVIEW_DARK_BACKGROUND} from './ElementPreviewComposition';

type ElementPreviewProps = {
	readonly backgroundTheme: ElementBackgroundTheme;
	readonly component: ComponentType<Record<string, never>>;
	readonly durationInFrames: number;
	readonly elementHeight: number | null;
	readonly elementWidth: number | null;
	readonly fps: number;
	readonly htmlInCanvasFallbackVideoUrl: string | null;
	readonly previewLayout: ElementPreviewLayout;
	readonly safeArea: number;
};

const previewHeight = 1080;
const previewWidth = 1920;
const lightPreviewBackground = '#f5f6f7';
const checkerboardBackgrounds = {
	light:
		'conic-gradient(rgba(0, 0, 0, 0.1) 25%, transparent 0 50%, rgba(0, 0, 0, 0.1) 0 75%, transparent 0)',
	dark: 'conic-gradient(rgba(255, 255, 255, 0.08) 25%, transparent 0 50%, rgba(255, 255, 255, 0.08) 0 75%, transparent 0)',
};

const HtmlInCanvasElementPreview: React.FC<{
	readonly component: ComponentType<Record<string, never>>;
	readonly fallbackVideoUrl: string;
}> = ({component: Component, fallbackVideoUrl}) => {
	const branch = useHtmlInCanvasDocsDemoBranch('webgl2');

	if (branch === 'pending') {
		return <AbsoluteFill />;
	}

	if (branch === 'fallback') {
		return (
			<AbsoluteFill>
				<Video
					muted
					objectFit="contain"
					src={fallbackVideoUrl}
					style={{height: '100%', width: '100%'}}
				/>
			</AbsoluteFill>
		);
	}

	return <Component />;
};

export const ElementPreview: React.FC<ElementPreviewProps> = ({
	backgroundTheme,
	component,
	durationInFrames,
	elementHeight,
	elementWidth,
	fps,
	htmlInCanvasFallbackVideoUrl,
	previewLayout,
	safeArea,
}) => {
	const [checkerboard, setCheckerboard] = useState(true);
	const playerComponent = useMemo(() => {
		if (htmlInCanvasFallbackVideoUrl === null) {
			return component;
		}

		return () => (
			<HtmlInCanvasElementPreview
				component={component}
				fallbackVideoUrl={htmlInCanvasFallbackVideoUrl}
			/>
		);
	}, [component, htmlInCanvasFallbackVideoUrl]);
	const previewBackgroundColor =
		backgroundTheme === 'dark'
			? ELEMENT_PREVIEW_DARK_BACKGROUND
			: lightPreviewBackground;
	const transparencyBackgroundStyle: React.CSSProperties = checkerboard
		? {
				backgroundColor:
					backgroundTheme === 'dark'
						? ELEMENT_PREVIEW_DARK_BACKGROUND
						: 'white',
				backgroundImage: checkerboardBackgrounds[backgroundTheme],
				backgroundSize: '32px 32px',
			}
		: {backgroundColor: previewBackgroundColor};
	let previewBackgroundStyle = transparencyBackgroundStyle;
	let verticalBackgroundStyle: React.CSSProperties | null = null;

	if (previewLayout === 'vertical') {
		if (elementHeight === null || elementWidth === null) {
			throw new Error(
				'A vertical Element preview requires fixed Element dimensions.',
			);
		}

		const scale = Math.min(
			1,
			(previewWidth - safeArea * 2) / elementWidth,
			(previewHeight - safeArea * 2) / elementHeight,
		);
		const displayedElementHeight = elementHeight * scale;
		const displayedElementWidth = elementWidth * scale;

		previewBackgroundStyle = {
			backgroundColor: 'var(--ifm-background-surface-color)',
		};
		verticalBackgroundStyle = {
			...transparencyBackgroundStyle,
			height: `${(displayedElementHeight * 100) / previewHeight}%`,
			left: '50%',
			position: 'absolute',
			top: '50%',
			transform: 'translate(-50%, -50%)',
			width: `${(displayedElementWidth * 100) / previewWidth}%`,
		};
	}

	const transparencyLabel = checkerboard
		? `Use ${backgroundTheme} preview background`
		: 'Show transparency as checkerboard';

	return (
		<div
			style={{
				backgroundColor: previewBackgroundColor,
				overflow: 'hidden',
			}}
		>
			<div
				style={{
					...previewBackgroundStyle,
					aspectRatio: `${previewWidth} / ${previewHeight}`,
					position: 'relative',
					width: '100%',
				}}
			>
				{verticalBackgroundStyle === null ? null : (
					<div style={verticalBackgroundStyle} />
				)}
				<Player
					acknowledgeRemotionLicense
					autoPlay
					component={playerComponent}
					durationInFrames={durationInFrames}
					fps={fps}
					compositionWidth={previewWidth}
					compositionHeight={previewHeight}
					controls
					initiallyMuted
					loop
					renderCustomControls={() => (
						<button
							aria-label={transparencyLabel}
							aria-pressed={checkerboard}
							onClick={() => setCheckerboard((current) => !current)}
							style={{
								alignItems: 'center',
								appearance: 'none',
								backgroundColor: 'transparent',
								border: 'none',
								color: checkerboard ? '#0b84f3' : 'white',
								cursor: 'pointer',
								display: 'inline-flex',
								height: 37,
								marginRight: 12,
								padding: '6px 0',
							}}
							title={transparencyLabel}
							type="button"
						>
							<svg
								aria-hidden="true"
								fill="none"
								focusable="false"
								height={18}
								viewBox="0 0 512 512"
								width={18}
							>
								<path
									d="M256 48h184c13.3 0 24 10.7 24 24v184H256V48zM48 256h208v208H72c-13.3 0-24-10.7-24-24V256z"
									fill="currentColor"
								/>
								<rect
									height="416"
									rx="24"
									stroke="currentColor"
									strokeWidth="32"
									width="416"
									x="48"
									y="48"
								/>
								<path
									d="M256 48v416M48 256h416"
									stroke="currentColor"
									strokeWidth="32"
								/>
							</svg>
						</button>
					)}
					style={{
						backgroundColor: 'transparent',
						height: '100%',
						width: '100%',
					}}
				/>
			</div>
		</div>
	);
};