🎥 Make videos programmatically with React
goToComposition() API
Jonny Burger662c154ef320
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.tsindex ed2212e16d..c626542df6 100644--- a/packages/core/src/internals.ts+++ b/packages/core/src/internals.ts@@ -1,3 +1,4 @@+import {createRef} from 'react';import {SharedAudioContext,SharedAudioContextProvider,@@ -106,6 +107,13 @@ import {useRemotionContexts,} from './wrap-remotion-context.js';+// needs to be in core package so gets deduplicated in studio+const compositionSelectorRef = createRef<{+ expandComposition: (compName: string) => void;+ selectComposition: (compName: string) => void;+ toggleFolder: (folderName: string, parentName: string | null) => void;+}>();+// Mark them as Internals so use don't assume this is public// API and are less likely to use itexport const Internals = {@@ -174,6 +182,7 @@ export const Internals = {useLogLevel,playbackLogging,timeValueRef,+ compositionSelectorRef,} as const;export type {diff --git a/packages/example/src/StudioApis/Seek.tsx b/packages/example/src/StudioApis/Seek.tsxindex cbe8cfb690..d13070826c 100644--- a/packages/example/src/StudioApis/Seek.tsx+++ b/packages/example/src/StudioApis/Seek.tsx@@ -1,4 +1,4 @@-import {pause, play, seek, toggle} from '@remotion/studio';+import {goToComposition, pause, play, seek, toggle} from '@remotion/studio';import React, {useCallback} from 'react';import {AbsoluteFill} from 'remotion';@@ -27,6 +27,10 @@ export const Seek: React.FC = () => {play();}, []);+ const onSeventhClick = useCallback(() => {+ goToComposition('freeze-example');+ }, []);+return (<AbsoluteFill><button onClick={onClick}>Seek</button>@@ -35,6 +39,7 @@ export const Seek: React.FC = () => {<button onClick={onFourthClick}>Toggle</button><button onClick={onFifthClick}>Pause</button><button onClick={onSixthClick}>Play</button>+ <button onClick={onSeventhClick}>Go to Composition</button></AbsoluteFill>);};diff --git a/packages/studio/src/api/go-to-composition.ts b/packages/studio/src/api/go-to-composition.tsnew file mode 100644index 0000000000..5bd0585231--- /dev/null+++ b/packages/studio/src/api/go-to-composition.ts@@ -0,0 +1,5 @@+import {Internals} from 'remotion';++export const goToComposition = (compositionId: string) => {+ Internals.compositionSelectorRef.current?.selectComposition(compositionId);+};diff --git a/packages/studio/src/components/CompSelectorRef.tsx b/packages/studio/src/components/CompSelectorRef.tsxnew file mode 100644index 0000000000..986495ec89--- /dev/null+++ b/packages/studio/src/components/CompSelectorRef.tsx@@ -0,0 +1,123 @@+import type React from 'react';+import {+ useCallback,+ useContext,+ useImperativeHandle,+ useMemo,+ useState,+} from 'react';+import {Internals} from 'remotion';+import type {+ ExpandedFoldersRef,+ ExpandedFoldersState,+} from '../helpers/persist-open-folders';+import {+ ExpandedFoldersContext,+ loadExpandedFolders,+ openFolderKey,+ persistExpandedFolders,+} from '../helpers/persist-open-folders';+import {useSelectComposition} from './InitialCompositionLoader';++export const CompSelectorRef: React.FC<{+ readonly children: React.ReactNode;+}> = ({children}) => {+ const {compositions} = useContext(Internals.CompositionManager);+ const [foldersExpanded, setFoldersExpanded] = useState<ExpandedFoldersState>(+ loadExpandedFolders('compositions'),+ );++ const selectComposition = useSelectComposition();++ const toggleFolder = useCallback(+ (folderName: string, parentName: string | null) => {+ setFoldersExpanded((p) => {+ const key = openFolderKey({folderName, parentName});+ const prev = p[key] ?? false;+ const foldersExpandedState: ExpandedFoldersState = {+ ...p,+ [key]: !prev,+ };+ persistExpandedFolders('compositions', foldersExpandedState);+ return foldersExpandedState;+ });+ },+ [],+ );++ useImperativeHandle(+ Internals.compositionSelectorRef,+ () => {+ return {+ expandComposition: (compName) => {+ const compositionToExpand = compositions.find(+ (c) => c.id === compName,+ );+ if (!compositionToExpand) {+ return;+ }++ const {folderName, parentFolderName} = compositionToExpand;+ if (folderName === null) {+ return;+ }++ setFoldersExpanded((previousState) => {+ const foldersExpandedState: ExpandedFoldersState = {+ ...previousState,+ };++ const currentFolder: string | null = folderName;+ const currentParentName: string | null = parentFolderName;+ const key = openFolderKey({+ folderName: currentFolder,+ parentName: currentParentName,+ });++ const splitted = key.split('/');+ for (let i = 0; i < splitted.length - 1; i++) {+ const allExceptLast =+ i === 0+ ? openFolderKey({+ folderName: splitted.filter((s) => s !== 'no-parent')[0],+ parentName: null,+ })+ : splitted.slice(0, i + 1).join('/');+ foldersExpandedState[allExceptLast] = true;+ }++ persistExpandedFolders('compositions', foldersExpandedState);++ return foldersExpandedState;+ });+ },+ selectComposition: (compName) => {+ const comp = compositions.find((c) => c.id === compName);+ if (!comp) {+ throw new Error(`Composition ${compName} not found`);+ }++ selectComposition(comp, true);+ },+ toggleFolder: (folderName, parentName) => {+ toggleFolder(folderName, parentName);+ },+ };+ },+ [compositions, selectComposition, toggleFolder],+ );++ const contextValue: ExpandedFoldersRef = useMemo(() => {+ return {+ foldersExpanded,+ setFoldersExpanded,+ toggleFolder,+ };+ }, [foldersExpanded, setFoldersExpanded, toggleFolder]);++ return (+ <ExpandedFoldersContext.Provider value={contextValue}>+ {children}+ </ExpandedFoldersContext.Provider>+ );+};diff --git a/packages/studio/src/components/CompositionSelector.tsx b/packages/studio/src/components/CompositionSelector.tsxindex b24c00ee99..addd316db7 100644--- a/packages/studio/src/components/CompositionSelector.tsx+++ b/packages/studio/src/components/CompositionSelector.tsx@@ -1,22 +1,13 @@-import React, {- createRef,- useCallback,- useContext,- useImperativeHandle,- useMemo,- useState,-} from 'react';+import React, {useCallback, useContext, useMemo} from 'react';import {Internals} from 'remotion';import {BACKGROUND} from '../helpers/colors';import {createFolderTree,splitParentIntoNameAndParent,} from '../helpers/create-folder-tree';-import type {ExpandedFoldersState} from '../helpers/persist-open-folders';import {- loadExpandedFolders,+ ExpandedFoldersContext,openFolderKey,- persistExpandedFolders,} from '../helpers/persist-open-folders';import {useZIndex} from '../state/z-index';import {CompositionSelectorItem} from './CompositionSelectorItem';@@ -54,81 +45,15 @@ export const getKeysToExpand = (return getKeysToExpand(name, parent, initial);};-export const compositionSelectorRef = createRef<{- expandComposition: (compName: string) => void;-}>();-export const CompositionSelector: React.FC = () => {const {compositions, canvasContent, folders} = useContext(Internals.CompositionManager,);- const [foldersExpanded, setFoldersExpanded] = useState<ExpandedFoldersState>(- loadExpandedFolders('compositions'),- );+ const {foldersExpanded} = useContext(ExpandedFoldersContext);+const {tabIndex} = useZIndex();const selectComposition = useSelectComposition();- const toggleFolder = useCallback(- (folderName: string, parentName: string | null) => {- setFoldersExpanded((p) => {- const key = openFolderKey({folderName, parentName});- const prev = p[key] ?? false;- const foldersExpandedState: ExpandedFoldersState = {- ...p,- [key]: !prev,- };- persistExpandedFolders('compositions', foldersExpandedState);- return foldersExpandedState;- });- },- [],- );-- useImperativeHandle(compositionSelectorRef, () => {- return {- expandComposition: (compName) => {- const compositionToExpand = compositions.find((c) => c.id === compName);- if (!compositionToExpand) {- return;- }-- const {folderName, parentFolderName} = compositionToExpand;- if (folderName === null) {- return;- }-- setFoldersExpanded((previousState) => {- const foldersExpandedState: ExpandedFoldersState = {- ...previousState,- };-- const currentFolder: string | null = folderName;- const currentParentName: string | null = parentFolderName;- const key = openFolderKey({- folderName: currentFolder,- parentName: currentParentName,- });-- const splitted = key.split('/');- for (let i = 0; i < splitted.length - 1; i++) {- const allExceptLast =- i === 0- ? openFolderKey({- folderName: splitted.filter((s) => s !== 'no-parent')[0],- parentName: null,- })- : splitted.slice(0, i + 1).join('/');- foldersExpandedState[allExceptLast] = true;- }-- persistExpandedFolders('compositions', foldersExpandedState);-- return foldersExpandedState;- });- },- };- }, [compositions]);-const items = useMemo(() => {return createFolderTree(compositions, folders, foldersExpanded);}, [compositions, folders, foldersExpanded]);@@ -145,6 +70,16 @@ export const CompositionSelector: React.FC = () => {};}, [showCurrentComposition]);+ const toggleFolder = useCallback(+ (folderName: string, parentName: string | null) => {+ Internals.compositionSelectorRef.current?.toggleFolder(+ folderName,+ parentName,+ );+ },+ [],+ );+return (<div style={container}>{showCurrentComposition ? <CurrentComposition /> : null}diff --git a/packages/studio/src/components/ExplorerPanel.tsx b/packages/studio/src/components/ExplorerPanel.tsxindex 52729de284..ea0185ea07 100644--- a/packages/studio/src/components/ExplorerPanel.tsx+++ b/packages/studio/src/components/ExplorerPanel.tsx@@ -2,6 +2,7 @@ import {createRef, useCallback, useImperativeHandle, useState} from 'react';import {BACKGROUND} from '../helpers/colors';import {AssetSelector} from './AssetSelector';import {CompositionSelector} from './CompositionSelector';+import {CompSelectorRef} from './CompSelectorRef';import {Tab, Tabs} from './Tabs';const container: React.CSSProperties = {@@ -69,25 +70,27 @@ export const ExplorerPanel: React.FC<{}, []);return (- <div style={container} className="css-reset">- <div style={tabsContainer}>- <Tabs>- <Tab- selected={panel === 'compositions'}- onClick={onCompositionsSelected}- >- Compositions- </Tab>- <Tab selected={panel === 'assets'} onClick={onAssetsSelected}>- Assets- </Tab>- </Tabs>+ <CompSelectorRef>+ <div style={container} className="css-reset">+ <div style={tabsContainer}>+ <Tabs>+ <Tab+ selected={panel === 'compositions'}+ onClick={onCompositionsSelected}+ >+ Compositions+ </Tab>+ <Tab selected={panel === 'assets'} onClick={onAssetsSelected}>+ Assets+ </Tab>+ </Tabs>+ </div>+ {panel === 'compositions' ? (+ <CompositionSelector />+ ) : (+ <AssetSelector readOnlyStudio={readOnlyStudio} />+ )}</div>- {panel === 'compositions' ? (- <CompositionSelector />- ) : (- <AssetSelector readOnlyStudio={readOnlyStudio} />- )}- </div>+ </CompSelectorRef>);};diff --git a/packages/studio/src/components/NewComposition/CodemodFooter.tsx b/packages/studio/src/components/NewComposition/CodemodFooter.tsxindex 50eac520cd..82e087cbfe 100644--- a/packages/studio/src/components/NewComposition/CodemodFooter.tsx+++ b/packages/studio/src/components/NewComposition/CodemodFooter.tsx@@ -14,7 +14,7 @@ export const CodemodFooter: React.FC<{readonly valid: boolean;readonly codemod: RecastCodemod;readonly loadingNotification: React.ReactNode;- readonly succeessNotifcation: React.ReactNode;+ readonly successNotification: React.ReactNode;readonly errorNotification: string;readonly genericSubmitLabel: string;readonly submitLabel: (options: {relativeRootPath: string}) => string;@@ -22,7 +22,7 @@ export const CodemodFooter: React.FC<{codemod,valid,loadingNotification,- succeessNotifcation,+ successNotification,errorNotification,genericSubmitLabel,submitLabel,@@ -65,7 +65,7 @@ export const CodemodFooter: React.FC<{signal: new AbortController().signal,}).then(() => {- notification.replaceContent(succeessNotifcation, 2000);+ notification.replaceContent(successNotification, 2000);}).catch((err) => {notification.replaceContent(@@ -78,7 +78,7 @@ export const CodemodFooter: React.FC<{errorNotification,loadingNotification,setSelectedModal,- succeessNotifcation,+ successNotification,]);const getCanApplyCodemod = useCallback(diff --git a/packages/studio/src/components/NewComposition/DeleteComposition.tsx b/packages/studio/src/components/NewComposition/DeleteComposition.tsxindex 531d167459..67ac9c174e 100644--- a/packages/studio/src/components/NewComposition/DeleteComposition.tsx+++ b/packages/studio/src/components/NewComposition/DeleteComposition.tsx@@ -58,7 +58,7 @@ const DeleteCompositionLoaded: React.FC<{<CodemodFootererrorNotification={`Could not delete composition`}loadingNotification={'Deleting'}- succeessNotifcation={`Deleted ${unresolved.id}`}+ successNotification={`Deleted ${unresolved.id}`}genericSubmitLabel={`Delete`}submitLabel={({relativeRootPath}) =>`Delete from ${relativeRootPath}`diff --git a/packages/studio/src/components/NewComposition/DuplicateComposition.tsx b/packages/studio/src/components/NewComposition/DuplicateComposition.tsxindex 8b79aaf94f..cea8db00af 100644--- a/packages/studio/src/components/NewComposition/DuplicateComposition.tsx+++ b/packages/studio/src/components/NewComposition/DuplicateComposition.tsx@@ -358,7 +358,7 @@ const DuplicateCompositionLoaded: React.FC<{<CodemodFooterloadingNotification={'Duplicating...'}errorNotification={'Could not duplicate composition'}- succeessNotifcation={`Duplicated ${unresolved.id}`}+ successNotification={`Duplicated ${unresolved.id} as ${newId}`}genericSubmitLabel={'Duplicate'}submitLabel={({relativeRootPath}) => `Add to ${relativeRootPath}`}codemod={codemod}diff --git a/packages/studio/src/components/NewComposition/RenameComposition.tsx b/packages/studio/src/components/NewComposition/RenameComposition.tsxindex 0576f4551a..9b6a4ab2e8 100644--- a/packages/studio/src/components/NewComposition/RenameComposition.tsx+++ b/packages/studio/src/components/NewComposition/RenameComposition.tsx@@ -99,7 +99,7 @@ const RenameCompositionLoaded: React.FC<{}> = () => {<CodemodFooterloadingNotification={'Renaming...'}errorNotification={'Could not rename composition'}- succeessNotifcation={`Renamed to ${newId}`}+ successNotification={`Renamed to ${newId}`}genericSubmitLabel={'Rename'}submitLabel={({relativeRootPath}) => `Modify ${relativeRootPath}`}codemod={codemod}diff --git a/packages/studio/src/components/QuickSwitcher/QuickSwitcherContent.tsx b/packages/studio/src/components/QuickSwitcher/QuickSwitcherContent.tsxindex 66e7a3df9a..452da3ed4e 100644--- a/packages/studio/src/components/QuickSwitcher/QuickSwitcherContent.tsx+++ b/packages/studio/src/components/QuickSwitcher/QuickSwitcherContent.tsx@@ -15,7 +15,6 @@ import {useMenuStructure,} from '../../helpers/use-menu-structure';import {ModalsContext} from '../../state/modals';-import {compositionSelectorRef} from '../CompositionSelector';import {useSelectComposition} from '../InitialCompositionLoader';import {KeyboardShortcutsExplainer} from '../KeyboardShortcutsExplainer';import {VERTICAL_SCROLLBAR_CLASSNAME} from '../Menu/is-menu-item';@@ -195,11 +194,10 @@ export const QuickSwitcherContent: React.FC<{const selector = `.__remotion-composition[data-compname="${c.id}"]`;- compositionSelectorRef.current?.expandComposition(c.id);+ Internals.compositionSelectorRef.current?.expandComposition(c.id);waitForElm(selector).then(() => {document.querySelector(selector)-?.scrollIntoView({block: 'center'});});},diff --git a/packages/studio/src/helpers/persist-open-folders.ts b/packages/studio/src/helpers/persist-open-folders.tsxsimilarity index 67%rename from packages/studio/src/helpers/persist-open-folders.tsrename to packages/studio/src/helpers/persist-open-folders.tsxindex fb3c3906e7..976dbcd32d 100644--- a/packages/studio/src/helpers/persist-open-folders.ts+++ b/packages/studio/src/helpers/persist-open-folders.tsx@@ -1,3 +1,5 @@+import {createContext} from 'react';+export const openFolderKey = ({folderName,parentName,@@ -34,3 +36,15 @@ export const loadExpandedFolders = (return JSON.parse(item);};++export type ExpandedFoldersRef = {+ toggleFolder: (folderName: string, parentName: string | null) => void;+ foldersExpanded: ExpandedFoldersState;+ setFoldersExpanded: (foldersExpanded: ExpandedFoldersState) => void;+};++export const ExpandedFoldersContext = createContext<ExpandedFoldersRef>({+ toggleFolder: () => {},+ foldersExpanded: {},+ setFoldersExpanded: () => {},+});diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.tsindex b117b4c10c..0d55b52c01 100644--- a/packages/studio/src/index.ts+++ b/packages/studio/src/index.ts@@ -6,6 +6,7 @@ export {} from './api/delete-static-file';export {focusDefaultPropsPath} from './api/focus-default-props-path';export {getStaticFiles, StaticFile} from './api/get-static-files';+export {goToComposition} from './api/go-to-composition';export {UpdateDefaultPropsFunction} from './api/helpers/calc-new-props';export {pause} from './api/pause';export {play} from './api/play';