🎥 Make videos programmatically with React
`@remotion/web-renderer`: Ignore transforms on inline elements (#8872)
Jonny Burger7f66452bdc6b
diff --git a/packages/web-renderer/src/drawing/calculate-transforms.ts b/packages/web-renderer/src/drawing/calculate-transforms.tsindex a81237c547..a37ce5e9e7 100644--- a/packages/web-renderer/src/drawing/calculate-transforms.ts+++ b/packages/web-renderer/src/drawing/calculate-transforms.ts@@ -29,6 +29,58 @@ type Transform = {boundingClientRect: DOMRect | null;};+const isReplacedElement = (element: Element) => {+ return (+ element instanceof HTMLImageElement ||+ element instanceof HTMLVideoElement ||+ element instanceof HTMLCanvasElement ||+ element instanceof HTMLIFrameElement ||+ element instanceof HTMLInputElement ||+ element instanceof HTMLTextAreaElement ||+ element instanceof HTMLSelectElement ||+ element instanceof HTMLObjectElement ||+ element instanceof HTMLEmbedElement+ );+};++const canApplyCssTransforms = ({+ element,+ computedStyle,+}: {+ element: HTMLElement | SVGElement;+ computedStyle: CSSStyleDeclaration;+}) => {+ if (element instanceof SVGElement) {+ return true;+ }++ if (computedStyle.display !== 'inline') {+ return true;+ }++ return isReplacedElement(element);+};++const makeTransformResetter = (element: HTMLElement | SVGElement) => {+ const {transform, scale, rotate} = element.style;++ return (hasApplicableTransformCssValue: boolean) => {+ if (hasApplicableTransformCssValue) {+ element.style.transform = 'none';+ element.style.scale = 'none';+ element.style.rotate = 'none';+ }++ return () => {+ if (hasApplicableTransformCssValue) {+ element.style.transform = transform;+ element.style.scale = scale;+ element.style.rotate = rotate;+ }+ };+ };+};+const getInternalTransformOrigin = (transform: Transform) => {const centerX = transform.boundingClientRect!.width / 2;const centerY = transform.boundingClientRect!.height / 2;@@ -106,13 +158,19 @@ export const calculateTransforms = ({});}- if (hasAnyTransformCssValue(computedStyle) || parent === element) {- const toParse = hasTransformCssValue(computedStyle)- ? computedStyle.transform- : undefined;+ const hasApplicableTransformCssValue =+ canApplyCssTransforms({computedStyle, element: parent}) &&+ hasAnyTransformCssValue(computedStyle);++ if (hasApplicableTransformCssValue || parent === element) {+ const toParse =+ hasApplicableTransformCssValue && hasTransformCssValue(computedStyle)+ ? computedStyle.transform+ : undefined;const matrix = new DOMMatrix(toParse);- const {transform, scale, rotate} = parent.style;+ const resetTransforms = makeTransformResetter(parent);+ const {scale, rotate} = parent.style;const additionalMatrices: DOMMatrix[] = [];// The order of transformations is:@@ -120,19 +178,21 @@ export const calculateTransforms = ({// 2. Rotate// 3. Scale// 4. CSS "transform"- if (rotate !== '' && rotate !== 'none') {+ if (+ hasApplicableTransformCssValue &&+ rotate !== '' &&+ rotate !== 'none'+ ) {additionalMatrices.push(new DOMMatrix(`rotate(${rotate})`));}- if (scale !== '' && scale !== 'none') {+ if (hasApplicableTransformCssValue && scale !== '' && scale !== 'none') {additionalMatrices.push(new DOMMatrix(`scale(${scale})`));}additionalMatrices.push(matrix);- parent.style.transform = 'none';- parent.style.scale = 'none';- parent.style.rotate = 'none';+ const cleanup = resetTransforms(hasApplicableTransformCssValue);transforms.push({element: parent,@@ -142,9 +202,7 @@ export const calculateTransforms = ({});const parentRef = parent;toReset.push(() => {- parentRef!.style.transform = transform;- parentRef!.style.scale = scale;- parentRef!.style.rotate = rotate;+ cleanup();parentRef!.style.transition = originalTransition;});} else {diff --git a/packages/web-renderer/src/test/Root.tsx b/packages/web-renderer/src/test/Root.tsxindex fa4a175f30..6c7a758f8a 100644--- a/packages/web-renderer/src/test/Root.tsx+++ b/packages/web-renderer/src/test/Root.tsx@@ -31,6 +31,7 @@ import {flexContainer} from './fixtures/flex-container';import {flexPositionedScaled} from './fixtures/flex-positioned-scaled';import {gradientTransparentKeyword} from './fixtures/gradient-transparent-keyword';import {hugeImageTransform} from './fixtures/huge-image-transform';+import {inlineScaleAfterOutline} from './fixtures/inline-scale-after-outline';import {inside3dTransform} from './fixtures/inside-3d-transform';import {issue6211MaskWheel} from './fixtures/issue-6211-mask-wheel';import {issue7050Minimal} from './fixtures/issue-7050-minimal';@@ -144,6 +145,7 @@ export const Root: React.FC = () => {<Composition {...gradientTransparentKeyword} /></Folder><Composition {...outline} />+ <Composition {...inlineScaleAfterOutline} /><Composition {...boxShadow} /><Folder name="Filter"><Composition {...filter} />diff --git a/packages/web-renderer/src/test/__screenshots__/inline-scale.test.tsx/inline-scale-after-outline-chromium-darwin.png b/packages/web-renderer/src/test/__screenshots__/inline-scale.test.tsx/inline-scale-after-outline-chromium-darwin.pngnew file mode 100644index 0000000000..9ea6a3e3faBinary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/inline-scale.test.tsx/inline-scale-after-outline-chromium-darwin.png differdiff --git a/packages/web-renderer/src/test/__screenshots__/inline-scale.test.tsx/inline-scale-after-outline-firefox-darwin.png b/packages/web-renderer/src/test/__screenshots__/inline-scale.test.tsx/inline-scale-after-outline-firefox-darwin.pngnew file mode 100644index 0000000000..5d67f5f581Binary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/inline-scale.test.tsx/inline-scale-after-outline-firefox-darwin.png differdiff --git a/packages/web-renderer/src/test/__screenshots__/inline-scale.test.tsx/inline-scale-after-outline-webkit-darwin.png b/packages/web-renderer/src/test/__screenshots__/inline-scale.test.tsx/inline-scale-after-outline-webkit-darwin.pngnew file mode 100644index 0000000000..7e64d77a9aBinary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/inline-scale.test.tsx/inline-scale-after-outline-webkit-darwin.png differdiff --git a/packages/web-renderer/src/test/fixtures/inline-scale-after-outline.tsx b/packages/web-renderer/src/test/fixtures/inline-scale-after-outline.tsxnew file mode 100644index 0000000000..1acb9015a8--- /dev/null+++ b/packages/web-renderer/src/test/fixtures/inline-scale-after-outline.tsx@@ -0,0 +1,100 @@+import type {CSSProperties} from 'react';+import {useCurrentFrame} from 'remotion';++const activeBlue = 'rgb(59, 130, 235)';++const baseStyle: CSSProperties = {+ display: 'inline',+ fontFamily: 'Arial, Helvetica, sans-serif',+ fontSize: 56,+ fontWeight: 600,+ lineHeight: 1.2,+};++const monoStyle: CSSProperties = {+ fontFamily: '"Roboto Mono", monospace',+ fontWeight: 500,+ fontFeatureSettings: '"ss03"',+ whiteSpace: 'nowrap',+ borderRadius: 10,+};++const CaptionLine: React.FC<{+ top: number;+ withScale: boolean;+}> = ({top, withScale}) => {+ const frame = useCurrentFrame();+ const active = frame === 1;++ return (+ <div+ style={{+ position: 'absolute',+ left: 30,+ top,+ width: 1020,+ height: 160,+ backgroundColor: '#eef2f7',+ border: '3px solid #ebebeb',+ borderRadius: 20,+ display: 'flex',+ alignItems: 'center',+ }}+ >+ <span+ style={{+ display: 'inline-block',+ paddingLeft: 30,+ paddingRight: 30,+ width: '100%',+ wordBreak: 'break-word',+ }}+ >+ <span style={{...baseStyle, color: 'black'}}>+ In the left sidebar, Just{' '}+ </span>+ <span+ style={{+ ...baseStyle,+ ...monoStyle,+ color: active ? 'white' : activeBlue,+ backgroundColor: active ? activeBlue : 'transparent',+ outline: active ? `5px solid ${activeBlue}` : 'none',+ boxShadow: active ? `0 0 0 1px ${activeBlue}` : 'none',+ scale: withScale ? (frame === 0 ? '1' : '0.95') : '1',+ }}+ >+ click+ </span>+ <span style={{...baseStyle, color: 'rgba(0, 0, 0, 0.3)'}}>+ {' '}+ on one to start+ </span>+ </span>+ </div>+ );+};++const Component: React.FC = () => {+ return (+ <div+ style={{+ width: 1080,+ height: 400,+ backgroundColor: '#dce3ec',+ }}+ >+ <CaptionLine top={30} withScale={false} />+ <CaptionLine top={210} withScale />+ </div>+ );+};++export const inlineScaleAfterOutline = {+ component: Component,+ id: 'inline-scale-after-outline',+ width: 1080,+ height: 400,+ fps: 30,+ durationInFrames: 3,+} as const;diff --git a/packages/web-renderer/src/test/inline-scale.test.tsx b/packages/web-renderer/src/test/inline-scale.test.tsxnew file mode 100644index 0000000000..ac11e2f929--- /dev/null+++ b/packages/web-renderer/src/test/inline-scale.test.tsx@@ -0,0 +1,101 @@+import {expect, test} from 'vitest';+import {renderStillOnWeb} from '../render-still-on-web';+import '../symbol-dispose';+import {inlineScaleAfterOutline} from './fixtures/inline-scale-after-outline';+import {testImage} from './utils';++const getImageData = async (blob: Blob) => {+ const image = document.createElement('img');+ const objectUrl = URL.createObjectURL(blob);+ image.src = objectUrl;++ await new Promise<void>((resolve, reject) => {+ image.onload = () => resolve();+ image.onerror = () => reject(new Error('Image failed to load'));+ });++ const canvas = document.createElement('canvas');+ canvas.width = image.naturalWidth;+ canvas.height = image.naturalHeight;++ const context = canvas.getContext('2d');+ URL.revokeObjectURL(objectUrl);++ if (!context) {+ throw new Error('Could not get canvas context');+ }++ context.drawImage(image, 0, 0);++ return context.getImageData(0, 0, image.naturalWidth, image.naturalHeight);+};++const getBlueBounds = ({+ imageData,+ yStart,+ yEnd,+}: {+ imageData: ImageData;+ yStart: number;+ yEnd: number;+}) => {+ let left = Infinity;+ let right = -Infinity;+ let top = Infinity;+ let bottom = -Infinity;++ for (let y = yStart; y < yEnd; y++) {+ for (let x = 0; x < imageData.width; x++) {+ const index = (y * imageData.width + x) * 4;+ const red = imageData.data[index];+ const green = imageData.data[index + 1];+ const blue = imageData.data[index + 2];+ const alpha = imageData.data[index + 3];++ if (+ alpha > 200 &&+ red > 30 &&+ red < 100 &&+ green > 100 &&+ green < 170 &&+ blue > 180+ ) {+ left = Math.min(left, x);+ right = Math.max(right, x);+ top = Math.min(top, y);+ bottom = Math.max(bottom, y);+ }+ }+ }++ if (!Number.isFinite(left)) {+ throw new Error('Could not find blue caption pixels');+ }++ return {bottom, left, right, top};+};++test('ignores scale on inline captions after outline and background disappear', async () => {+ const blob = await (+ await renderStillOnWeb({+ licenseKey: 'free-license',+ composition: inlineScaleAfterOutline,+ frame: 2,+ inputProps: {},+ })+ ).blob({format: 'png'});++ const imageData = await getImageData(blob);+ const unscaled = getBlueBounds({imageData, yStart: 30, yEnd: 190});+ const withScale = getBlueBounds({imageData, yStart: 210, yEnd: 370});++ expect(Math.abs(withScale.left - unscaled.left)).toBeLessThanOrEqual(1);+ expect(Math.abs(withScale.right - unscaled.right)).toBeLessThanOrEqual(1);+ expect(withScale.right - withScale.left).toBe(unscaled.right - unscaled.left);++ await testImage({+ blob,+ testId: 'inline-scale-after-outline',+ allowedMismatchedPixelRatio: 0.02,+ });+});