🎥 Make videos programmatically with React
let's continue tomorrow
JonnyBurgerd57de6e50d27
diff --git a/packages/transitions/src/TransitionSeries.tsx b/packages/transitions/src/TransitionSeries.tsxindex 37438cc458..6f30ac4480 100644--- a/packages/transitions/src/TransitionSeries.tsx+++ b/packages/transitions/src/TransitionSeries.tsx@@ -12,10 +12,8 @@ import {WrapInExitingProgressContext,} from './context.js';import {flattenChildren} from './flatten-children.js';-import {HtmlInCanvasOverlay} from './html-in-canvas-presentation.js';import {slide} from './presentations/slide.js';import type {- OverlayMethods,TransitionSeriesOverlayProps,TransitionSeriesTransitionProps,} from './types.js';@@ -73,13 +71,19 @@ type TypeChild<PresentationProps extends Record<string, unknown>> =| OverlayType| string;+export type DrawFunction = (+ prevImage: ElementImage | null,+ nextImage: ElementImage | null,+ progress: number,+) => void;+type ElementImageAndProgress = {elementImage: ElementImage | null;progress: number | null;+ draw: DrawFunction | null;};type ImageMap = Record<number, ElementImageAndProgress>;-type OverlayMethodsMap = Record<number, React.RefObject<OverlayMethods | null>>;const TransitionSeriesChildren: FC<{readonly children: React.ReactNode}> = ({children,@@ -94,44 +98,31 @@ const TransitionSeriesChildren: FC<{readonly children: React.ReactNode}> = ({return flattenChildren(children);}, [children]);- const refToMethods = useMemo(() => {- return flattedChildren.reduce<OverlayMethodsMap>((acc, _child, index) => {- acc[index] = React.createRef<OverlayMethods>();- acc[index].current = {- draw: () => {},- clear: () => {},- };- return acc;- }, {} as OverlayMethodsMap);- }, [flattedChildren]);-- const drawIfSynced = useCallback(- (index: number) => {- const prevImage = prevImageRef?.current?.[index];- const nextImage = nextImageRef?.current?.[index];-- if (- (prevImage && nextImage && prevImage.progress === nextImage.progress) ||- !prevImage?.elementImage ||- !nextImage?.elementImage- ) {- refToMethods[index]?.current?.draw(- prevImage?.elementImage ?? null,- nextImage?.elementImage ?? null,- prevImage?.progress ?? nextImage?.progress ?? 0,- );- }- },- [refToMethods],- );+ const drawIfSynced = useCallback((index: number) => {+ const prevImage = prevImageRef?.current?.[index];+ const nextImage = nextImageRef?.current?.[index];++ if (+ (prevImage && nextImage && prevImage.progress === nextImage.progress) ||+ !prevImage?.elementImage ||+ !nextImage?.elementImage+ ) {+ nextImage?.draw?.(+ prevImage?.elementImage ?? null,+ nextImage?.elementImage ?? null,+ prevImage?.progress ?? nextImage?.progress ?? 0,+ );+ }+ }, []);const onPreviousElementImage = useCallback((elementImage: ElementImage | null,progress: number | null,+ draw: DrawFunction | null,index: number,) => {- prevImageRef.current[index] = {elementImage, progress};+ prevImageRef.current[index] = {elementImage, progress, draw};drawIfSynced(index);},@@ -142,9 +133,10 @@ const TransitionSeriesChildren: FC<{readonly children: React.ReactNode}> = ({(elementImage: ElementImage | null,progress: number | null,+ draw: DrawFunction | null,index: number,) => {- nextImageRef.current[index] = {elementImage, progress};+ nextImageRef.current[index] = {elementImage, progress, draw};drawIfSynced(index);},@@ -477,11 +469,11 @@ const TransitionSeriesChildren: FC<{readonly children: React.ReactNode}> = ({presentationDurationInFrames={next.props.timing.getDurationInFrames({fps},)}- onElementImage={(elementImage, progress) =>- onNextElementImage(elementImage, progress, i + 1)+ onElementImage={(elementImage, progress, draw) =>+ onNextElementImage(elementImage, progress, draw, i + 1)}onUnmount={() => {- onNextElementImage(null, null, i + 1);+ onNextElementImage(null, null, null, i + 1);}}><WrapInExitingProgressContext presentationProgress={nextProgress}>@@ -492,11 +484,11 @@ const TransitionSeriesChildren: FC<{readonly children: React.ReactNode}> = ({presentationDurationInFrames={prev.props.timing.getDurationInFrames({fps},)}- onElementImage={(elementImage, progress) =>- onPreviousElementImage(elementImage, progress, i - 1)+ onElementImage={(elementImage, progress, draw) =>+ onPreviousElementImage(elementImage, progress, draw, i - 1)}onUnmount={() => {- onPreviousElementImage(null, null, i - 1);+ onPreviousElementImage(null, null, null, i - 1);}}><WrapInEnteringProgressContext@@ -507,13 +499,6 @@ const TransitionSeriesChildren: FC<{readonly children: React.ReactNode}> = ({</UppercasePrevPresentation></WrapInExitingProgressContext></UppercaseNextPresentation>- {prevPresentation.shader && (- <HtmlInCanvasOverlay- refToMethods={refToMethods[i - 1]}- shader={prevPresentation.shader}- passedProps={prevPresentation.props ?? {}}- />- )}</Sequence>);}@@ -539,11 +524,11 @@ const TransitionSeriesChildren: FC<{readonly children: React.ReactNode}> = ({presentationDurationInFrames={prev.props.timing.getDurationInFrames({fps},)}- onElementImage={(elementImage, progress) =>- onPreviousElementImage(elementImage, progress, i - 1)+ onElementImage={(elementImage, progress, draw) =>+ onPreviousElementImage(elementImage, progress, draw, i - 1)}onUnmount={() => {- onPreviousElementImage(null, null, i - 1);+ onPreviousElementImage(null, null, null, i - 1);}}><WrapInEnteringProgressContext@@ -552,13 +537,6 @@ const TransitionSeriesChildren: FC<{readonly children: React.ReactNode}> = ({{child}</WrapInEnteringProgressContext></UppercasePrevPresentation>- {prevPresentation.shader && (- <HtmlInCanvasOverlay- refToMethods={refToMethods[i - 1]}- passedProps={prevPresentation.props ?? {}}- shader={prevPresentation.shader}- />- )}</Sequence>);}@@ -584,24 +562,17 @@ const TransitionSeriesChildren: FC<{readonly children: React.ReactNode}> = ({presentationDurationInFrames={next.props.timing.getDurationInFrames({fps},)}- onElementImage={(elementImage, progress) =>- onNextElementImage(elementImage, progress, i + 1)+ onElementImage={(elementImage, progress, draw) =>+ onNextElementImage(elementImage, progress, draw, i + 1)}onUnmount={() => {- onNextElementImage(null, null, i + 1);+ onNextElementImage(null, null, null, i + 1);}}><WrapInExitingProgressContext presentationProgress={nextProgress}>{child}</WrapInExitingProgressContext></UppercaseNextPresentation>- {nextPresentation.shader && (- <HtmlInCanvasOverlay- refToMethods={refToMethods[i + 1]}- passedProps={nextPresentation.props ?? {}}- shader={nextPresentation.shader}- />- )}</Sequence>);}@@ -646,14 +617,7 @@ const TransitionSeriesChildren: FC<{readonly children: React.ReactNode}> = ({});return [...(mainChildren || []), ...overlayElements];- }, [- flattedChildren,- fps,- frame,- onNextElementImage,- onPreviousElementImage,- refToMethods,- ]);+ }, [flattedChildren, fps, frame, onNextElementImage, onPreviousElementImage]);// eslint-disable-next-line react/jsx-no-useless-fragmentreturn <>{childrenValue}</>;diff --git a/packages/transitions/src/html-in-canvas-presentation.tsx b/packages/transitions/src/html-in-canvas-presentation.tsxindex 8b33980e83..11c99dfdfa 100644--- a/packages/transitions/src/html-in-canvas-presentation.tsx+++ b/packages/transitions/src/html-in-canvas-presentation.tsx@@ -1,31 +1,26 @@-import {- useImperativeHandle,- useLayoutEffect,- useMemo,- useRef,- useState,-} from 'react';+import {useLayoutEffect, useMemo, useRef, useState, useCallback} from 'react';import type {EffectsProp} from 'remotion';-import {- AbsoluteFill,- Internals,- useCurrentFrame,- useVideoConfig,-} from 'remotion';+import {AbsoluteFill, Internals, useCurrentFrame} from 'remotion';+import type {DrawFunction} from './TransitionSeries';import type {- MandatoryOverlayComponentProps,TransitionPresentation,TransitionPresentationComponentProps,} from './types';-export const HtmlInCanvasPresentation: React.FC<- TransitionPresentationComponentProps<Record<string, unknown>>-> = ({+export const HtmlInCanvasPresentation = <+ TPassedProps extends Record<string, unknown>,+>({children,onElementImage,onUnmount,presentationProgress,presentationDirection,+ shader,+ _experimentalEffects,+ passedProps,+}: TransitionPresentationComponentProps<TPassedProps> & {+ readonly shader: () => HtmlInCanvasShader<TPassedProps>;+ readonly _experimentalEffects?: EffectsProp;}) => {const canvasRef = useRef<HTMLCanvasElement>(null);const canvasSubtreeStyle: React.CSSProperties = useMemo(() => {@@ -40,6 +35,70 @@ export const HtmlInCanvasPresentation: React.FC<};}, []);+ const [offscreenCanvas] = useState(() => new OffscreenCanvas(1, 1));++ const passedPropsRef = useRef(passedProps);+ passedPropsRef.current = passedProps;++ const frame = useCurrentFrame();+ const frameRef = useRef(frame);+ frameRef.current = frame;++ const effectsRef = useRef(_experimentalEffects);+ effectsRef.current = _experimentalEffects;++ const [instance] = useState(() => shader());++ useLayoutEffect(() => {+ instance.init(offscreenCanvas);++ return () => {+ instance.cleanup();+ };+ }, [offscreenCanvas, instance]);++ const chainState = Internals.useEffectChainState();++ const draw: DrawFunction = useCallback(+ (prevImage, nextImage, progress) => {+ if (!canvasRef.current) {+ return;+ }++ const width = prevImage?.width ?? nextImage?.width ?? 0;+ const height = prevImage?.height ?? nextImage?.height ?? 0;++ if (width === 0 || height === 0) {+ return;+ }++ offscreenCanvas.width = width;+ offscreenCanvas.height = height;++ instance.draw({+ prevImage,+ nextImage,+ width,+ height,+ time: progress,+ passedProps: passedPropsRef.current,+ });++ Internals.runEffectChain({+ state: chainState.get(width, height)!,+ source: offscreenCanvas,+ effects: effectsRef.current ?? [],+ frame: frameRef.current,+ width,+ height,+ output: canvasRef.current,+ });+ },+ [chainState, instance, offscreenCanvas],+ );++ // TODO: Implement clear()+const presentationProgressRef = useRef(presentationProgress);presentationProgressRef.current = presentationProgress;@@ -59,7 +118,7 @@ export const HtmlInCanvasPresentation: React.FC<}const elementImage = canvas.captureElementImage(firstChild);- onElementImage(elementImage, presentationProgressRef.current);+ onElementImage(elementImage, presentationProgressRef.current, draw);const context = canvas.getContext('2d');if (!context) {@@ -72,7 +131,7 @@ export const HtmlInCanvasPresentation: React.FC<return () => {canvas.removeEventListener('paint', onPaint);};- }, [onElementImage, presentationDirection]);+ }, [onElementImage, presentationDirection, draw]);useLayoutEffect(() => {const canvas = canvasRef.current;@@ -89,99 +148,25 @@ export const HtmlInCanvasPresentation: React.FC<};}, [onUnmount]);- return (- <AbsoluteFill>- <canvas ref={canvasRef} style={canvasSubtreeStyle}>- {children}- </canvas>- </AbsoluteFill>- );-};--export const HtmlInCanvasOverlay: React.FC<- MandatoryOverlayComponentProps<Record<string, unknown>>-> = ({refToMethods, passedProps, shader}) => {- const {width, height} = useVideoConfig();- const [offscreenCanvas] = useState(() => new OffscreenCanvas(width, height));- const canvasRef = useRef<HTMLCanvasElement>(null);-- const frame = useCurrentFrame();- const frameRef = useRef(frame);- frameRef.current = frame;- const passedPropsRef = useRef(passedProps);- passedPropsRef.current = passedProps;-- const [instance] = useState(() => shader());-useLayoutEffect(() => {- instance.init(offscreenCanvas);-- return () => {- instance.cleanup();- };- }, [offscreenCanvas, instance]);-- const chainState = Internals.useEffectChainState();-- useImperativeHandle(refToMethods, () => {- return {- draw: (- prevImage: ElementImage | null,- nextImage: ElementImage | null,- progress: number,- ) => {- console.log('draw!!');- if (!canvasRef.current) {- return;- }-- instance.draw({- prevImage,- nextImage,- width,- height,- time: progress,- passedProps: passedPropsRef.current,- });- offscreenCanvas.width = width;- offscreenCanvas.height = height;- Internals.runEffectChain({- state: chainState.get(width, height)!,- source: offscreenCanvas,- effects: passedPropsRef.current._experimentalEffects ?? [],- frame: frameRef.current,- width,- height,- output: canvasRef.current,- });- },- clear: () => {- instance.clear();- },- };- }, [chainState, height, instance, offscreenCanvas, width]);-- const outerStyle: React.CSSProperties = useMemo(() => {- return {- pointerEvents: 'none',- };- }, []);+ const canvas = canvasRef.current;+ if (!canvas) {+ return;+ }- const innerStyle: React.CSSProperties = useMemo(() => {- return {- width: '100%',- height: '100%',- };+ // Size the canvas grid to match the device scale factor to prevent blurriness.+ const observer = new ResizeObserver(([entry]) => {+ canvas.width = entry.devicePixelContentBoxSize[0].inlineSize;+ canvas.height = entry.devicePixelContentBoxSize[0].blockSize;+ });+ observer.observe(canvas, {box: 'device-pixel-content-box'});}, []);return (- <AbsoluteFill style={outerStyle}>- <canvas- ref={canvasRef}- width={width}- height={height}- style={innerStyle}- />+ <AbsoluteFill>+ <canvas ref={canvasRef} style={canvasSubtreeStyle}>+ {children}+ </canvas></AbsoluteFill>);};@@ -206,11 +191,25 @@ export const makeHtmlInCanvasPresentation = <shader: () => HtmlInCanvasShader<TPassedProps>,) => {type AugmentedProps = TPassedProps & {_experimentalEffects?: EffectsProp};+ const CompWithShader: React.FC<+ TransitionPresentationComponentProps<AugmentedProps>+ > = (props) => {+ const {passedProps, ...otherProps} = props;+ const {_experimentalEffects, ...restPassedProps} = props.passedProps;+ return (+ <HtmlInCanvasPresentation+ shader={shader}+ passedProps={restPassedProps as TPassedProps}+ _experimentalEffects={_experimentalEffects}+ {...otherProps}+ />+ );+ };+return (props: AugmentedProps): TransitionPresentation<AugmentedProps> => {return {- component: HtmlInCanvasPresentation,+ component: CompWithShader,props,- shader,};};};diff --git a/packages/transitions/src/types.ts b/packages/transitions/src/types.tsindex 730fb2cfc3..7edfdb6e07 100644--- a/packages/transitions/src/types.ts+++ b/packages/transitions/src/types.ts@@ -2,6 +2,7 @@ import type {ComponentType} from 'react';import type React from 'react';import type {EffectsProp} from 'remotion';import type {HtmlInCanvasShader} from './html-in-canvas-presentation';+import type {DrawFunction} from './TransitionSeries';export type PresentationDirection = 'entering' | 'exiting';@@ -45,7 +46,6 @@ export type TransitionPresentation<TransitionPresentationComponentProps<PresentationProps>>;props: PresentationProps;- shader?: () => HtmlInCanvasShader<PresentationProps>;};export type TransitionPresentationComponentProps<@@ -56,7 +56,11 @@ export type TransitionPresentationComponentProps<presentationDirection: PresentationDirection;passedProps: PresentationProps;presentationDurationInFrames: number;- onElementImage: (elementImage: ElementImage, progress: number) => void;+ onElementImage: (+ elementImage: ElementImage,+ progress: number,+ draw: DrawFunction,+ ) => void;onUnmount: () => void;};