Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/transitions`: Add `blurSlide()` HTML-in-canvas presentation

Cursor Agent0f1fb9fe0336
diff --git a/packages/docs/components/TableOfContents/transitions/presentations.tsx b/packages/docs/components/TableOfContents/transitions/presentations.tsx
index 2f2d0c3a74..cba7190193 100644
--- a/packages/docs/components/TableOfContents/transitions/presentations.tsx
+++ b/packages/docs/components/TableOfContents/transitions/presentations.tsx
@@ -9,6 +9,7 @@ import {pushCut} from '@remotion/transitions/push-cut';
import {slide} from '@remotion/transitions/slide';
import {wipe} from '@remotion/transitions/wipe';
import React from 'react';
+import {BlurSlideTocPreview} from '../../transitions/blur-slide-toc-preview';
import {BookFlipTocPreview} from '../../transitions/book-flip-toc-preview';
import {CrossZoomTocPreview} from '../../transitions/cross-zoom-toc-preview';
import {CrosswarpTocPreview} from '../../transitions/crosswarp-toc-preview';
@@ -309,6 +310,18 @@ export const Presentations: React.FC<{
</div>
</div>
</TOCItem>
+ <TOCItem link="/docs/transitions/presentations/blur-slide">
+ <div style={row}>
+ <BlurSlideTocPreview />
+ <div style={{flex: 1, marginLeft: 10}}>
+ <strong>
+ <code>{'blurSlide()'}</code>
+ </strong>
+ <HtmlInCanvasLabel />
+ <div>Whip both scenes sideways with a motion blur</div>
+ </div>
+ </div>
+ </TOCItem>
<TOCItem link="/docs/transitions/presentations/cube">
<div style={row}>
diff --git a/packages/docs/components/demos/BlurSlideDemo.tsx b/packages/docs/components/demos/BlurSlideDemo.tsx
new file mode 100644
index 0000000000..cf4294631c
--- /dev/null
+++ b/packages/docs/components/demos/BlurSlideDemo.tsx
@@ -0,0 +1,21 @@
+import React from 'react';
+import {AbsoluteFill} from 'remotion';
+import {BlurSlideTransitionPreview} from '../transitions/blur-slide-preview';
+import {HtmlInCanvasDocsVideoFallback} from './HtmlInCanvasDocsVideoFallback';
+import {useHtmlInCanvasDocsDemoBranch} from './useHtmlInCanvasDocsDemoBranch';
+
+export const BlurSlideDocsDemo: React.FC = () => {
+ const branch = useHtmlInCanvasDocsDemoBranch();
+
+ if (branch === 'pending') {
+ return <AbsoluteFill style={{backgroundColor: '#000'}} />;
+ }
+
+ if (branch === 'fallback') {
+ return (
+ <HtmlInCanvasDocsVideoFallback relativeSrc="img/blur-slide-transition.mp4" />
+ );
+ }
+
+ return <BlurSlideTransitionPreview />;
+};
diff --git a/packages/docs/components/demos/index.tsx b/packages/docs/components/demos/index.tsx
index b082c51b2c..787889bad6 100644
--- a/packages/docs/components/demos/index.tsx
+++ b/packages/docs/components/demos/index.tsx
@@ -12,6 +12,7 @@ import type {DemoType, Option} from './types';
import {
animationMathDemo,
arrowDemo,
+ blurSlidePresentationDemo,
bookFlipPresentationDemo,
calloutDemo,
circleDemo,
@@ -177,6 +178,7 @@ const demos: DemoType[] = [
crosswarpPresentationDemo,
crossZoomPresentationDemo,
swapPresentationDemo,
+ blurSlidePresentationDemo,
];
const shouldShowOption = (
diff --git a/packages/docs/components/demos/types.ts b/packages/docs/components/demos/types.ts
index 130b06b6bc..6af614b487 100644
--- a/packages/docs/components/demos/types.ts
+++ b/packages/docs/components/demos/types.ts
@@ -13,6 +13,7 @@ import {
WipeDemo,
} from '../transitions/previews';
import {ArrowDemo} from './Arrow';
+import {BlurSlideDocsDemo} from './BlurSlideDemo';
import {BookFlipDocsDemo} from './BookFlipDemo';
import {CalloutDemo} from './Callout';
import {CircleDemo} from './Circle';
@@ -1254,6 +1255,19 @@ export const swapPresentationDemo: DemoType = {
options: [],
};
+export const blurSlidePresentationDemo: DemoType = {
+ comp: BlurSlideDocsDemo,
+ compHeight: 1080,
+ compWidth: 1920,
+ durationInFrames: 90,
+ fps: 30,
+ id: 'blur-slide',
+ autoPlay: true,
+ controls: false,
+ logLevel: 'info',
+ options: [],
+};
+
export const customPresentationDemo: DemoType = {
comp: CustomTransitionDemo,
compHeight: 280,
diff --git a/packages/docs/components/transitions/blur-slide-preview.tsx b/packages/docs/components/transitions/blur-slide-preview.tsx
new file mode 100644
index 0000000000..93fa74b495
--- /dev/null
+++ b/packages/docs/components/transitions/blur-slide-preview.tsx
@@ -0,0 +1,73 @@
+import {linearTiming, TransitionSeries} from '@remotion/transitions';
+import {blurSlide} from '@remotion/transitions/blur-slide';
+import React from 'react';
+import {AbsoluteFill, Img} from 'remotion';
+
+const sceneStyle: React.CSSProperties = {
+ justifyContent: 'center',
+ alignItems: 'center',
+ fontFamily: 'sans-serif',
+ fontWeight: 900,
+ color: 'white',
+ fontSize: '40cqmin',
+};
+
+const backgroundImageStyle: React.CSSProperties = {
+ position: 'absolute',
+ inset: 0,
+ width: '100%',
+ height: '100%',
+ objectFit: 'cover',
+};
+
+const letterStyle: React.CSSProperties = {
+ position: 'relative',
+ textShadow: '0 4px 30px rgba(0, 0, 0, 0.55)',
+};
+
+const SceneA: React.FC = () => {
+ return (
+ <AbsoluteFill style={sceneStyle}>
+ <Img
+ crossOrigin="anonymous"
+ src="https://remotion.media/transition-bg-blue.jpg"
+ style={backgroundImageStyle}
+ alt=""
+ />
+ <div style={letterStyle}>A</div>
+ </AbsoluteFill>
+ );
+};
+
+const SceneB: React.FC = () => {
+ return (
+ <AbsoluteFill style={sceneStyle}>
+ <Img
+ crossOrigin="anonymous"
+ src="https://remotion.media/transition-bg-pink.jpg"
+ style={backgroundImageStyle}
+ alt=""
+ />
+ <div style={letterStyle}>B</div>
+ </AbsoluteFill>
+ );
+};
+
+export const BlurSlideTransitionPreview: React.FC = () => {
+ return (
+ <AbsoluteFill style={{containerType: 'size'}}>
+ <TransitionSeries>
+ <TransitionSeries.Sequence durationInFrames={60}>
+ <SceneA />
+ </TransitionSeries.Sequence>
+ <TransitionSeries.Transition
+ presentation={blurSlide()}
+ timing={linearTiming({durationInFrames: 30})}
+ />
+ <TransitionSeries.Sequence durationInFrames={60}>
+ <SceneB />
+ </TransitionSeries.Sequence>
+ </TransitionSeries>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/docs/components/transitions/blur-slide-toc-preview.tsx b/packages/docs/components/transitions/blur-slide-toc-preview.tsx
new file mode 100644
index 0000000000..2a8fa7ffc7
--- /dev/null
+++ b/packages/docs/components/transitions/blur-slide-toc-preview.tsx
@@ -0,0 +1,35 @@
+import React from 'react';
+import {staticFile} from 'remotion';
+import {
+ presentationCompositionHeight,
+ presentationCompositionWidth,
+} from '../TableOfContents/transitions/presentations';
+
+export const BlurSlideTocPreview: React.FC = () => {
+ const tileHeight = 60;
+ const tileWidth =
+ (tileHeight * presentationCompositionWidth) / presentationCompositionHeight;
+ const sharedStyle: React.CSSProperties = {
+ width: tileWidth,
+ height: tileHeight,
+ flex: 'none',
+ borderRadius: 6,
+ display: 'block',
+ objectFit: 'cover',
+ };
+
+ return (
+ <video
+ muted
+ playsInline
+ preload="auto"
+ src={staticFile('img/blur-slide-transition-thumb.mp4')}
+ style={sharedStyle}
+ onPointerEnter={(event) => {
+ const video = event.currentTarget;
+ video.currentTime = 0;
+ video.play();
+ }}
+ />
+ );
+};
diff --git a/packages/docs/docs/transitions/presentations/blur-slide.mdx b/packages/docs/docs/transitions/presentations/blur-slide.mdx
new file mode 100644
index 0000000000..bc39fa6d3d
--- /dev/null
+++ b/packages/docs/docs/transitions/presentations/blur-slide.mdx
@@ -0,0 +1,110 @@
+---
+crumb: '@remotion/transitions - Presentations'
+title: 'blurSlide()'
+---
+
+# blurSlide()<AvailableFrom v="4.0.523"/>
+
+A presentation that whips both scenes in one direction with a heavy motion blur, like a fast camera pan.
+
+The exiting scene slides out and wraps around the edges, and the entering scene slides in behind it. The blur is strongest halfway through the transition and both scenes are sharp at the start and the end.
+
+<Demo type="blur-slide" />
+
+:::warning
+This presentation is built with [HTML-in-canvas](/docs/remotion/html-in-canvas) and requires [Google Chrome](https://www.google.com/chrome/) with `chrome://flags/#canvas-draw-element` enabled. It does not work in Firefox or Safari.
+:::
+
+## Example
+
+```tsx twoslash title="BlurSlideTransition.tsx"
+import {AbsoluteFill} from 'remotion';
+
+const Letter: React.FC<{
+ children: React.ReactNode;
+ color: string;
+}> = ({children, color}) => {
+ return (
+ <AbsoluteFill
+ style={{
+ backgroundColor: color,
+ opacity: 0.9,
+ justifyContent: 'center',
+ alignItems: 'center',
+ fontSize: 200,
+ color: 'white',
+ }}
+ >
+ {children}
+ </AbsoluteFill>
+ );
+};
+// ---cut---
+import {linearTiming, TransitionSeries} from '@remotion/transitions';
+import {blurSlide} from '@remotion/transitions/blur-slide';
+
+const BasicTransition = () => {
+ return (
+ <TransitionSeries>
+ <TransitionSeries.Sequence durationInFrames={40}>
+ <Letter color="#0b84f3">A</Letter>
+ </TransitionSeries.Sequence>
+ <TransitionSeries.Transition
+ presentation={blurSlide({direction: 'from-left'})}
+ timing={linearTiming({durationInFrames: 20})}
+ />
+ <TransitionSeries.Sequence durationInFrames={60}>
+ <Letter color="pink">B</Letter>
+ </TransitionSeries.Sequence>
+ </TransitionSeries>
+ );
+};
+```
+
+The slide is eased so that it starts and ends at rest. [`linearTiming()`](/docs/transitions/timings/lineartiming) is a good choice for this presentation.
+
+## API
+
+Accepts an object with the following options:
+
+### `direction?`
+
+One of `from-left`, `from-right`, `from-top`, `from-bottom`. Determines from which side the entering scene slides in.
+
+Defaults to `from-left`.
+
+```tsx twoslash title="TypeScript type"
+import {BlurSlideDirection} from '@remotion/transitions/blur-slide';
+
+const direction: BlurSlideDirection = 'from-left';
+```
+
+### `blur?`
+
+The maximum length of the motion blur, as a fraction of the frame size along the slide direction. `0.5` blurs across half of the frame at the midpoint of the transition. Must be `0` or greater.
+
+Defaults to `0.5`.
+
+## Compatibility
+
+<CompatibilityTable
+ chrome
+ firefox={false}
+ safari={false}
+ nodejs
+ bun
+ serverlessFunctions
+ clientSideRendering
+ serverSideRendering
+ player
+ studio
+/>
+
+For Preview, Chrome with the `chrome://flags/#canvas-draw-element` flag enabled is required.
+
+## See also
+
+- [Source code for this presentation](https://github.com/remotion-dev/remotion/blob/main/packages/transitions/src/presentations/blur-slide.tsx)
+- [`slide()`](/docs/transitions/presentations/slide) β€” the CSS-based slide without blur
+- [HTML-in-canvas](/docs/client-side-rendering/html-in-canvas)
+- [Presentations](/docs/transitions/presentations)
diff --git a/packages/docs/docs/transitions/presentations/custom-html-in-canvas.mdx b/packages/docs/docs/transitions/presentations/custom-html-in-canvas.mdx
index 53150c9bb1..254d6f85ef 100644
--- a/packages/docs/docs/transitions/presentations/custom-html-in-canvas.mdx
+++ b/packages/docs/docs/transitions/presentations/custom-html-in-canvas.mdx
@@ -140,6 +140,7 @@ See the following example implementations:
- [`zoom-blur.tsx`](https://github.com/remotion-dev/remotion/blob/main/packages/transitions/src/presentations/zoom-blur.tsx)
- [`zoom-in-out.tsx`](https://github.com/remotion-dev/remotion/blob/main/packages/transitions/src/presentations/zoom-in-out.tsx) β€” adapted from a gl-transitions shader
- [`swap.tsx`](https://github.com/remotion-dev/remotion/blob/main/packages/transitions/src/presentations/swap.tsx) β€” adapted from a gl-transitions shader
+- [`blur-slide.tsx`](https://github.com/remotion-dev/remotion/blob/main/packages/transitions/src/presentations/blur-slide.tsx) β€” a two-pass shader that renders into an intermediate framebuffer
## See also
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index c44219dde1..835548fac4 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -914,6 +914,7 @@ const sidebars: SidebarsConfig = {
'transitions/presentations/crosswarp',
'transitions/presentations/cross-zoom',
'transitions/presentations/swap',
+ 'transitions/presentations/blur-slide',
'transitions/presentations/none',
{
type: 'doc',
diff --git a/packages/example/src/HtmlInCanvas/blur-slide-doc.tsx b/packages/example/src/HtmlInCanvas/blur-slide-doc.tsx
new file mode 100644
index 0000000000..c764bc3c7d
--- /dev/null
+++ b/packages/example/src/HtmlInCanvas/blur-slide-doc.tsx
@@ -0,0 +1,92 @@
+import {linearTiming, TransitionSeries} from '@remotion/transitions';
+import {blurSlide} from '@remotion/transitions/blur-slide';
+import React from 'react';
+import {AbsoluteFill, Img} from 'remotion';
+
+const sceneStyle: React.CSSProperties = {
+ justifyContent: 'center',
+ alignItems: 'center',
+ fontFamily: 'sans-serif',
+ fontWeight: 900,
+ color: 'white',
+ fontSize: '40cqmin',
+};
+
+const backgroundImageStyle: React.CSSProperties = {
+ position: 'absolute',
+ inset: 0,
+ width: '100%',
+ height: '100%',
+ objectFit: 'cover',
+};
+
+const letterStyle: React.CSSProperties = {
+ position: 'relative',
+ textShadow: '0 4px 30px rgba(0, 0, 0, 0.55)',
+};
+
+const SceneA: React.FC<{readonly small: boolean}> = ({small}) => {
+ return (
+ <AbsoluteFill style={sceneStyle}>
+ <Img
+ crossOrigin="anonymous"
+ src={`https://remotion.media/transition-bg-blue${small ? '-small' : ''}.jpg`}
+ style={backgroundImageStyle}
+ alt=""
+ />
+ <div style={letterStyle}>A</div>
+ </AbsoluteFill>
+ );
+};
+
+const SceneB: React.FC<{readonly small: boolean}> = ({small}) => {
+ return (
+ <AbsoluteFill style={sceneStyle}>
+ <Img
+ crossOrigin="anonymous"
+ src={`https://remotion.media/transition-bg-pink${small ? '-small' : ''}.jpg`}
+ style={backgroundImageStyle}
+ alt=""
+ />
+ <div style={letterStyle}>B</div>
+ </AbsoluteFill>
+ );
+};
+
+export const BlurSlideTransitionDoc: React.FC = () => {
+ return (
+ <AbsoluteFill style={{containerType: 'size'}}>
+ <TransitionSeries>
+ <TransitionSeries.Sequence durationInFrames={60}>
+ <SceneA small={false} />
+ </TransitionSeries.Sequence>
+ <TransitionSeries.Transition
+ presentation={blurSlide()}
+ timing={linearTiming({durationInFrames: 30})}
+ />
+ <TransitionSeries.Sequence durationInFrames={60}>
+ <SceneB small={false} />
+ </TransitionSeries.Sequence>
+ </TransitionSeries>
+ </AbsoluteFill>
+ );
+};
+
+export const BlurSlideTransitionDocThumb: React.FC = () => {
+ return (
+ <AbsoluteFill style={{containerType: 'size'}}>
+ <TransitionSeries>
+ <TransitionSeries.Sequence durationInFrames={30}>
+ <SceneA small />
+ </TransitionSeries.Sequence>
+ <TransitionSeries.Transition
+ presentation={blurSlide()}
+ timing={linearTiming({durationInFrames: 30})}
+ />
+ <TransitionSeries.Sequence durationInFrames={60}>
+ <SceneB small />
+ </TransitionSeries.Sequence>
+ </TransitionSeries>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/example/src/HtmlInCanvas/index.tsx b/packages/example/src/HtmlInCanvas/index.tsx
index 6e1c4734a3..5d181047d1 100644
--- a/packages/example/src/HtmlInCanvas/index.tsx
+++ b/packages/example/src/HtmlInCanvas/index.tsx
@@ -1,3 +1,7 @@
+export {
+ BlurSlideTransitionDoc,
+ BlurSlideTransitionDocThumb,
+} from './blur-slide-doc';
export {
BookFlipTransitionDoc,
BookFlipTransitionDocThumb,
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index c8b86fc5f2..e425445f25 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -68,6 +68,8 @@ import {
HourLongTimelineTestbed,
} from './HourLongTimelineTestbed';
import {
+ BlurSlideTransitionDoc,
+ BlurSlideTransitionDocThumb,
BookFlipTransitionDoc,
BookFlipTransitionDocThumb,
CrossZoomTransitionDoc,
@@ -1465,6 +1467,22 @@ export const Index: React.FC = () => {
width={540}
durationInFrames={60}
/>
+ <Composition
+ id="blur-slide-transition-doc"
+ component={BlurSlideTransitionDoc}
+ fps={30}
+ height={1080}
+ width={1920}
+ durationInFrames={90}
+ />
+ <Composition
+ id="blur-slide-transition-doc-thumb"
+ component={BlurSlideTransitionDocThumb}
+ fps={30}
+ height={280}
+ width={540}
+ durationInFrames={60}
+ />
<Composition
id="html-in-canvas-complex-text"
component={HtmlInCanvasComplexText}
diff --git a/packages/transitions/blur-slide.js b/packages/transitions/blur-slide.js
new file mode 100644
index 0000000000..fb419c4603
--- /dev/null
+++ b/packages/transitions/blur-slide.js
@@ -0,0 +1,2 @@
+// For backwards compatibility when you use `esm-wallaby`
+module.exports = require('./dist/presentations/blur-slide.js');
diff --git a/packages/transitions/bundle.ts b/packages/transitions/bundle.ts
index 20eaa170c6..077b1249bb 100644
--- a/packages/transitions/bundle.ts
+++ b/packages/transitions/bundle.ts
@@ -25,6 +25,7 @@ const presentations = [
'cross-zoom',
'swap',
'push-cut',
+ 'blur-slide',
];
const output = await build({
diff --git a/packages/transitions/package.json b/packages/transitions/package.json
index 8f9d779744..c430d2970b 100644
--- a/packages/transitions/package.json
+++ b/packages/transitions/package.json
@@ -169,6 +169,12 @@
"import": "./dist/esm/push-cut.mjs",
"require": "./dist/presentations/push-cut.js"
},
+ "./blur-slide": {
+ "types": "./dist/presentations/blur-slide.d.ts",
+ "module": "./dist/esm/blur-slide.mjs",
+ "import": "./dist/esm/blur-slide.mjs",
+ "require": "./dist/presentations/blur-slide.js"
+ },
"./package.json": "./package.json"
},
"typesVersions": {
@@ -229,6 +235,9 @@
],
"push-cut": [
"dist/presentations/push-cut.d.ts"
+ ],
+ "blur-slide": [
+ "dist/presentations/blur-slide.d.ts"
]
}
},
diff --git a/packages/transitions/src/index.ts b/packages/transitions/src/index.ts
index 0accdc70c4..e184101ca3 100644
--- a/packages/transitions/src/index.ts
+++ b/packages/transitions/src/index.ts
@@ -19,6 +19,11 @@ export type {
HtmlInCanvasShaderDraw,
HtmlInCanvasShaderDrawParams,
} from './html-in-canvas-presentation.js';
+export {blurSlide} from './presentations/blur-slide.js';
+export type {
+ BlurSlideDirection,
+ BlurSlideProps,
+} from './presentations/blur-slide.js';
export {crossZoom} from './presentations/cross-zoom.js';
export type {CrossZoomProps} from './presentations/cross-zoom.js';
export {dreamyZoom} from './presentations/dreamy-zoom.js';
diff --git a/packages/transitions/src/presentations/blur-slide.tsx b/packages/transitions/src/presentations/blur-slide.tsx
new file mode 100644
index 0000000000..1bf3fc203b
--- /dev/null
+++ b/packages/transitions/src/presentations/blur-slide.tsx
@@ -0,0 +1,387 @@
+import type {EffectsProp} from 'remotion';
+import type {HtmlInCanvasShader} from '../html-in-canvas-presentation';
+import {makeHtmlInCanvasPresentation} from '../html-in-canvas-presentation';
+import type {TransitionPresentation} from '../types';
+import type {SlideDirection} from './slide';
+import {uploadElementImage} from './upload-element-image';
+
+export type BlurSlideDirection = SlideDirection;
+
+export type BlurSlideProps = {
+ direction?: BlurSlideDirection;
+ blur?: number;
+};
+
+const DEFAULT_DIRECTION: BlurSlideDirection = 'from-left';
+const DEFAULT_BLUR = 0.5;
+
+const VALID_DIRECTIONS: BlurSlideDirection[] = [
+ 'from-left',
+ 'from-right',
+ 'from-top',
+ 'from-bottom',
+];
+
+const VERTEX_SHADER = `#version 300 es
+in vec2 a_pos;
+out vec2 v_uv;
+void main() {
+ v_uv = vec2(a_pos.x * 0.5 + 0.5, 0.5 - a_pos.y * 0.5);
+ gl_Position = vec4(a_pos, 0.0, 1.0);
+}`;
+
+// Pass 1: slide both scenes along u_direction, wrapping around the edges
+// (REPEAT), crossfade them around the midpoint and apply a box blur along
+// the direction of travel.
+const SLIDE_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+
+uniform sampler2D u_prev;
+uniform sampler2D u_next;
+uniform float u_progress;
+uniform vec2 u_direction;
+uniform float u_blur_length;
+
+in vec2 v_uv;
+out vec4 outColor;
+
+const int SAMPLES = 32;
+
+void main() {
+ // Both scenes travel together; the exiting scene wraps around the edges
+ // while the entering scene takes over through a crossfade in the middle.
+ vec2 slidUv = v_uv - u_direction * u_progress;
+ float mixFactor = smoothstep(0.3, 0.7, u_progress);
+
+ vec4 color = vec4(0.0);
+ for (int i = 0; i < SAMPLES; i++) {
+ float t = (float(i) / float(SAMPLES - 1) - 0.5) * u_blur_length;
+ vec2 uv = slidUv + u_direction * t;
+ color += mix(texture(u_prev, uv), texture(u_next, uv), mixFactor);
+ }
+
+ outColor = color / float(SAMPLES);
+}`;
+
+// Pass 2: blur the intermediate result along the same direction once more.
+// Two box blurs combine into a triangle kernel, which hides the banding a
+// single wide box blur would produce.
+const BLUR_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+
+uniform sampler2D u_source;
+uniform vec2 u_direction;
+uniform float u_blur_length;
+
+in vec2 v_uv;
+out vec4 outColor;
+
+const int SAMPLES = 32;
+
+void main() {
+ vec4 color = vec4(0.0);
+ for (int i = 0; i < SAMPLES; i++) {
+ float t = (float(i) / float(SAMPLES - 1) - 0.5) * u_blur_length;
+ vec2 uv = v_uv + u_direction * t;
+ // The framebuffer texture is stored bottom-up, so flip Y when sampling it.
+ color += texture(u_source, vec2(uv.x, 1.0 - uv.y));
+ }
+
+ outColor = color / float(SAMPLES);
+}`;
+
+const compileShader = (
+ gl: WebGL2RenderingContext,
+ source: string,
+ type: number,
+): WebGLShader => {
+ const shader = gl.createShader(type);
+ if (!shader) {
+ throw new Error('Failed to create shader');
+ }
+
+ gl.shaderSource(shader, source);
+ gl.compileShader(shader);
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+ const log = gl.getShaderInfoLog(shader);
+ gl.deleteShader(shader);
+ throw new Error(`Failed to compile shader: ${log}`);
+ }
+
+ return shader;
+};
+
+const createProgram = (
+ gl: WebGL2RenderingContext,
+ fragmentShader: string,
+): WebGLProgram => {
+ const program = gl.createProgram();
+ if (!program) {
+ throw new Error('Failed to create WebGL program');
+ }
+
+ const vs = compileShader(gl, VERTEX_SHADER, gl.VERTEX_SHADER);
+ const fs = compileShader(gl, fragmentShader, gl.FRAGMENT_SHADER);
+ gl.attachShader(program, vs);
+ gl.attachShader(program, fs);
+ gl.linkProgram(program);
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
+ const log = gl.getProgramInfoLog(program);
+ gl.deleteProgram(program);
+ throw new Error(`Failed to link program: ${log}`);
+ }
+
+ return program;
+};
+
+const createTexture = (gl: WebGL2RenderingContext): WebGLTexture => {
+ const tex = gl.createTexture();
+ if (!tex) {
+ throw new Error('Failed to create texture');
+ }
+
+ gl.bindTexture(gl.TEXTURE_2D, tex);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ 1,
+ 1,
+ 0,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ new Uint8Array([0, 0, 0, 0]),
+ );
+ return tex;
+};
+
+const getDirectionVector = (
+ direction: BlurSlideDirection,
+): [number, number] => {
+ // v_uv has its origin in the top-left corner, so +y points down.
+ switch (direction) {
+ case 'from-left':
+ return [1, 0];
+ case 'from-right':
+ return [-1, 0];
+ case 'from-top':
+ return [0, 1];
+ case 'from-bottom':
+ return [0, -1];
+ default:
+ throw new Error(`Invalid direction: ${direction}`);
+ }
+};
+
+const validateProps = (props: BlurSlideProps) => {
+ const direction = props.direction ?? DEFAULT_DIRECTION;
+ const blur = props.blur ?? DEFAULT_BLUR;
+
+ if (!VALID_DIRECTIONS.includes(direction)) {
+ throw new TypeError(
+ `direction passed to blurSlide() must be one of ${VALID_DIRECTIONS.map((d) => `"${d}"`).join(', ')}, received ${JSON.stringify(direction)}`,
+ );
+ }
+
+ if (typeof blur !== 'number' || !Number.isFinite(blur)) {
+ throw new TypeError(
+ `blur passed to blurSlide() must be a finite number, received ${blur}`,
+ );
+ }
+
+ if (blur < 0) {
+ throw new TypeError(
+ `blur passed to blurSlide() must be greater than or equal to 0, received ${blur}`,
+ );
+ }
+};
+
+export const blurSlideShader = (
+ canvas: OffscreenCanvas,
+): ReturnType<HtmlInCanvasShader<BlurSlideProps>> => {
+ const gl = canvas.getContext('webgl2', {premultipliedAlpha: true});
+ if (!gl) {
+ throw new Error('Failed to create WebGL2 context');
+ }
+
+ const slideProgram = createProgram(gl, SLIDE_FRAGMENT_SHADER);
+ const blurProgram = createProgram(gl, BLUR_FRAGMENT_SHADER);
+ const prevTex = createTexture(gl);
+ const nextTex = createTexture(gl);
+ const intermediateTex = createTexture(gl);
+
+ const framebuffer = gl.createFramebuffer();
+ if (!framebuffer) {
+ throw new Error('Failed to create framebuffer');
+ }
+
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
+ gl.framebufferTexture2D(
+ gl.FRAMEBUFFER,
+ gl.COLOR_ATTACHMENT0,
+ gl.TEXTURE_2D,
+ intermediateTex,
+ 0,
+ );
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+
+ let intermediateWidth = 1;
+ let intermediateHeight = 1;
+
+ const vao = gl.createVertexArray();
+ gl.bindVertexArray(vao);
+ const buffer = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+ gl.bufferData(
+ gl.ARRAY_BUFFER,
+ new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),
+ gl.STATIC_DRAW,
+ );
+ // Both programs share the same vertex shader, so the attribute location matches.
+ const aPos = gl.getAttribLocation(slideProgram, 'a_pos');
+ gl.enableVertexAttribArray(aPos);
+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
+
+ const uPrev = gl.getUniformLocation(slideProgram, 'u_prev');
+ const uNext = gl.getUniformLocation(slideProgram, 'u_next');
+ const uProgress = gl.getUniformLocation(slideProgram, 'u_progress');
+ const uSlideDirection = gl.getUniformLocation(slideProgram, 'u_direction');
+ const uSlideBlurLength = gl.getUniformLocation(slideProgram, 'u_blur_length');
+
+ const uSource = gl.getUniformLocation(blurProgram, 'u_source');
+ const uBlurDirection = gl.getUniformLocation(blurProgram, 'u_direction');
+ const uBlurBlurLength = gl.getUniformLocation(blurProgram, 'u_blur_length');
+
+ const cleanup: ReturnType<
+ HtmlInCanvasShader<BlurSlideProps>
+ >['cleanup'] = () => {
+ gl.deleteProgram(slideProgram);
+ gl.deleteProgram(blurProgram);
+ gl.deleteTexture(prevTex);
+ gl.deleteTexture(nextTex);
+ gl.deleteTexture(intermediateTex);
+ gl.deleteFramebuffer(framebuffer);
+ gl.deleteBuffer(buffer);
+ gl.deleteVertexArray(vao);
+ };
+
+ const clear: ReturnType<HtmlInCanvasShader<BlurSlideProps>>['clear'] = () => {
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ };
+
+ const draw: ReturnType<HtmlInCanvasShader<BlurSlideProps>>['draw'] = ({
+ prevImage,
+ nextImage,
+ width,
+ height,
+ time,
+ passedProps,
+ }) => {
+ const {direction = DEFAULT_DIRECTION, blur = DEFAULT_BLUR} = passedProps;
+
+ if (!prevImage && !nextImage) {
+ return;
+ }
+
+ if (prevImage && (prevImage.width === 0 || prevImage.height === 0)) {
+ return;
+ }
+
+ if (nextImage && (nextImage.width === 0 || nextImage.height === 0)) {
+ return;
+ }
+
+ // At time=0 the shader outputs nextImage. At time=1 the shader outputs prevImage.
+ const effectiveTime = !prevImage ? 0 : !nextImage ? 1 : time;
+ const linearProgress = 1 - effectiveTime;
+ // Ease the slide so that it starts and ends at rest. The blur is
+ // proportional to the speed of the slide, which peaks halfway through.
+ const progress = linearProgress * linearProgress * (3 - 2 * linearProgress);
+ const velocity = 4 * linearProgress * (1 - linearProgress);
+ // Each pass covers half of the kernel; together they form a triangle
+ // kernel spanning `blur * velocity` of the frame.
+ const passBlurLength = (blur * velocity) / 2;
+ const [dirX, dirY] = getDirectionVector(direction);
+
+ gl.bindVertexArray(vao);
+
+ if (intermediateWidth !== width || intermediateHeight !== height) {
+ gl.bindTexture(gl.TEXTURE_2D, intermediateTex);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ width,
+ height,
+ 0,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ null,
+ );
+ intermediateWidth = width;
+ intermediateHeight = height;
+ }
+
+ // Pass 1: slide + crossfade + first blur into the intermediate texture.
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
+ gl.viewport(0, 0, width, height);
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.useProgram(slideProgram);
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, prevTex);
+ if (prevImage) {
+ uploadElementImage(gl, prevImage);
+ }
+
+ gl.uniform1i(uPrev, 0);
+
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, nextTex);
+ if (nextImage) {
+ uploadElementImage(gl, nextImage);
+ }
+
+ gl.uniform1i(uNext, 1);
+ gl.uniform1f(uProgress, progress);
+ gl.uniform2f(uSlideDirection, dirX, dirY);
+ gl.uniform1f(uSlideBlurLength, passBlurLength);
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+
+ // Pass 2: second blur into the output canvas.
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.viewport(0, 0, width, height);
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.useProgram(blurProgram);
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, intermediateTex);
+ gl.uniform1i(uSource, 0);
+ gl.uniform2f(uBlurDirection, dirX, dirY);
+ gl.uniform1f(uBlurBlurLength, passBlurLength);
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+ };
+
+ return {
+ clear,
+ cleanup,
+ draw,
+ };
+};
+
+const makeBlurSlide = makeHtmlInCanvasPresentation(blurSlideShader);
+
+export const blurSlide = (
+ props: BlurSlideProps & {effects?: EffectsProp} = {},
+): TransitionPresentation<BlurSlideProps & {effects?: EffectsProp}> => {
+ validateProps(props);
+ return makeBlurSlide(props);
+};
diff --git a/packages/transitions/src/test/blur-slide.test.tsx b/packages/transitions/src/test/blur-slide.test.tsx
new file mode 100644
index 0000000000..ebc88f75a8
--- /dev/null
+++ b/packages/transitions/src/test/blur-slide.test.tsx
@@ -0,0 +1,26 @@
+import {expect, test} from 'bun:test';
+import {blurSlide} from '../presentations/blur-slide';
+
+test('blurSlide() should return a presentation', () => {
+ const presentation = blurSlide({direction: 'from-top', blur: 0.3});
+
+ expect(presentation.props).toEqual({direction: 'from-top', blur: 0.3});
+ expect(typeof presentation.component).toBe('function');
+});
+
+test('blurSlide() should accept being called without arguments', () => {
+ const presentation = blurSlide();
+
+ expect(presentation.props).toEqual({});
+ expect(typeof presentation.component).toBe('function');
+});
+
+test('blurSlide() should reject invalid props', () => {
+ expect(() =>
+ // @ts-expect-error invalid direction
+ blurSlide({direction: 'from-center'}),
+ ).toThrow('direction');
+ expect(() => blurSlide({blur: -0.1})).toThrow('blur');
+ expect(() => blurSlide({blur: Number.NaN})).toThrow('finite');
+ expect(() => blurSlide({blur: Number.POSITIVE_INFINITY})).toThrow('finite');
+});