🎥 Make videos programmatically with React
import {PlayerInternals} from '@remotion/player';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import ReactDOM from 'react-dom';
import {useMobileLayout} from '../helpers/mobile-layout';
import {noop} from '../helpers/noop';
import {HigherZIndex, useZIndex} from '../state/z-index';
import {
getNextMenuTreeId,
isNodeInMenuTree,
MenuTreeContext,
} from './Menu/menu-tree-context';
import {getPortal} from './Menu/portals';
import {
MAX_MENU_WIDTH,
MAX_MOBILE_MENU_WIDTH,
fullScreenOverlay,
menuContainerTowardsTop,
outerPortal,
} from './Menu/styles';
import type {ComboboxValue} from './NewComposition/ComboBox';
import {MenuContent} from './NewComposition/MenuContent';
type OpenState =
| {
type: 'not-open';
}
| {
type: 'open';
left: number;
top: number;
values: readonly ComboboxValue[];
};
type OpenedState = Extract<OpenState, {type: 'open'}>;
type ContextMenuItemsResult = false | readonly ComboboxValue[];
export type ContextMenuItemsFactory = (
event: MouseEvent,
) => ContextMenuItemsResult | Promise<ContextMenuItemsResult>;
export const resolveContextMenuItems = async (
getItems: ContextMenuItemsFactory,
event: MouseEvent,
): Promise<readonly ComboboxValue[] | null> => {
const result = await getItems(event);
if (result === false || result.length === 0) {
return null;
}
return [...result];
};
type ContextMenuProps = {
readonly children: React.ReactNode;
readonly getItems: ContextMenuItemsFactory;
// eslint-disable-next-line react/require-default-props
readonly style?: React.CSSProperties;
// eslint-disable-next-line react/require-default-props
readonly className?: string;
// eslint-disable-next-line react/require-default-props
readonly onPointerDown?: React.PointerEventHandler<HTMLDivElement>;
};
const contextMenuFullScreenOverlay: React.CSSProperties = {
...fullScreenOverlay,
pointerEvents: 'none',
};
const contextMenuOuterPortal: React.CSSProperties = {
...outerPortal,
pointerEvents: 'auto',
};
const contextMenuOpenedEvent = 'remotion-context-menu-opened';
let nextContextMenuId = 0;
const notifyContextMenuOpened = (id: number) => {
window.dispatchEvent(
new CustomEvent(contextMenuOpenedEvent, {
detail: id,
}),
);
};
const ContextMenuPortal: React.FC<{
readonly anchorRef: React.RefObject<HTMLElement | null> | null;
readonly onHide: () => void;
readonly opened: OpenedState;
}> = ({anchorRef, onHide, opened}) => {
const [menuTreeId] = useState(getNextMenuTreeId);
const {currentZIndex} = useZIndex();
const size = PlayerInternals.useElementSize(anchorRef ?? document.body, {
triggerOnWindowResize: true,
shouldApplyCssTransforms: true,
});
const isMobileLayout = useMobileLayout();
const portalStyle = useMemo(() => {
if (!size) {
return;
}
const spaceToBottom = size.windowSize.height - opened.top;
const spaceToTop = opened.top;
const spaceToRight = size.windowSize.width - opened.left;
const spaceToLeft = opened.left;
const minSpaceRequired = isMobileLayout
? MAX_MOBILE_MENU_WIDTH
: MAX_MENU_WIDTH;
const verticalLayout = spaceToTop > spaceToBottom ? 'bottom' : 'top';
const canOpenOnLeft = spaceToLeft >= minSpaceRequired;
const canOpenOnRight = spaceToRight >= minSpaceRequired;
const horizontalLayout = canOpenOnRight ? 'left' : 'right';
return {
...menuContainerTowardsTop,
...(verticalLayout === 'top'
? {
top: opened.top,
}
: {
bottom: size.windowSize.height - opened.top,
}),
...(horizontalLayout === 'left'
? {
left: opened.left,
}
: {
right: canOpenOnLeft ? size.windowSize.width - opened.left : 0,
}),
};
}, [opened.left, opened.top, size, isMobileLayout]);
useEffect(() => {
const preventNativeContextMenu = (event: MouseEvent) => {
event.preventDefault();
};
window.addEventListener('contextmenu', preventNativeContextMenu, true);
return () => {
window.removeEventListener('contextmenu', preventNativeContextMenu, true);
};
}, []);
useEffect(() => {
const dismissWithoutClickThrough = (event: PointerEvent) => {
if (event.button !== 0) {
return;
}
const target = event.target as Node;
if (isNodeInMenuTree(target, menuTreeId)) {
return;
}
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
onHide();
};
window.addEventListener('pointerdown', dismissWithoutClickThrough, true);
return () => {
window.removeEventListener(
'pointerdown',
dismissWithoutClickThrough,
true,
);
};
}, [menuTreeId, onHide]);
// Prevent deselection of a selected item
const onMenuPointerDown = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
e.stopPropagation();
},
[],
);
if (!portalStyle) {
return null;
}
return ReactDOM.createPortal(
<div style={contextMenuFullScreenOverlay}>
<div style={contextMenuOuterPortal} className="css-reset">
<HigherZIndex
onOutsideClick={onHide}
onEscape={onHide}
outsideClickButton="primary"
>
<div
data-remotion-menu-tree-id={menuTreeId}
style={portalStyle}
onPointerDown={onMenuPointerDown}
>
<MenuTreeContext.Provider value={menuTreeId}>
<MenuContent
onNextMenu={noop}
onPreviousMenu={noop}
values={opened.values}
onHide={onHide}
leaveLeftSpace
preselectIndex={false}
topItemCanBeUnselected={false}
fixedHeight={null}
/>
</MenuTreeContext.Provider>
</div>
</HigherZIndex>
</div>
</div>,
getPortal(currentZIndex),
);
};
export const ContextMenu = React.forwardRef<HTMLDivElement, ContextMenuProps>(
(
{
children,
getItems,
style = undefined,
className = undefined,
onPointerDown = undefined,
},
forwardedRef,
) => {
const ref = useRef<HTMLDivElement>(null);
const [id] = useState(() => nextContextMenuId++);
const invocationRef = useRef(0);
const getItemsRef = useRef(getItems);
getItemsRef.current = getItems;
const [opened, setOpened] = useState<OpenState>({type: 'not-open'});
const setRef = useCallback(
(node: HTMLDivElement | null) => {
ref.current = node;
if (typeof forwardedRef === 'function') {
forwardedRef(node);
return;
}
if (forwardedRef) {
(forwardedRef as React.RefObject<HTMLDivElement | null>).current =
node;
}
},
[forwardedRef],
);
useEffect(() => {
const {current} = ref;
if (!current) {
return;
}
const onClick = async (e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
const currentInvocation = ++invocationRef.current;
const values = await resolveContextMenuItems(getItemsRef.current, e);
if (currentInvocation !== invocationRef.current || values === null) {
return false;
}
notifyContextMenuOpened(id);
setOpened({
type: 'open',
left: e.clientX,
top: e.clientY,
values,
});
return false;
};
current.addEventListener('contextmenu', onClick);
return () => {
current.removeEventListener('contextmenu', onClick);
};
}, [id]);
useEffect(() => {
const invocation = invocationRef;
return () => {
invocation.current++;
};
}, []);
const onHide = useCallback(() => {
setOpened({type: 'not-open'});
}, []);
useEffect(() => {
if (opened.type !== 'open') {
return;
}
const onOtherContextMenuOpened = (event: Event) => {
if ((event as CustomEvent<number>).detail === id) {
return;
}
onHide();
};
window.addEventListener(contextMenuOpenedEvent, onOtherContextMenuOpened);
return () => {
window.removeEventListener(
contextMenuOpenedEvent,
onOtherContextMenuOpened,
);
};
}, [id, onHide, opened.type]);
return (
<>
<div
ref={setRef}
onContextMenu={() => false}
style={style}
className={className}
onPointerDown={onPointerDown}
>
{children}
</div>
{opened.type === 'open' ? (
<ContextMenuPortal anchorRef={ref} onHide={onHide} opened={opened} />
) : null}
</>
);
},
);
ContextMenu.displayName = 'ContextMenu';
export const ContextMenuForTarget: React.FC<{
readonly triggerRef: React.RefObject<HTMLElement | SVGElement | null>;
readonly getItems: ContextMenuItemsFactory;
readonly onOpenChange?: (open: boolean) => void;
}> = ({triggerRef, getItems, onOpenChange = undefined}) => {
const [id] = useState(() => nextContextMenuId++);
const invocationRef = useRef(0);
const isOpenRef = useRef(false);
const getItemsRef = useRef(getItems);
const onOpenChangeRef = useRef(onOpenChange);
getItemsRef.current = getItems;
onOpenChangeRef.current = onOpenChange;
const [opened, setOpened] = useState<OpenState>({type: 'not-open'});
// Another menu must be able to cancel an in-flight items factory, too.
const [active, setActive] = useState(false);
const setOpenLifecycleState = useCallback((open: boolean) => {
if (isOpenRef.current === open) {
return;
}
isOpenRef.current = open;
setActive(open);
onOpenChangeRef.current?.(open);
}, []);
useEffect(() => {
const {current} = triggerRef;
if (!current) {
return;
}
const onClick = async (event: Event) => {
const e = event as MouseEvent;
e.preventDefault();
e.stopPropagation();
const currentInvocation = ++invocationRef.current;
setOpenLifecycleState(true);
let values: readonly ComboboxValue[] | null;
try {
values = await resolveContextMenuItems(getItemsRef.current, e);
} catch (err) {
if (currentInvocation === invocationRef.current) {
setOpenLifecycleState(false);
}
throw err;
}
if (currentInvocation !== invocationRef.current || values === null) {
if (currentInvocation === invocationRef.current) {
setOpenLifecycleState(false);
}
return false;
}
notifyContextMenuOpened(id);
setOpened({
type: 'open',
left: e.clientX,
top: e.clientY,
values,
});
return false;
};
current.addEventListener('contextmenu', onClick);
return () => {
current.removeEventListener('contextmenu', onClick);
};
}, [id, setOpenLifecycleState, triggerRef]);
useEffect(() => {
const invocation = invocationRef;
return () => {
invocation.current++;
setOpenLifecycleState(false);
};
}, [setOpenLifecycleState]);
const onHide = useCallback(() => {
invocationRef.current++;
setOpenLifecycleState(false);
setOpened({type: 'not-open'});
}, [setOpenLifecycleState]);
useEffect(() => {
if (!active) {
return;
}
const onOtherContextMenuOpened = (event: Event) => {
if ((event as CustomEvent<number>).detail === id) {
return;
}
onHide();
};
window.addEventListener(contextMenuOpenedEvent, onOtherContextMenuOpened);
return () => {
window.removeEventListener(
contextMenuOpenedEvent,
onOtherContextMenuOpened,
);
};
}, [active, id, onHide]);
return opened.type === 'open' ? (
<ContextMenuPortal anchorRef={null} onHide={onHide} opened={opened} />
) : null;
};