🎥 Make videos programmatically with React
Created Loop component * Created exampled of looped in example package * Created tests * Created documentation in docs package
bpedersenbf680221746b
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 39111f735a..030a017629 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -30,6 +30,7 @@ export * from './Img';export * from './internals';export * from './interpolate';export {interpolateColors} from './interpolateColors';+export {Loop} from './loop';export * from './random';export * from './ready-manager';export {registerRoot} from './register-root';diff --git a/packages/core/src/loop/index.tsx b/packages/core/src/loop/index.tsxnew file mode 100644index 0000000000..e0c38542c2--- /dev/null+++ b/packages/core/src/loop/index.tsx@@ -0,0 +1,67 @@+import React from 'react';+import {Sequence, useVideoConfig} from '..';++export type LoopProps = {+ children: React.ReactNode;+ // The duration of the content to be looped+ durationInFrames: number;+ // How many times to loop (optional, default Infinity)+ times?: number;+};++export const Loop: React.FC<LoopProps> = ({+ durationInFrames,+ times,+ children,+}) => {+ const video = useVideoConfig();++ if (typeof durationInFrames !== 'number') {+ throw new TypeError(+ `You passed to durationInFrames an argument of type ${typeof durationInFrames}, but it must be a number.`+ );+ }++ if (durationInFrames <= 0) {+ throw new TypeError(+ `durationInFrames must be positive, but got ${durationInFrames}.`+ );+ }++ // Infinity is non-integer but allowed!+ if (durationInFrames % 1 !== 0 && Number.isFinite(durationInFrames)) {+ throw new TypeError(+ `The "durationInFrames" of a loop must be an integer, but got ${durationInFrames}.`+ );+ }++ if (times && typeof times !== 'number') {+ throw new TypeError(+ `You passed to "times" an argument of type ${typeof times}, but it must be a number.`+ );+ }++ if (times && times % 1 !== 0) {+ throw new TypeError(+ `The "times" prop of a loop must be an integer, but got ${times}.`+ );+ }++ const loopCount = times+ ? times+ : Math.floor(video.durationInFrames / durationInFrames);+ return (+ <>+ {new Array(loopCount).fill('').map((_, index) => (+ <Sequence+ // eslint-disable-next-line react/no-array-index-key+ key={index}+ from={durationInFrames * index}+ durationInFrames={durationInFrames}+ >+ {children}+ </Sequence>+ ))}+ </>+ );+};diff --git a/packages/core/src/test/loop-validation.test.tsx b/packages/core/src/test/loop-validation.test.tsxnew file mode 100644index 0000000000..83750bad2c--- /dev/null+++ b/packages/core/src/test/loop-validation.test.tsx@@ -0,0 +1,125 @@+import {render} from '@testing-library/react';+import React, {useContext} from 'react';+import {Internals, LooseAnyComponent} from '..';+import {Loop} from '../loop';+import {expectToThrow} from './expect-to-throw';++const Wrapper: React.FC = ({children}) => {+ const compositions = useContext(Internals.CompositionManager);+ return (+ <Internals.RemotionRoot>+ <Internals.CompositionManager.Provider+ // eslint-disable-next-line react/jsx-no-constructed-context-values+ value={{+ ...compositions,+ compositions: [+ {+ height: 1080,+ width: 1080,+ fps: 30,+ durationInFrames: 30,+ id: 'markup',+ nonce: 0,+ component: React.lazy(() =>+ Promise.resolve({+ default: (() => null) as LooseAnyComponent<unknown>,+ })+ ),+ },+ ],+ currentComposition: 'markup',+ }}+ >+ {children}+ </Internals.CompositionManager.Provider>+ </Internals.RemotionRoot>+ );+};++describe('Loop-validation render should throw with invalid props', () => {+ describe('Throw with invalid durationInFrames prop', () => {+ test('It should throw if Loop has non-number durationInFrames', () => {+ expectToThrow(+ () =>+ render(+ <Wrapper>+ {/* @ts-expect-error */}+ <Loop durationInFrames={'1'}>hi</Loop>+ </Wrapper>+ ),+ /You passed to durationInFrames an argument of type string, but it must be a number./+ );+ });+ test('It should throw if Loop has non-integer durationInFrames', () => {+ expectToThrow(+ () =>+ render(+ <Wrapper>+ <Loop durationInFrames={1.1}>hi</Loop>+ </Wrapper>+ ),+ /The "durationInFrames" of a loop must be an integer, but got 1.1./+ );+ });+ test('It should throw if Loop has a negative duration', () => {+ expectToThrow(+ () =>+ render(+ <Wrapper>+ <Loop durationInFrames={-1}>hi</Loop>+ </Wrapper>+ ),+ /durationInFrames must be positive, but got -1./+ );+ });+ });+ describe('Throw with invalid times prop', () => {+ test('It should throw if Loop has non-number times', () => {+ expectToThrow(+ () =>+ render(+ <Wrapper>+ {/* @ts-expect-error */}+ <Loop durationInFrames={50} times="1">+ hi+ </Loop>+ </Wrapper>+ ),+ /You passed to "times" an argument of type string, but it must be a number./+ );+ });+ test('It should throw if Loop has non-integer times', () => {+ expectToThrow(+ () =>+ render(+ <Wrapper>+ <Loop durationInFrames={50} times={1.1}>+ hi+ </Loop>+ </Wrapper>+ ),+ /The "times" prop of a loop must be an integer, but got 1.1./+ );+ });+ });+ describe('Should NOT throw with valid props', () => {+ test('It should allow null as children', () => {+ expect(() =>+ render(+ <Wrapper>+ <Loop durationInFrames={50}>{null}</Loop>+ </Wrapper>+ )+ ).not.toThrow();+ });+ test('It should allow undefined as children', () => {+ expect(() =>+ render(+ <Wrapper>+ <Loop durationInFrames={50}>{undefined}</Loop>+ </Wrapper>+ )+ ).not.toThrow();+ });+ });+});diff --git a/packages/docs/components/LoopExamples/LoopExamples.tsx b/packages/docs/components/LoopExamples/LoopExamples.tsxnew file mode 100644index 0000000000..76766f81f7--- /dev/null+++ b/packages/docs/components/LoopExamples/LoopExamples.tsx@@ -0,0 +1,100 @@+import { Player } from "@remotion/player";+import React from "react";+import {+ AbsoluteFill,+ interpolate,+ Loop,+ spring,+ useCurrentFrame,+} from "remotion";++const BlueSquare: React.FC = () => {+ const frame = useCurrentFrame();+ const animation = spring({+ fps: 30,+ frame,+ config: {+ damping: 400,+ },+ });+ return (+ <AbsoluteFill style={{ justifyContent: "center", alignItems: "center" }}>+ <div+ style={{+ height: 200,+ width: 200,+ backgroundColor: "#3498db",+ borderRadius: 20,+ transform: `translateY(${interpolate(+ animation,+ [0, 1],+ [600, 0]+ )}px)`,+ justifyContent: "center",+ alignItems: "center",+ display: "flex",+ color: "rgba(255, 255, 255, 0.7)",+ fontSize: 50,+ }}+ >+ {frame}+ </div>+ </AbsoluteFill>+ );+};++const BaseExample: React.FC = () => (+ <Loop durationInFrames={50}>+ <BlueSquare />+ </Loop>+);++const TimesExample: React.FC = () => (+ <Loop durationInFrames={50} times={2}>+ <BlueSquare />+ </Loop>+);++const NestedExample: React.FC = () => (+ <Loop durationInFrames={75}>+ <Loop durationInFrames={30}>+ <BlueSquare />+ </Loop>+ </Loop>+);++export const LoopExamples: React.FC<{ type: "base" | "times" | "nested" }> = ({+ type,+}) => {+ const component = (() => {+ if (type === "base") {+ return BaseExample;+ }++ if (type === "times") {+ return TimesExample;+ }++ if (type === "nested") {+ return NestedExample;+ }++ return BlueSquare;+ })();+ return (+ <div>+ <Player+ component={component}+ compositionWidth={1280}+ compositionHeight={720}+ controls+ durationInFrames={150}+ fps={30}+ style={{+ width: "100%",+ }}+ loop+ />+ </div>+ );+};diff --git a/packages/docs/docs/loop.md b/packages/docs/docs/loop.mdnew file mode 100644index 0000000000..c830550be9--- /dev/null+++ b/packages/docs/docs/loop.md@@ -0,0 +1,89 @@+---+id: loop+title: <Loop />+sidebar_label: <Loop />+---++import { LoopExamples, BlueSquare } from "../components/LoopExamples/LoopExamples";++```twoslash include example+const BlueSquare: React.FC = () => <div></div>+// - BlueSquare+```++## API++The Sequence component is a high order component and accepts, besides it's children, the following props:++- `durationInFrames` _(required)_: How many frames of the content the loop should include. Children are unmounted if they are not within the time range of display.++- `times` _(optional)_: How many times to loop the content. By default it will be `Infinity`.++:::info+Good to know: You can nest loops within each other and they will cascade. For example, a loop that has a duration of 30 frames which is inside a loop that has a duration of 75 will play 2 times. However, nested loops are not currently displayed in the timeline.+:::++## Examples++All the examples below are based on the following animation of a blue square:++<LoopExamples />+<br />++```tsx twoslash+// @include: example-BlueSquare+// ---cut---+const MyVideo = () => {+ return <BlueSquare />+}+```++### Continuous loop++<LoopExamples type="base" />+<br />++```tsx twoslash+// @include: example-BlueSquare+import { Loop } from 'remotion'+// ---cut---+const MyVideo = () => {+ return <Loop durationInFrames={50}>+ <BlueSquare />+ </Loop>+}+```++### Fixed count loop++<LoopExamples type="times" />+<br />++```tsx twoslash+// @include: example-BlueSquare+import { Loop } from 'remotion'+// ---cut---+const MyVideo = () => {+ return <Loop durationInFrames={50} times={2}>+ <BlueSquare />+ </Loop>+}+```++### Nested loop++<LoopExamples type="nested" />+<br />++```tsx twoslash+// @include: example-BlueSquare+import { Loop } from 'remotion'+// ---cut---+const MyVideo = () => {+ return <Loop durationInFrames={75}>+ <Loop durationInFrames={30}>+ <BlueSquare />+ </Loop>+ </Loop>+}+```diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.jsindex 6e10591433..e2de6bbe0a 100644--- a/packages/docs/sidebars.js+++ b/packages/docs/sidebars.js@@ -59,6 +59,7 @@ module.exports = {"audio","composition","sequence",+ "loop","video","absolute-fill","img",diff --git a/packages/example/src/LoopedVideo/index.tsx b/packages/example/src/LoopedVideo/index.tsxnew file mode 100644index 0000000000..fb008e0688--- /dev/null+++ b/packages/example/src/LoopedVideo/index.tsx@@ -0,0 +1,31 @@+import React from 'react';+import {Loop, useCurrentFrame} from 'remotion';++const LoopedVideo: React.FC = () => {+ return (+ <Loop durationInFrames={50} times={2}>+ <Child />+ </Loop>+ );+};++const Child = () => {+ const frame = useCurrentFrame();++ return (+ <div+ style={{+ backgroundColor: 'white',+ flex: 1,+ justifyContent: 'center',+ alignItems: 'center',+ display: 'flex',+ fontSize: 50,+ }}+ >+ {frame}+ </div>+ );+};++export default LoopedVideo;diff --git a/packages/example/src/Video.tsx b/packages/example/src/Video.tsxindex 92e64abe4c..0d48cdbc90 100644--- a/packages/example/src/Video.tsx+++ b/packages/example/src/Video.tsx@@ -36,6 +36,14 @@ export const Index: React.FC = () => {height={1080}width={1080}/>+ <Composition+ id="looped"+ lazyComponent={() => import('./LoopedVideo')}+ durationInFrames={200}+ fps={60}+ height={1080}+ width={1080}+ /><Compositionid="beta-text"component={BetaText}