🎥 Make videos programmatically with React
`@remotion/studio`: Clear stale hover backgrounds (#10068)
Jonny Burgerbc37f8306ab8
diff --git a/packages/browser-studio/e2e/browser-studio.test.ts b/packages/browser-studio/e2e/browser-studio.test.tsindex c9f409d9c4..b0b74a9f14 100644--- a/packages/browser-studio/e2e/browser-studio.test.ts+++ b/packages/browser-studio/e2e/browser-studio.test.ts@@ -45,3 +45,62 @@ test('loads the Browser Studio canvas and enables Visual Mode', async ({expect(pageErrors).toEqual([]);expect(updateAvailableRequests).toEqual([]);});++test('clears hover backgrounds even if pointer leave events are lost', async ({+ page,+}) => {+ await page.goto('/');+ const studio = page.frameLocator('iframe');+ await expect(studio.getByTitle('/project').getByText('MyComp')).toBeVisible();+ await studio.locator('[data-compname="MyComp"]').click();+ await studio.locator('[data-sidebar-toggle="right"]').click();++ const addSolid = studio.getByRole('button', {name: 'Add Solid'});+ await expect(addSolid).toBeVisible();++ const getBackgroundColor = (locator: ReturnType<typeof studio.locator>) =>+ locator.evaluate(+ (element) => window.getComputedStyle(element).backgroundColor,+ );++ await addSolid.hover();+ await expect+ .poll(() => getBackgroundColor(addSolid))+ .toBe('rgba(255, 255, 255, 0.06)');++ // Browsers can fail to deliver pointer leave events when the pointer+ // exits the Studio <iframe>. Simulate this by suppressing them before+ // they reach the app: https://github.com/remotion-dev/remotion/issues/9886+ await studio.locator('body').evaluate((body) => {+ const win = body.ownerDocument.defaultView as Window;+ for (const type of [+ 'pointerout',+ 'pointerleave',+ 'mouseout',+ 'mouseleave',+ ]) {+ win.addEventListener(type, (e) => e.stopImmediatePropagation(), {+ capture: true,+ });+ }+ });++ const neutralArea = studio.locator('.remotion-studio-composition-container');++ await neutralArea.hover();+ await expect+ .poll(() => getBackgroundColor(addSolid))+ .toBe('rgba(0, 0, 0, 0)');++ // Menubar items must reset as well+ const fileMenu = studio.getByRole('button', {name: 'File', exact: true});+ await fileMenu.hover();+ await expect+ .poll(() => getBackgroundColor(fileMenu))+ .toBe('rgba(255, 255, 255, 0.06)');++ await neutralArea.hover();+ await expect+ .poll(() => getBackgroundColor(fileMenu))+ .toBe('rgba(0, 0, 0, 0)');+});diff --git a/packages/studio/src/components/InlineAction.tsx b/packages/studio/src/components/InlineAction.tsxindex e588d28322..44da193366 100644--- a/packages/studio/src/components/InlineAction.tsx+++ b/packages/studio/src/components/InlineAction.tsx@@ -1,10 +1,12 @@-import React, {useCallback, useMemo, useState} from 'react';+import React, {useMemo} from 'react';import {+ CURRENT_COLOR,LIGHT_TEXT,TRANSPARENT,WHITE,getBackgroundFromHoverState,} from '../helpers/colors';+import {HOVERABLE_CLASS_NAME, hoverableStyle} from '../helpers/hoverable';import {useZIndex} from '../state/z-index';export type RenderInlineAction = (color: string) => React.ReactNode;@@ -28,26 +30,14 @@ export const InlineAction = ({unhoveredColor = LIGHT_TEXT,variant,style: customStyle,+ className,...buttonProps}: InlineActionProps) => {const {tabIndex} = useZIndex();- const [hovered, setHovered] = useState(false);-- const onPointerEnter = useCallback(() => {- setHovered(true);- }, []);-- const onPointerLeave = useCallback(() => {- setHovered(false);- }, []);-const style: React.CSSProperties = useMemo(() => {return {border: 'none',- background: disabled- ? TRANSPARENT- : getBackgroundFromHoverState({hovered, selected: false}),height: 24,width: variant === 'compact' ? 14 : 24,padding: 0,@@ -57,24 +47,35 @@ export const InlineAction = ({borderRadius: 3,opacity: disabled ? 0.5 : 1,pointerEvents: disabled ? 'none' : 'auto',+ ...hoverableStyle({+ idleBackground: TRANSPARENT,+ hoverBackground: disabled+ ? TRANSPARENT+ : getBackgroundFromHoverState({hovered: true, selected: false}),+ idleColor: unhoveredColor,+ hoverColor: disabled ? unhoveredColor : WHITE,+ }),...customStyle,};- }, [customStyle, disabled, hovered, variant]);+ }, [customStyle, disabled, unhoveredColor, variant]);return (<button{...buttonProps}type="button"+ className={+ className+ ? `${HOVERABLE_CLASS_NAME} ${className}`+ : HOVERABLE_CLASS_NAME+ }disabled={disabled}- onPointerEnter={onPointerEnter}- onPointerLeave={onPointerLeave}onClick={onClick}style={style}tabIndex={tabIndex}title={title}aria-label={buttonProps['aria-label'] ?? title}>- {renderAction(hovered ? WHITE : unhoveredColor)}+ {renderAction(CURRENT_COLOR)}</button>);};diff --git a/packages/studio/src/components/InspectorPanel/common.tsx b/packages/studio/src/components/InspectorPanel/common.tsxindex bc23edf438..d9acebcf93 100644--- a/packages/studio/src/components/InspectorPanel/common.tsx+++ b/packages/studio/src/components/InspectorPanel/common.tsx@@ -1,10 +1,17 @@import React from 'react';import {+ CURRENT_COLOR,LIGHT_TEXT,TRANSPARENT,WHITE,getBackgroundFromHoverState,} from '../../helpers/colors';+import {+ HOVERABLE_CLASS_NAME,+ HOVER_GROUP_CLASS_NAME,+ HOVER_GROUP_REVEAL_CLASS_NAME,+ hoverableStyle,+} from '../../helpers/hoverable';import {INSPECTOR_PANEL_HORIZONTAL_PADDING} from '../InspectorPanelLayout';import {COMPACT_CONTROL_ROW_HEIGHT, COMPACT_INLINE_ROW_HEIGHT} from '../layout';import {ValidationMessage} from '../NewComposition/ValidationMessage';@@ -122,11 +129,9 @@ const INLINE_LABEL_BUTTON_MARGIN = 4;const inlineLabelButton: React.CSSProperties = {alignItems: 'center',appearance: 'none',- backgroundColor: TRANSPARENT,border: 'none',borderRadius: 4,boxSizing: 'border-box',- color: LIGHT_TEXT,cursor: 'default',display: 'flex',fontFamily: 'sans-serif',@@ -150,7 +155,6 @@ const compactInlineLabelButton: React.CSSProperties = {};const inlineLabelText: React.CSSProperties = {- color: LIGHT_TEXT,flex: 1,fontFamily: 'sans-serif',fontSize: 13,@@ -198,11 +202,6 @@ const segmentedTrailingAction: React.CSSProperties = {width: 28,};-const hiddenSegmentedTrailingIcon: React.CSSProperties = {- ...inlineLabelIcon,- opacity: 0,-};-export type InspectorInlineActionSegment = {readonly disabled: boolean;readonly onClick: React.MouseEventHandler<HTMLButtonElement>;@@ -236,76 +235,65 @@ export const InspectorInlineAction: React.FC<InspectorInlineActionProps> = ({title,variant = {type: 'single'},}) => {- const [hovered, setHovered] = React.useState(false);- const color = hovered && !disabled ? WHITE : LIGHT_TEXT;const isSegmented = variant.type === 'segmented';+ // A non-clickable single action (onClick === null) never shows a hover+ // effect. In the segmented variant, the main segment highlights whenever+ // the group is hovered, even if it is not clickable itself.+ const showsHover = !disabled && (onClick !== null || isSegmented);const buttonStyle = React.useMemo((): React.CSSProperties => ({...(disabled ? inlineLabelButtonDisabled : inlineLabelButton),- backgroundColor: getBackgroundFromHoverState({- hovered: hovered && !disabled,- selected: false,+ ...hoverableStyle({+ idleBackground: TRANSPARENT,+ hoverBackground: showsHover+ ? getBackgroundFromHoverState({hovered: true, selected: false})+ : TRANSPARENT,+ idleColor: LIGHT_TEXT,+ hoverColor: showsHover ? WHITE : LIGHT_TEXT,}),- color,...(size === 'compact' ? compactInlineLabelButton : null),...(isSegmented ? segmentedMainAction : null),...style,}),- [color, disabled, hovered, isSegmented, size, style],- );- const textStyle = React.useMemo(- (): React.CSSProperties => ({- ...inlineLabelText,- color,- }),- [color],+ [disabled, showsHover, isSegmented, size, style],);- const onPointerEnter = React.useCallback(() => {- setHovered(true);- }, []);- const onPointerLeave = React.useCallback(() => {- setHovered(false);- }, []);-const mainContent = (<>{renderIcon ? (- <span style={inlineLabelIcon}>{renderIcon(color)}</span>+ <span style={inlineLabelIcon}>{renderIcon(CURRENT_COLOR)}</span>) : null}- <span style={textStyle}>{children}</span>+ <span style={inlineLabelText}>{children}</span></>);const mainAction = onClick ? (<button- className="__remotion-inspector-inline-action"+ className={`__remotion-inspector-inline-action ${HOVERABLE_CLASS_NAME}`}type="button"disabled={disabled}style={buttonStyle}title={title}onClick={onClick}- onPointerEnter={disabled || isSegmented ? undefined : onPointerEnter}- onPointerLeave={isSegmented ? undefined : onPointerLeave}>{mainContent}</button>) : (- <div style={buttonStyle} title={title}>+ <div className={HOVERABLE_CLASS_NAME} style={buttonStyle} title={title}>{mainContent}</div>);if (variant.type === 'segmented') {- const trailingColor =- hovered && !variant.trailing.disabled ? WHITE : LIGHT_TEXT;const trailingStyle: React.CSSProperties = {...segmentedTrailingAction,- backgroundColor: variant.trailing.disabled- ? TRANSPARENT- : getBackgroundFromHoverState({- hovered,- selected: false,- }),+ ...hoverableStyle({+ idleBackground: TRANSPARENT,+ hoverBackground: variant.trailing.disabled+ ? TRANSPARENT+ : getBackgroundFromHoverState({hovered: true, selected: false}),+ idleColor: LIGHT_TEXT,+ hoverColor: variant.trailing.disabled ? LIGHT_TEXT : WHITE,+ }),height:size === 'compact'? COMPACT_INLINE_ROW_HEIGHT@@ -314,21 +302,21 @@ export const InspectorInlineAction: React.FC<InspectorInlineActionProps> = ({};return (- <div- style={segmentedInlineAction}- onPointerEnter={onPointerEnter}- onPointerLeave={onPointerLeave}- >+ <div className={HOVER_GROUP_CLASS_NAME} style={segmentedInlineAction}>{mainAction}<buttontype="button"+ className={HOVERABLE_CLASS_NAME}disabled={variant.trailing.disabled}style={trailingStyle}title={variant.trailing.title}onClick={variant.trailing.onClick}>- <span style={hovered ? inlineLabelIcon : hiddenSegmentedTrailingIcon}>- {variant.trailing.renderIcon(trailingColor)}+ <span+ className={HOVER_GROUP_REVEAL_CLASS_NAME}+ style={inlineLabelIcon}+ >+ {variant.trailing.renderIcon(CURRENT_COLOR)}</span></button></div>diff --git a/packages/studio/src/components/Menu/MenuItem.tsx b/packages/studio/src/components/Menu/MenuItem.tsxindex 38fc1b69b7..424159f8b4 100644--- a/packages/studio/src/components/Menu/MenuItem.tsx+++ b/packages/studio/src/components/Menu/MenuItem.tsx@@ -1,12 +1,13 @@import {PlayerInternals} from '@remotion/player';import type {SetStateAction} from 'react';-import React, {useCallback, useMemo, useRef, useState} from 'react';+import React, {useCallback, useMemo, useRef} from 'react';import ReactDOM from 'react-dom';import {WHITE,WHITE_ALPHA_80,getBackgroundFromHoverState,} from '../../helpers/colors';+import {HOVERABLE_CLASS_NAME, hoverableStyle} from '../../helpers/hoverable';import {startPointerSession} from '../../helpers/pointer-session';import {HigherZIndex, useZIndex} from '../../state/z-index';import type {ComboboxValue} from '../NewComposition/ComboBox';@@ -17,7 +18,6 @@ import {menuContainerTowardsBottom, outerPortal} from './styles';const container: React.CSSProperties = {fontSize: 13,- color: WHITE_ALPHA_80,paddingLeft: 10,paddingRight: 10,cursor: 'default',@@ -65,7 +65,6 @@ export const MenuItem: React.FC<{onNextMenu,menu,}) => {- const [hovered, setHovered] = useState(false);const ref = useRef<HTMLButtonElement>(null);const size = PlayerInternals.useElementSize(ref, {triggerOnWindowResize: true,@@ -76,13 +75,20 @@ export const MenuItem: React.FC<{const containerStyle = useMemo((): React.CSSProperties => {return {...container,- color: hovered || selected ? WHITE : WHITE_ALPHA_80,- backgroundColor: getBackgroundFromHoverState({- hovered,- selected,+ ...hoverableStyle({+ idleBackground: getBackgroundFromHoverState({+ hovered: false,+ selected,+ }),+ hoverBackground: getBackgroundFromHoverState({+ hovered: true,+ selected,+ }),+ idleColor: selected ? WHITE : WHITE_ALPHA_80,+ hoverColor: WHITE,}),};- }, [hovered, selected]);+ }, [selected]);const portalStyle = useMemo((): React.CSSProperties | null => {if (!selected || !size) {@@ -96,15 +102,12 @@ export const MenuItem: React.FC<{};}, [selected, size]);+ // Not for styling (which is done via CSS :hover), but for switching+ // between menus when a menu is already open.const onPointerEnter = useCallback(() => {onItemHovered(id);- setHovered(true);}, [id, onItemHovered]);- const onPointerLeave = useCallback(() => {- setHovered(false);- }, []);-const onPointerDown: React.PointerEventHandler<HTMLButtonElement> =useCallback((e) => {@@ -176,12 +179,11 @@ export const MenuItem: React.FC<{role="button"tabIndex={tabIndex}onPointerEnter={onPointerEnter}- onPointerLeave={onPointerLeave}onPointerDown={onPointerDown}onClick={onClick}style={containerStyle}type="button"- className={MENU_INITIATOR_CLASSNAME}+ className={`${MENU_INITIATOR_CLASSNAME} ${HOVERABLE_CLASS_NAME}`}>{itemName}</button>diff --git a/packages/studio/src/helpers/hoverable.ts b/packages/studio/src/helpers/hoverable.tsnew file mode 100644index 0000000000..333389757d--- /dev/null+++ b/packages/studio/src/helpers/hoverable.ts@@ -0,0 +1,82 @@+import type React from 'react';+import {TRANSPARENT} from './colors';++// Purely visual hover styling must be driven by CSS `:hover` rather than+// React state: When the Studio runs in an <iframe> (like in Browser Studio),+// browsers can fail to deliver `pointerleave` when the pointer exits the+// frame, which would leave a state-driven hover background stuck forever.+// CSS `:hover` is maintained by the browser and self-corrects.+// https://github.com/remotion-dev/remotion/issues/9886++export const HOVERABLE_CLASS_NAME = '__remotion-hoverable';+export const HOVER_GROUP_CLASS_NAME = '__remotion-hover-group';+export const HOVER_GROUP_REVEAL_CLASS_NAME = '__remotion-hover-group-reveal';++const BG_VARIABLE = '--remotion-hoverable-bg';+const HOVER_BG_VARIABLE = '--remotion-hoverable-hover-bg';+const COLOR_VARIABLE = '--remotion-hoverable-color';+const HOVER_COLOR_VARIABLE = '--remotion-hoverable-hover-color';++// To disable the hover effect (e.g. for a disabled control), pass the idle+// values as the hover values.+export const hoverableStyle = ({+ idleBackground,+ hoverBackground,+ idleColor,+ hoverColor,+}: {+ idleBackground: string;+ hoverBackground: string;+ idleColor: string;+ hoverColor: string;+}): React.CSSProperties => {+ return {+ [BG_VARIABLE]: idleBackground,+ [HOVER_BG_VARIABLE]: hoverBackground,+ [COLOR_VARIABLE]: idleColor,+ [HOVER_COLOR_VARIABLE]: hoverColor,+ } as React.CSSProperties;+};++// The doubled class names give these rules a higher specificity than the+// `.css-reset, .css-reset *` rule which sets `color` and `background` on+// every descendant - the injection order of the two stylesheets is not+// deterministic.+// The `*` selectors re-establish color inheritance inside the hoverable+// element so that text and `currentColor`-based icons follow the hover state.+const hoverable = `.${HOVERABLE_CLASS_NAME}.${HOVERABLE_CLASS_NAME}`;+const hoverGroup = `.${HOVER_GROUP_CLASS_NAME}`;+const reveal = `.${HOVER_GROUP_REVEAL_CLASS_NAME}.${HOVER_GROUP_REVEAL_CLASS_NAME}`;++export const makeHoverableCSS = () => `+ ${hoverable} {+ background-color: var(${BG_VARIABLE}, ${TRANSPARENT});+ }++ ${hoverable},+ ${hoverable} * {+ color: var(${COLOR_VARIABLE}, inherit);+ }++ @media (hover: hover) {+ ${hoverable}:hover,+ ${hoverGroup}:hover ${hoverable} {+ background-color: var(${HOVER_BG_VARIABLE}, var(${BG_VARIABLE}, ${TRANSPARENT}));+ }++ ${hoverable}:hover,+ ${hoverable}:hover *,+ ${hoverGroup}:hover ${hoverable},+ ${hoverGroup}:hover ${hoverable} * {+ color: var(${HOVER_COLOR_VARIABLE}, var(${COLOR_VARIABLE}, inherit));+ }++ ${hoverGroup} ${reveal} {+ opacity: 0;+ }++ ${hoverGroup}:hover ${reveal} {+ opacity: 1;+ }+ }+`;diff --git a/packages/studio/src/helpers/inject-css.ts b/packages/studio/src/helpers/inject-css.tsindex ef424ae89d..1442b9ab91 100644--- a/packages/studio/src/helpers/inject-css.ts+++ b/packages/studio/src/helpers/inject-css.ts@@ -8,6 +8,7 @@ import {TRANSPARENT,WHITE,} from './colors';+import {makeHoverableCSS} from './hoverable';const makeDefaultGlobalCSS = () => {const dragAreaFactor = 2;@@ -159,6 +160,8 @@ const makeDefaultGlobalCSS = () => {color: var(--remotion-cli-internals-blue) !important;transition: color 0.2s ease-in-out;}++ ${makeHoverableCSS()}`.trim();};