Skip to content

🎥 Make videos programmatically with React

11.6 KB
Raw Blame
import type {StudioKeyboardShortcutAction} from '@remotion/studio-shared';
import type React from 'react';
import {useCallback, useContext, useEffect} from 'react';
import {Internals} from 'remotion';
import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
import {useTimelineCalculator} from '../helpers/calculate-timeline';
import {StudioServerConnectionCtx} from '../helpers/client-id';
import {getPreviewFileType} from '../helpers/get-preview-file-type';
import {pickColor} from '../helpers/pick-color';
import {getStudioAskAIEnabled} from '../helpers/studio-runtime-config';
import {timelineNodePathInfoToKey} from '../helpers/timeline-node-path-key';
import {useKeybinding} from '../helpers/use-keybinding';
import {CheckerboardContext} from '../state/checkerboard';
import {EditorShowGuidesContext} from '../state/editor-guides';
import {EditorShowOutlinesContext} from '../state/editor-outlines';
import {EditorShowPixelGridContext} from '../state/editor-pixel-grid';
import {EditorShowRulersContext} from '../state/editor-rulers';
import {EditorSnappingContext} from '../state/editor-snapping';
import {SetSelectedModalContext} from '../state/modals';
import {askAiModalRef} from './AskAiModal';
import {useCompositionNavigation} from './CompositionSelector';
import {explorerSidebarTabs} from './ExplorerPanelRef';
import {showNotification} from './Notifications/NotificationCenter';
import {OverrideIdToNodePathMappingsRefContext} from './SequencePropsSubscriptionProvider';
import {
	getTimelineSequenceSelectionKey,
	useCurrentTimelineSelectionStateAsRef,
} from './Timeline/TimelineSelection';

const sequencePropShortcuts = [
	{action: 'selectTranslateProp', fieldKey: 'style.translate'},
	{action: 'selectRotateProp', fieldKey: 'style.rotate'},
	{action: 'selectScaleProp', fieldKey: 'style.scale'},
	{action: 'selectOpacityProp', fieldKey: 'style.opacity'},
	{action: 'selectVolumeProp', fieldKey: 'volume'},
] as const satisfies readonly {
	readonly action: StudioKeyboardShortcutAction;
	readonly fieldKey: string;
}[];

const hasOwnProperty = (obj: object, key: string) =>
	Object.prototype.hasOwnProperty.call(obj, key);

export const GlobalKeybindings: React.FC = () => {
	const calculateTimeline = useTimelineCalculator();
	const keybindings = useKeybinding();
	const {setSelectedModal} = useContext(SetSelectedModalContext);
	const {previewServerState} = useContext(StudioServerConnectionCtx);
	const {setCheckerboard} = useContext(CheckerboardContext);
	const {setEditorSnapping} = useContext(EditorSnappingContext);
	const {canvasContent} = useContext(Internals.CompositionManager);
	const {setEditorShowOutlines} = useContext(EditorShowOutlinesContext);
	const {setEditorShowPixelGrid} = useContext(EditorShowPixelGridContext);
	const {editorShowRulers, setEditorShowRulers} = useContext(
		EditorShowRulersContext,
	);
	const {editorShowGuides, setEditorShowGuides} = useContext(
		EditorShowGuidesContext,
	);
	const showGuides = canvasContent?.type === 'composition';
	const showCanvasViewControls =
		showGuides ||
		(canvasContent?.type === 'asset' &&
			getPreviewFileType(canvasContent.asset) === 'video');

	useEffect(() => {
		if (!showCanvasViewControls) return;
		const outlines = showGuides
			? keybindings.registerKeybinding({
					event: 'keydown',
					action: 'toggleOutlines',
					callback: (event) => {
						if (!event.repeat) setEditorShowOutlines((current) => !current);
					},
					preventDefault: true,
					triggerIfInputFieldFocused: false,
					keepRegisteredWhenNotHighestContext: false,
				})
			: null;
		const rulers = keybindings.registerKeybinding({
			event: 'keydown',
			action: 'toggleRulersAndGuides',
			callback: (event) => {
				if (event.repeat) return;
				const visible = editorShowRulers || (showGuides && editorShowGuides);
				setEditorShowRulers(() => !visible);
				if (showGuides) setEditorShowGuides(() => !visible);
			},
			preventDefault: true,
			triggerIfInputFieldFocused: false,
			keepRegisteredWhenNotHighestContext: false,
		});
		const pixelGrid = keybindings.registerKeybinding({
			event: 'keydown',
			action: 'togglePixelGrid',
			callback: (event) => {
				if (!event.repeat) setEditorShowPixelGrid((current) => !current);
			},
			preventDefault: true,
			triggerIfInputFieldFocused: false,
			keepRegisteredWhenNotHighestContext: false,
		});
		return () => {
			outlines?.unregister();
			rulers.unregister();
			pixelGrid.unregister();
		};
	}, [
		keybindings,
		showCanvasViewControls,
		showGuides,
		editorShowRulers,
		editorShowGuides,
		setEditorShowOutlines,
		setEditorShowPixelGrid,
		setEditorShowRulers,
		setEditorShowGuides,
	]);

	const currentSelection = useCurrentTimelineSelectionStateAsRef();
	const sequencesRef = useContext(Internals.SequenceManagerRefContext);
	const videoConfig = Internals.useUnsafeVideoConfig();
	const overrideIdToNodePathMappingsRef = useContext(
		OverrideIdToNodePathMappingsRefContext,
	);
	const {navigateToNextComposition, navigateToPreviousComposition} =
		useCompositionNavigation();
	const video = Internals.useVideo();
	const selectSequenceProp = useCallback(
		(fieldKey: string) => {
			const {selectedItems, selectItems} = currentSelection.current;
			if (videoConfig === null || selectedItems.length !== 1) {
				return false;
			}

			const [selection] = selectedItems;
			if (selection.type !== 'sequence' && selection.type !== 'sequence-prop') {
				return false;
			}

			const selectedTrackKey = getTimelineSequenceSelectionKey(
				selection.nodePathInfo,
			);
			const {tracks: timeline} = calculateTimeline({
				sequences: sequencesRef.current,
				overrideIdsToNodePaths: overrideIdToNodePathMappingsRef.current,
			});
			const track = timeline.find(
				(candidate) =>
					candidate.nodePathInfo !== null &&
					timelineNodePathInfoToKey(candidate.nodePathInfo) ===
						selectedTrackKey,
			);

			if (!track?.sequence.controls) {
				return false;
			}

			const {schema, runtimeValues} = track.sequence.controls;
			const currentRuntimeValueDotNotation = runtimeValues.getSnapshot();
			if (
				!hasOwnProperty(schema, fieldKey) &&
				!hasOwnProperty(currentRuntimeValueDotNotation, fieldKey)
			) {
				return false;
			}

			selectItems(
				[
					{
						type: 'sequence-prop',
						nodePathInfo: {
							...selection.nodePathInfo,
							auxiliaryKeys: ['controls', fieldKey],
						},
						key: fieldKey,
					},
				],
				{reveal: true},
			);
			return true;
		},
		[
			calculateTimeline,
			currentSelection,
			overrideIdToNodePathMappingsRef,
			sequencesRef,
			videoConfig,
		],
	);

	const openRenderModal = useCallback(() => {
		if (!video) {
			return;
		}

		const renderButton = document.getElementById(
			'render-modal-button',
		) as HTMLDivElement;

		renderButton.click();
	}, [video]);

	useEffect(() => {
		const cmdKKey = keybindings.registerKeybinding({
			event: 'keydown',
			action: 'quickSwitcher',
			callback: () => {
				setSelectedModal({
					type: 'quick-switcher',
					mode:
						explorerSidebarTabs.current?.getSelectedPanel() === 'assets'
							? 'assets'
							: 'compositions',
					invocationTimestamp: Date.now(),
					assetSelection: null,
					compositionSelection: null,
				});
			},
			triggerIfInputFieldFocused: true,
			keepRegisteredWhenNotHighestContext: false,
			preventDefault: true,
		});
		const cmdSKey = keybindings.registerKeybinding({
			event: 'keydown',
			key: 's',
			callback: () => {
				showNotification('Remotion saves automatically', 2000);
			},
			triggerIfInputFieldFocused: true,
			keepRegisteredWhenNotHighestContext: false,
			commandCtrlKey: true,
			preventDefault: true,
		});
		const newComposition = keybindings.registerKeybinding({
			event: 'keydown',
			action: 'newComposition',
			callback: () => {
				if (
					getBrowserStudioOperations() === null &&
					(window.remotion_isReadOnlyStudio ||
						previewServerState.type !== 'connected')
				) {
					return;
				}

				setSelectedModal({
					type: 'new-comp',
					folderName: null,
					parentName: null,
					stack: null,
					canvasCapture: null,
				});
			},
			triggerIfInputFieldFocused: false,
			keepRegisteredWhenNotHighestContext: false,
			preventDefault: true,
		});
		const cmdIKey = getStudioAskAIEnabled()
			? keybindings.registerKeybinding({
					event: 'keydown',
					action: 'askAI',
					callback: () => {
						askAiModalRef.current?.toggle();
					},
					triggerIfInputFieldFocused: true,
					keepRegisteredWhenNotHighestContext: true,
					preventDefault: true,
				})
			: null;
		const colorPicker =
			'EyeDropper' in window
				? keybindings.registerKeybinding({
						event: 'keydown',
						action: 'pickColor',
						callback: () => {
							pickColor();
						},
						triggerIfInputFieldFocused: false,
						keepRegisteredWhenNotHighestContext: false,
						preventDefault: true,
					})
				: null;

		const sequencePropKeys = sequencePropShortcuts.map(({action, fieldKey}) =>
			keybindings.registerKeybinding({
				event: 'keydown',
				action,
				callback: (event) => {
					if (selectSequenceProp(fieldKey)) {
						event.preventDefault();
					}
				},
				preventDefault: false,
				triggerIfInputFieldFocused: false,
				keepRegisteredWhenNotHighestContext: false,
			}),
		);
		const render = keybindings.registerKeybinding({
			event: 'keydown',
			action: 'render',
			callback: (event) => {
				if (event.defaultPrevented) return;
				openRenderModal();
				event.preventDefault();
			},
			preventDefault: false,
			triggerIfInputFieldFocused: false,
			keepRegisteredWhenNotHighestContext: false,
		});
		const checkerboard = keybindings.registerKeybinding({
			event: 'keydown',
			action: 'toggleCheckerboard',
			callback: (event) => {
				if (event.defaultPrevented) return;
				setCheckerboard((current) => !current);
				event.preventDefault();
			},
			preventDefault: false,
			triggerIfInputFieldFocused: false,
			keepRegisteredWhenNotHighestContext: false,
		});
		const questionMark = keybindings.registerKeybinding({
			event: 'keydown',
			action: 'showKeyboardShortcuts',
			callback: () => {
				setSelectedModal({
					type: 'settings',
					initialStudioPane: null,
					initialTab: 'shortcuts',
					initialPublicLicenseKey:
						window.remotion_renderDefaults?.publicLicenseKey ?? null,
				});
			},
			preventDefault: true,
			triggerIfInputFieldFocused: false,
			keepRegisteredWhenNotHighestContext: false,
		});

		const pageDown = keybindings.registerKeybinding({
			event: 'keydown',
			action: 'nextComposition',
			callback: navigateToNextComposition,
			preventDefault: true,
			triggerIfInputFieldFocused: false,
			keepRegisteredWhenNotHighestContext: false,
		});

		const pageUp = keybindings.registerKeybinding({
			event: 'keydown',
			action: 'previousComposition',
			callback: navigateToPreviousComposition,
			preventDefault: true,
			triggerIfInputFieldFocused: false,
			keepRegisteredWhenNotHighestContext: false,
		});

		const shiftMKey = keybindings.registerKeybinding({
			event: 'keydown',
			action: 'toggleSnapping',
			callback: () => {
				setEditorSnapping((current) => !current);
			},
			preventDefault: true,
			triggerIfInputFieldFocused: false,
			keepRegisteredWhenNotHighestContext: false,
		});

		return () => {
			for (const sequencePropKey of sequencePropKeys) {
				sequencePropKey.unregister();
			}

			render.unregister();
			checkerboard.unregister();

			questionMark.unregister();
			cmdKKey.unregister();
			cmdSKey.unregister();
			newComposition.unregister();
			cmdIKey?.unregister();
			colorPicker?.unregister();
			pageDown.unregister();
			pageUp.unregister();
			shiftMKey.unregister();
		};
	}, [
		keybindings,
		openRenderModal,
		selectSequenceProp,
		setCheckerboard,
		setEditorSnapping,
		setSelectedModal,
		previewServerState.type,
		navigateToNextComposition,
		navigateToPreviousComposition,
	]);

	return null;
};