π₯ Make videos programmatically with React
cool
JonnyBurger421d9700edee
diff --git a/packages/core/src/HtmlInCanvas.tsx b/packages/core/src/HtmlInCanvas.tsxindex 6ef61f31a2..22abefb74e 100644--- a/packages/core/src/HtmlInCanvas.tsx+++ b/packages/core/src/HtmlInCanvas.tsx@@ -1,4 +1,5 @@import React, {+ forwardRef,useCallback,useLayoutEffect,useMemo,@@ -237,6 +238,7 @@ const defaultOnPaint: HtmlInCanvasOnPaint = ({element.style.transform = transform.toString();};+/* eslint-disable react/require-default-props -- optional fields mirror `<Sequence>` / canvas hooks API */export type HtmlInCanvasProps = Omit<SequenceProps,'children' | 'durationInFrames' | keyof LayoutAndStyle@@ -257,6 +259,7 @@ export type HtmlInCanvasProps = Omit<readonly onPaint?: HtmlInCanvasOnPaint;readonly onInit?: HtmlInCanvasOnInit;};+/* eslint-enable react/require-default-props */const htmlInCanvasSchema = {'style.translate': {@@ -289,228 +292,254 @@ const htmlInCanvasSchema = {},} as const satisfies SequenceSchema;-const HtmlInCanvasInner: React.FC<+const HtmlInCanvasInner = forwardRef<+ HTMLCanvasElement,HtmlInCanvasProps & {readonly controls: SequenceControls | undefined;}-> = ({- width,- height,- _experimentalEffects: experimentalEffects = [],- children,- onPaint,- onInit,- controls,- style,- durationInFrames,-- ...sequenceProps-}) => {- assertHtmlInCanvasDimensions(width, height);- const {continueRender, cancelRender} = useDelayRender();-- if (!isHtmlInCanvasSupported()) {- cancelRender(- new Error(- 'HTML in Canvas is not supported. Open this page in Chrome Canary with chrome://flags/#canvas-draw-element enabled.',- ),- );- }+>(+ (+ {+ width,+ height,+ _experimentalEffects: experimentalEffects = [],+ children,+ onPaint,+ onInit,+ controls,+ style,+ durationInFrames,+ ...sequenceProps+ },+ ref,+ ) => {+ assertHtmlInCanvasDimensions(width, height);+ const {continueRender, cancelRender} = useDelayRender();++ if (!isHtmlInCanvasSupported()) {+ cancelRender(+ new Error(+ 'HTML in Canvas is not supported. Open this page in Chrome Canary with chrome://flags/#canvas-draw-element enabled.',+ ),+ );+ }- const {durationInFrames: videoDuration} = useVideoConfig();- const resolvedDuration = durationInFrames ?? videoDuration;+ const {durationInFrames: videoDuration} = useVideoConfig();+ const resolvedDuration = durationInFrames ?? videoDuration;- const frame = useCurrentFrame();+ const frame = useCurrentFrame();- const canvas2dRef = useRef<HTMLCanvasElement | null>(null);- const divRef = useRef<HTMLDivElement | null>(null);- const [offscreenCanvas] = useState(() => new OffscreenCanvas(1, 1));+ const canvas2dRef = useRef<HTMLCanvasElement | null>(null);+ const divRef = useRef<HTMLDivElement | null>(null);++ const setLayoutCanvasRef = useCallback(+ (node: HTMLCanvasElement | null) => {+ canvas2dRef.current = node;+ if (typeof ref === 'function') {+ ref(node);+ } else if (ref) {+ (ref as React.MutableRefObject<HTMLCanvasElement | null>).current =+ node;+ }+ },+ [ref],+ );+ const [offscreenCanvas] = useState(() => new OffscreenCanvas(1, 1));++ const chainState = useEffectChainState();++ // Refs so the paint handler always reads fresh values.+ const effectsRef = useRef(experimentalEffects);+ effectsRef.current = experimentalEffects;+ const frameRef = useRef(frame);+ frameRef.current = frame;+ const onPaintRef = useRef(onPaint);+ onPaintRef.current = onPaint;+ const onInitRef = useRef(onInit);+ onInitRef.current = onInit;+ const initializedRef = useRef(false);+ const onInitCleanupRef = useRef<HtmlInCanvasOnInitCleanup | null>(null);+ const unmountedRef = useRef(false);++ const onPaintCb = useCallback(async () => {+ const element = divRef.current;++ if (!element) {+ throw new Error('Canvas or scene element not found');+ }- const chainState = useEffectChainState();+ offscreenCanvas.width = width;+ offscreenCanvas.height = height;- // Refs so the paint handler always reads fresh values.- const effectsRef = useRef(experimentalEffects);- effectsRef.current = experimentalEffects;- const frameRef = useRef(frame);- frameRef.current = frame;- const onPaintRef = useRef(onPaint);- onPaintRef.current = onPaint;- const onInitRef = useRef(onInit);- onInitRef.current = onInit;- const initializedRef = useRef(false);- const onInitCleanupRef = useRef<HtmlInCanvasOnInitCleanup | null>(null);- const unmountedRef = useRef(false);+ try {+ const layoutCanvas = canvas2dRef.current;+ if (!layoutCanvas) {+ throw new Error('Canvas not found');+ }- const onPaintCb = useCallback(async () => {- const element = divRef.current;+ // `GPUQueue.copyElementImageToTexture` / related paths validate the+ // layout canvas has a rendering context. `runEffectChain` only runs+ // after `onPaint`, so acquire `2d` here before any capture or handler.+ const layout2d = layoutCanvas.getContext('2d');+ if (!layout2d) {+ throw new Error(+ 'Failed to acquire 2D context for <HtmlInCanvas> layout canvas',+ );+ }- if (!element) {- throw new Error('Canvas or scene element not found');- }+ const handle = delayRender('onPaint');+ if (!initializedRef.current) {+ initializedRef.current = true;+ // `onInit` may be async (e.g. WebGPU `requestAdapter`/`requestDevice`).+ // Capture an `ElementImage` here only for `onInit` consumers β do NOT+ // reuse it for the paint handler below, because awaiting `onInit`+ // can invalidate the capture's paint context, leaving subsequent+ // uploads (e.g. `copyElementImageToTexture`) failing with+ // "No context found for ElementImage" on the very first paint.+ const initImage = layoutCanvas.captureElementImage(element);+ const currentOnInit = onInitRef.current;+ if (currentOnInit) {+ const cleanup = await currentOnInit({+ canvas: offscreenCanvas,+ element,+ elementImage: initImage!,+ });+ if (typeof cleanup !== 'function') {+ throw new Error(+ 'HtmlInCanvas: when `onInit` is provided, it must return a cleanup function, or a Promise that resolves to one.',+ );+ }++ if (unmountedRef.current) {+ cleanup();+ } else {+ onInitCleanupRef.current = cleanup;+ }+ }+ }- offscreenCanvas.width = width;- offscreenCanvas.height = height;+ const handler = onPaintRef.current ?? defaultOnPaint;++ const elImage = layoutCanvas.captureElementImage(element);+ await handler({+ canvas: offscreenCanvas,+ element,+ elementImage: elImage!,+ });++ await runEffectChain({+ state: chainState.get(width, height)!,+ source: offscreenCanvas,+ effects: effectsRef.current,+ output: canvas2dRef.current!,+ frame: frameRef.current,+ width,+ height,+ });- try {- const layoutCanvas = canvas2dRef.current;- if (!layoutCanvas) {+ continueRender(handle);+ } catch (error) {+ cancelRender(error);+ }+ }, [+ chainState,+ continueRender,+ cancelRender,+ width,+ height,+ offscreenCanvas,+ ]);++ // Set up layoutSubtree and persistent paint listener. Runs as a+ // layout effect so the listener is attached before the resize effect+ // below dispatches its first synthetic paint.+ useLayoutEffect(() => {+ const canvas = canvas2dRef.current;+ if (!canvas) {throw new Error('Canvas not found');}- // `GPUQueue.copyElementImageToTexture` / related paths validate the- // layout canvas has a rendering context. `runEffectChain` only runs- // after `onPaint`, so acquire `2d` here before any capture or handler.- const layout2d = layoutCanvas.getContext('2d');- if (!layout2d) {- throw new Error(- 'Failed to acquire 2D context for <HtmlInCanvas> layout canvas',- );+ canvas.layoutSubtree = true;+ canvas.addEventListener('paint', onPaintCb);++ return () => {+ canvas.removeEventListener('paint', onPaintCb);+ unmountedRef.current = true;+ onInitCleanupRef.current?.();+ onInitCleanupRef.current = null;+ };+ }, [onPaintCb, cancelRender]);++ const onPaintChangedRef = useRef(false);+ useLayoutEffect(() => {+ if (!onPaintChangedRef.current) {+ onPaintChangedRef.current = true;+ return;}- const handle = delayRender('onPaint');- if (!initializedRef.current) {- initializedRef.current = true;- // `onInit` may be async (e.g. WebGPU `requestAdapter`/`requestDevice`).- // Capture an `ElementImage` here only for `onInit` consumers β do NOT- // reuse it for the paint handler below, because awaiting `onInit`- // can invalidate the capture's paint context, leaving subsequent- // uploads (e.g. `copyElementImageToTexture`) failing with- // "No context found for ElementImage" on the very first paint.- const initImage = layoutCanvas.captureElementImage(element);- const currentOnInit = onInitRef.current;- if (currentOnInit) {- const cleanup = await currentOnInit({- canvas: offscreenCanvas,- element,- elementImage: initImage!,- });- if (typeof cleanup !== 'function') {- throw new Error(- 'HtmlInCanvas: when `onInit` is provided, it must return a cleanup function, or a Promise that resolves to one.',- );- }+ const canvas = canvas2dRef.current;+ if (!canvas) {+ return;+ }- if (unmountedRef.current) {- cleanup();- } else {- onInitCleanupRef.current = cleanup;- }- }+ canvas.requestPaint?.();+ }, [onPaint]);++ useLayoutEffect(() => {+ const canvas = canvas2dRef.current;+ if (!canvas) {+ return;}- const handler = onPaintRef.current ?? defaultOnPaint;+ const handle = delayRender('waiting for first paint after canvas resize');+ canvas.addEventListener(+ 'paint',+ () => {+ continueRender(handle);+ },+ {once: true},+ );- const elImage = layoutCanvas.captureElementImage(element);- await handler({canvas: offscreenCanvas, element, elementImage: elImage!});+ return () => {+ continueRender(handle);+ };+ }, [width, height, continueRender]);- await runEffectChain({- state: chainState.get(width, height)!,- source: offscreenCanvas,- effects: effectsRef.current,- output: canvas2dRef.current!,- frame: frameRef.current,+ const innerStyle = useMemo(() => {+ return {width,height,- });-- continueRender(handle);- } catch (error) {- cancelRender(error);- }- }, [- chainState,- continueRender,- cancelRender,- width,- height,- offscreenCanvas,- ]);-- // Set up layoutSubtree and persistent paint listener. Runs as a- // layout effect so the listener is attached before the resize effect- // below dispatches its first synthetic paint.- useLayoutEffect(() => {- const canvas = canvas2dRef.current;- if (!canvas) {- throw new Error('Canvas not found');- }-- canvas.layoutSubtree = true;- canvas.addEventListener('paint', onPaintCb);-- return () => {- canvas.removeEventListener('paint', onPaintCb);- unmountedRef.current = true;- onInitCleanupRef.current?.();- onInitCleanupRef.current = null;- };- }, [onPaintCb, cancelRender]);-- const onPaintChangedRef = useRef(false);- useLayoutEffect(() => {- if (!onPaintChangedRef.current) {- onPaintChangedRef.current = true;- return;- }-- const canvas = canvas2dRef.current;- if (!canvas) {- return;- }-- canvas.requestPaint?.();- }, [onPaint]);-- useLayoutEffect(() => {- const canvas = canvas2dRef.current;- if (!canvas) {- return;- }-- const handle = delayRender('waiting for first paint after canvas resize');- canvas.addEventListener(- 'paint',- () => {- continueRender(handle);- },- {once: true},+ ...style,+ };+ }, [width, height, style]);++ return (+ <Sequence+ durationInFrames={resolvedDuration}+ name="<HtmlInCanvas>"+ controls={controls}+ layout="none"+ {...sequenceProps}+ >+ <canvas ref={setLayoutCanvasRef} width={width} height={height}>+ <div ref={divRef} style={innerStyle}>+ {children}+ </div>+ </canvas>+ </Sequence>);+ },+);- return () => {- continueRender(handle);- };- }, [width, height, continueRender]);-- const innerStyle = useMemo(() => {- return {- width,- height,- ...style,- };- }, [width, height, style]);-- return (- <Sequence- durationInFrames={resolvedDuration}- name="<HtmlInCanvas>"- controls={controls}- layout="none"- {...sequenceProps}- >- <canvas ref={canvas2dRef} width={width} height={height}>- <div ref={divRef} style={innerStyle}>- {children}- </div>- </canvas>- </Sequence>- );-};+HtmlInCanvasInner.displayName = 'HtmlInCanvas';const HtmlInCanvasWrapped = wrapInSchema(HtmlInCanvasInner, htmlInCanvasSchema);export const HtmlInCanvas = Object.assign(HtmlInCanvasWrapped, {isHtmlInCanvasSupported,-}) as typeof HtmlInCanvasWrapped & {+}) as React.ForwardRefExoticComponent<+ HtmlInCanvasProps & React.RefAttributes<HTMLCanvasElement>+> & {readonly isHtmlInCanvasSupported: typeof isHtmlInCanvasSupported;};diff --git a/packages/core/src/canvas-effects/effect-types.ts b/packages/core/src/canvas-effects/effect-types.tsindex 190c0e0bb6..5acc8846f7 100644--- a/packages/core/src/canvas-effects/effect-types.ts+++ b/packages/core/src/canvas-effects/effect-types.ts@@ -1,4 +1,4 @@-// Public types for the canvas-effects system.+// Internal types for the canvas-effects system (exported via `remotion` β `./internals.js`).//// An effect is a description of how to transform an input image into an output// image, executed inside a per-frame chain runtime owned by a source component@@ -9,7 +9,7 @@// sRGB-encoded. Effects that perform color math in linear space are responsible// for converting to/from sRGB themselves.-import type {SequenceSchema} from '../internals';+import type {SequenceSchema} from '../sequence-field-schema.js';export type Backend = '2d' | 'webgl2' | 'webgpu';@@ -48,7 +48,7 @@ export type EffectDescriptor<P = unknown> = EffectDefinitionAndStack<P> & {readonly params: P;};-// Public prop type for `effects`: callers may interleave single descriptors+// Prop type for `effects`: callers may interleave single descriptors// with arrays of descriptors. The runtime calls `.flat()` once before// processing, which lets a single factory call (e.g. `blur(...)`) expand into// multiple passes (e.g. horizontal + vertical) without leaking that detail todiff --git a/packages/core/src/canvas-effects/index.ts b/packages/core/src/canvas-effects/index.tsindex 9b2119cf56..93129fa1cd 100644--- a/packages/core/src/canvas-effects/index.ts+++ b/packages/core/src/canvas-effects/index.ts@@ -1,8 +1,2 @@-export type {- Backend,- EffectApplyParams,- EffectDefinition,- EffectDefinitionAndStack,- EffectDescriptor,- EffectsProp,-} from './effect-types.js';+// Only types needed outside core for `_experimentalEffects` prop typing.+export type {EffectDefinitionAndStack, EffectsProp} from './effect-types.js';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 7f2127ec84..ddd9f71a21 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -131,12 +131,8 @@ export type BundleState =checkMultipleRemotionVersions();export * from './AbsoluteFill.js';export * from './animated-image/index.js';-export {- Backend,- EffectApplyParams,- EffectDefinition,+export type {EffectDefinitionAndStack,- EffectDescriptor,EffectsProp,} from './canvas-effects/index.js';export type {SolidProps} from './canvas-effects/Solid.js';diff --git a/packages/docs/docs/remotion/html-in-canvas.mdx b/packages/docs/docs/remotion/html-in-canvas.mdxindex 2b4eb432a2..38525c36b6 100644--- a/packages/docs/docs/remotion/html-in-canvas.mdx+++ b/packages/docs/docs/remotion/html-in-canvas.mdx@@ -109,6 +109,28 @@ Inherited from [`<Sequence>`](/docs/sequence#durationinframes).Inherited from [`<Sequence>`](/docs/sequence#from).+### `ref?`++You can add a [React ref](https://react.dev/learn/manipulating-the-dom-with-refs) to `<HtmlInCanvas />`.+It is attached to the layout [`HTMLCanvasElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement) β the canvas that hosts the laid-out subtree (`layoutSubtree`).++If you use TypeScript, type the ref with `HTMLCanvasElement`:++```tsx twoslash title="src/Example.tsx"+import React, {useRef} from 'react';+import {AbsoluteFill, HtmlInCanvas} from 'remotion';++export const Example: React.FC = () => {+ const canvasRef = useRef<HTMLCanvasElement>(null);++ return (+ <HtmlInCanvas ref={canvasRef} width={1280} height={720}>+ <AbsoluteFill style={{fontSize: 80}}>Hello</AbsoluteFill>+ </HtmlInCanvas>+ );+};+```+## `onPaint` examples### 2Ddiff --git a/packages/transitions/src/presentations/zoom-blur.tsx b/packages/transitions/src/presentations/zoom-blur.tsxindex e381912886..ae1f29beee 100644--- a/packages/transitions/src/presentations/zoom-blur.tsx+++ b/packages/transitions/src/presentations/zoom-blur.tsx@@ -5,7 +5,7 @@ export type ZoomBlurProps = {rotation?: number;};-export type GLState = {+type GLState = {gl: WebGL2RenderingContext;program: WebGLProgram;prevTex: WebGLTexture;