Skip to content

🎥 Make videos programmatically with React

only 20 errors remaining

Jonny Burger33083d7cd3f2
diff --git a/packages/cli/src/progress-bar.ts b/packages/cli/src/progress-bar.ts
index 46d2025fbd..52b77c42f7 100644
--- a/packages/cli/src/progress-bar.ts
+++ b/packages/cli/src/progress-bar.ts
@@ -7,7 +7,7 @@ import type {
RenderingProgressInput,
StitchingProgressInput,
} from '@remotion/studio-server';
-import {StudioInternals} from '@remotion/studio-server';
+import {StudioServerClientAPIs} from '@remotion/studio-server/client';
import {chalk} from './chalk';
import {
getFileSizeDownloadBar,
@@ -55,7 +55,7 @@ export const createOverwriteableCliOutput = (options: {
};
}
- const diff = new StudioInternals.AnsiDiff();
+ const diff = new StudioServerClientAPIs.AnsiDiff();
options.cancelSignal?.(() => {
process.stdout.write(diff.finish());
@@ -270,7 +270,7 @@ const getGuiProgressSubtitle = (progress: AggregateRenderProgress): string => {
}
if (progress.copyingState.doneIn === null) {
- return `Copying public dir ${StudioInternals.formatBytes(
+ return `Copying public dir ${StudioServerClientAPIs.formatBytes(
progress.copyingState.bytes,
)}`;
}
diff --git a/packages/studio-server/src/ansi/ansi-diff.ts b/packages/studio-server/src/ansi-diff.ts
similarity index 100%
rename from packages/studio-server/src/ansi/ansi-diff.ts
rename to packages/studio-server/src/ansi-diff.ts
diff --git a/packages/studio-server/src/ansi/ansi-split.ts b/packages/studio-server/src/ansi-split.ts
similarity index 100%
rename from packages/studio-server/src/ansi/ansi-split.ts
rename to packages/studio-server/src/ansi-split.ts
diff --git a/packages/studio-server/src/client.ts b/packages/studio-server/src/client.ts
index fc9857d903..57a92d7eff 100644
--- a/packages/studio-server/src/client.ts
+++ b/packages/studio-server/src/client.ts
@@ -1,9 +1,23 @@
+import {AnsiDiff} from './ansi-diff';
+import {splitAnsi, stripAnsi} from './ansi-split';
import {stringifyDefaultProps} from './codemods/stringify-with-path';
import {DEFAULT_TIMELINE_TRACKS} from './default-max-timeline-tracks';
import {getDefaultOutLocation} from './get-default-out-name';
+import {formatBytes} from './helpers/format-bytes';
+import {hotMiddlewareOptions} from './preview-server/hot-middleware/types';
export const StudioServerClientAPIs = {
stringifyDefaultProps,
DEFAULT_TIMELINE_TRACKS,
getDefaultOutLocation,
+ AnsiDiff,
+ splitAnsi,
+ formatBytes,
+ hotMiddlewareOptions,
+ stripAnsi,
};
+
+export {
+ HotMiddlewareMessage,
+ hotMiddlewareOptions,
+} from './preview-server/hot-middleware/types';
diff --git a/packages/studio/src/error-overlay/react-overlay/utils/get-file-source.ts b/packages/studio-server/src/helpers/get-file-source.ts
similarity index 100%
rename from packages/studio/src/error-overlay/react-overlay/utils/get-file-source.ts
rename to packages/studio-server/src/helpers/get-file-source.ts
diff --git a/packages/studio/src/error-overlay/react-overlay/effects/map-error-to-react-stack.ts b/packages/studio-server/src/helpers/map-error-to-react-stack.ts
similarity index 100%
rename from packages/studio/src/error-overlay/react-overlay/effects/map-error-to-react-stack.ts
rename to packages/studio-server/src/helpers/map-error-to-react-stack.ts
diff --git a/packages/studio/src/error-overlay/react-overlay/utils/open-in-editor.ts b/packages/studio-server/src/helpers/open-in-editor.ts
similarity index 100%
rename from packages/studio/src/error-overlay/react-overlay/utils/open-in-editor.ts
rename to packages/studio-server/src/helpers/open-in-editor.ts
diff --git a/packages/studio-server/src/helpers/use-menu-structure.tsx b/packages/studio-server/src/helpers/use-menu-structure.tsx
deleted file mode 100644
index 67270c80d0..0000000000
--- a/packages/studio-server/src/helpers/use-menu-structure.tsx
+++ /dev/null
@@ -1,841 +0,0 @@
-import {useContext, useMemo} from 'react';
-import {Internals} from 'remotion';
-import {NoReactInternals} from 'remotion/no-react';
-import {cmdOrCtrlCharacter} from '../../../studio/src/error-overlay/remotion-overlay/ShortcutHint';
-import {Checkmark} from '../../../studio/src/icons/Checkmark';
-import {canvasRef} from '../../../studio/src/state/canvas-ref';
-import {CheckerboardContext} from '../../../studio/src/state/checkerboard';
-import {EditorShowGuidesContext} from '../../../studio/src/state/editor-guides';
-import {EditorShowRulersContext} from '../../../studio/src/state/editor-rulers';
-import {EditorZoomGesturesContext} from '../../../studio/src/state/editor-zoom-gestures';
-import type {ModalState} from '../../../studio/src/state/modals';
-import {ModalsContext} from '../../../studio/src/state/modals';
-import {PreviewSizeContext} from '../../../studio/src/state/preview-size';
-import type {SidebarCollapsedState} from '../../../studio/src/state/sidebar';
-import {SidebarContext} from '../../../studio/src/state/sidebar';
-import {Row} from '../components/layout';
-import type {Menu} from '../components/Menu/MenuItem';
-import type {SelectionItem} from '../components/NewComposition/ComboBox';
-import {sendErrorNotification} from '../components/Notifications/NotificationCenter';
-import type {TQuickSwitcherResult} from '../components/QuickSwitcher/QuickSwitcherResult';
-import {getPreviewSizeLabel, getUniqueSizes} from '../components/SizeSelector';
-import {inOutHandles} from '../components/TimelineInOutToggle';
-import {timeValueRef} from '../components/TimeValue';
-import {StudioServerConnectionCtx} from './client-id';
-import {openInEditor} from './open-in-editor';
-import {pickColor} from './pick-color';
-import {areKeyboardShortcutsDisabled} from './use-keybinding';
-
-type Structure = Menu[];
-
-const openExternal = (link: string) => {
- window.open(link, '_blank');
-};
-
-const rotate: React.CSSProperties = {
- transform: `rotate(90deg)`,
-};
-const ICON_SIZE = 16;
-
-export const useMenuStructure = (closeMenu: () => void) => {
- const {setSelectedModal} = useContext(ModalsContext);
- const {checkerboard, setCheckerboard} = useContext(CheckerboardContext);
- const {editorZoomGestures, setEditorZoomGestures} = useContext(
- EditorZoomGesturesContext,
- );
- const {editorShowRulers, setEditorShowRulers} = useContext(
- EditorShowRulersContext,
- );
- const {editorShowGuides, setEditorShowGuides} = useContext(
- EditorShowGuidesContext,
- );
- const {size, setSize} = useContext(PreviewSizeContext);
- const {type} = useContext(StudioServerConnectionCtx).previewServerState;
-
- const {
- setSidebarCollapsedState,
- sidebarCollapsedStateLeft,
- sidebarCollapsedStateRight,
- } = useContext(SidebarContext);
- const sizes = getUniqueSizes(size);
-
- const isFullscreenSupported =
- document.fullscreenEnabled || document.webkitFullscreenEnabled;
-
- const structure = useMemo((): Structure => {
- const struct: Structure = [
- {
- id: 'remotion' as const,
- label: (
- <Row align="center" justify="center">
- <svg
- width={ICON_SIZE}
- height={ICON_SIZE}
- viewBox="-100 -100 400 400"
- style={rotate}
- >
- <path
- fill="#fff"
- stroke="#fff"
- strokeWidth="100"
- strokeLinejoin="round"
- d="M 2 172 a 196 100 0 0 0 195 5 A 196 240 0 0 0 100 2.259 A 196 240 0 0 0 2 172 z"
- />
- </svg>
- </Row>
- ),
- leaveLeftPadding: false,
- items: [
- {
- id: 'about',
- value: 'about',
- label: 'About Remotion',
- onClick: () => {
- closeMenu();
- openExternal('https://remotion.dev');
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'Help: About Remotion',
- },
- {
- id: 'changelog',
- value: 'changelog',
- label: 'Changelog',
- onClick: () => {
- closeMenu();
- openExternal('https://github.com/remotion-dev/remotion/releases');
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'Help: Changelog',
- },
- {
- id: 'license',
- value: 'license',
- label: 'License',
- onClick: () => {
- closeMenu();
- openExternal(
- 'https://github.com/remotion-dev/remotion/blob/main/LICENSE.md',
- );
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'Help: License',
- },
- ],
- quickSwitcherLabel: null,
- },
- {
- id: 'file' as const,
- label: 'File',
- leaveLeftPadding: false,
- items: [
- {
- id: 'new-sequence',
- value: 'new-sequence',
- label: 'New composition...',
- onClick: () => {
- closeMenu();
- setSelectedModal({
- compType: 'composition',
- type: 'new-comp',
- });
- },
- type: 'item' as const,
- keyHint: 'N',
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'New composition...',
- },
- {
- id: 'new-still',
- value: 'new-still',
- label: 'New still...',
- onClick: () => {
- closeMenu();
- setSelectedModal({
- compType: 'still',
- type: 'new-comp',
- });
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'New still...',
- },
- {
- type: 'divider' as const,
- id: 'new-divider',
- },
- {
- id: 'render',
- value: 'render',
- label: 'Render...',
- onClick: () => {
- closeMenu();
- if (type !== 'connected') {
- sendErrorNotification('Restart the studio to render');
- return;
- }
-
- const renderButton = document.getElementById(
- 'render-modal-button',
- ) as HTMLDivElement;
-
- renderButton.click();
- },
- type: 'item' as const,
- keyHint: 'R',
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'Render...',
- },
- window.remotion_editorName
- ? {
- type: 'divider' as const,
- id: 'open-in-editor-divider',
- }
- : null,
- window.remotion_editorName
- ? {
- id: 'open-in-editor',
- value: 'open-in-editor',
- label: `Open in ${window.remotion_editorName}`,
- onClick: async () => {
- await openInEditor({
- originalFileName: `${window.remotion_cwd}`,
- originalLineNumber: 1,
- originalColumnNumber: 1,
- originalFunctionName: null,
- originalScriptCode: null,
- })
- .then((res) => res.json())
- .then(({success}) => {
- if (!success) {
- sendErrorNotification(
- `Could not open ${window.remotion_editorName}`,
- );
- }
- })
- .catch((err) => {
- // eslint-disable-next-line no-console
- console.error(err);
- sendErrorNotification(
- `Could not open ${window.remotion_editorName}`,
- );
- });
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'Open in editor...',
- }
- : null,
- ].filter(NoReactInternals.truthy),
- quickSwitcherLabel: null,
- },
- {
- id: 'view' as const,
- label: 'View',
- leaveLeftPadding: true,
- items: [
- {
- id: 'preview-size',
- keyHint: null,
- label: 'Preview size',
- onClick: () => undefined,
- type: 'item' as const,
- value: 'preview-size',
- leftItem: null,
- subMenu: {
- leaveLeftSpace: true,
- preselectIndex: sizes.findIndex(
- (s) => String(size.size) === String(s.size),
- ),
- items: sizes.map((newSize) => ({
- id: String(newSize.size),
- keyHint: newSize.size === 1 ? '0' : null,
- label: getPreviewSizeLabel(newSize),
- leftItem:
- String(newSize.size) === String(size.size) ? (
- <Checkmark />
- ) : null,
- onClick: () => {
- closeMenu();
- setSize(() => newSize);
- },
- subMenu: null,
- type: 'item' as const,
- value: newSize.size,
- quickSwitcherLabel: null,
- })),
- quickSwitcherLabel: null,
- },
- quickSwitcherLabel: null,
- },
- {
- id: 'editor-zoom-gestures',
- keyHint: null,
- label: 'Zoom and Pan Gestures',
- onClick: () => {
- closeMenu();
- setEditorZoomGestures((c) => !c);
- },
- type: 'item' as const,
- value: 'editor-zoom-gestures',
- leftItem: editorZoomGestures ? <Checkmark /> : null,
- subMenu: null,
- quickSwitcherLabel: editorZoomGestures
- ? 'Disable Zoom and Pan Gestures'
- : 'Enable Zoom and Pan Gestures',
- },
- {
- id: 'show-rulers',
- keyHint: null,
- label: 'Show Rulers',
- onClick: () => {
- closeMenu();
- setEditorShowRulers((c) => !c);
- },
- type: 'item' as const,
- value: 'show-ruler',
- leftItem: editorShowRulers ? <Checkmark /> : null,
- subMenu: null,
- quickSwitcherLabel: editorShowRulers
- ? 'Hide Rulers'
- : 'Show Rulers',
- },
- {
- id: 'show-guides',
- keyHint: null,
- label: 'Show Guides',
- onClick: () => {
- closeMenu();
- setEditorShowGuides((c) => !c);
- },
- type: 'item' as const,
- value: 'show-guides',
- leftItem: editorShowGuides ? <Checkmark /> : null,
- subMenu: null,
- quickSwitcherLabel: editorShowGuides
- ? 'Hide Guides'
- : 'Show Guides',
- },
- {
- id: 'timeline-divider-1',
- type: 'divider' as const,
- },
- {
- id: 'left-sidebar',
- label: 'Left Sidebar',
- keyHint: null,
- type: 'item' as const,
- value: 'preview-size',
- leftItem: null,
- quickSwitcherLabel: null,
- subMenu: {
- leaveLeftSpace: true,
- preselectIndex: 0,
- items: [
- {
- id: 'left-sidebar-responsive',
- keyHint: null,
- label: 'Responsive',
- leftItem:
- sidebarCollapsedStateLeft === 'responsive' ? (
- <Checkmark />
- ) : null,
- onClick: () => {
- closeMenu();
- setSidebarCollapsedState({
- left: 'responsive',
- right: null,
- });
- },
- subMenu: null,
- type: 'item' as const,
- value: 'responsive' as SidebarCollapsedState,
- quickSwitcherLabel: null,
- },
- {
- id: 'left-sidebar-expanded',
- keyHint: null,
- label: 'Expanded',
- leftItem:
- sidebarCollapsedStateLeft === 'expanded' ? (
- <Checkmark />
- ) : null,
- onClick: () => {
- closeMenu();
- setSidebarCollapsedState({left: 'expanded', right: null});
- },
- subMenu: null,
- type: 'item' as const,
- value: 'expanded' as SidebarCollapsedState,
- quickSwitcherLabel: 'Expand',
- },
- {
- id: 'left-sidebar-collapsed',
- keyHint: null,
- label: 'Collapsed',
- leftItem:
- sidebarCollapsedStateLeft === 'collapsed' ? (
- <Checkmark />
- ) : null,
- onClick: () => {
- closeMenu();
- setSidebarCollapsedState({
- left: 'collapsed',
- right: null,
- });
- },
- subMenu: null,
- type: 'item' as const,
- value: 'collapsed' as SidebarCollapsedState,
- quickSwitcherLabel: 'Collapse',
- },
- ],
- },
- onClick: () => undefined,
- },
- {
- id: 'right-sidebar',
- label: 'Right Sidebar',
- keyHint: null,
- type: 'item' as const,
- value: 'preview-size',
- leftItem: null,
- quickSwitcherLabel: null,
- subMenu: {
- leaveLeftSpace: true,
- preselectIndex: 0,
- items: [
- {
- id: 'sidebar-expanded',
- keyHint: null,
- label: 'Expanded',
- leftItem:
- sidebarCollapsedStateRight === 'expanded' ? (
- <Checkmark />
- ) : null,
- onClick: () => {
- closeMenu();
- setSidebarCollapsedState({left: null, right: 'expanded'});
- },
- subMenu: null,
- type: 'item' as const,
- value: 'expanded' as SidebarCollapsedState,
- quickSwitcherLabel: 'Expand',
- },
- {
- id: 'right-sidebar-collapsed',
- keyHint: null,
- label: 'Collapsed',
- leftItem:
- sidebarCollapsedStateRight === 'collapsed' ? (
- <Checkmark />
- ) : null,
- onClick: () => {
- closeMenu();
- setSidebarCollapsedState({
- left: null,
- right: 'collapsed',
- });
- },
- subMenu: null,
- type: 'item' as const,
- value: 'collapsed' as SidebarCollapsedState,
- quickSwitcherLabel: 'Collapse',
- },
- ],
- },
- onClick: () => undefined,
- },
- {
- id: 'timeline-divider-2',
- type: 'divider' as const,
- },
- {
- id: 'checkerboard',
- keyHint: 'T',
- label: 'Transparency as checkerboard',
- onClick: () => {
- closeMenu();
- setCheckerboard((c) => !c);
- },
- type: 'item' as const,
- value: 'checkerboard',
- leftItem: checkerboard ? <Checkmark /> : null,
- subMenu: null,
- quickSwitcherLabel: checkerboard
- ? 'Disable Checkerboard Transparency'
- : 'Enable Checkerboard Transparency',
- },
- {
- id: 'timeline-divider-3',
- type: 'divider' as const,
- },
- {
- id: 'in-out-divider-4',
- type: 'divider' as const,
- },
- {
- id: 'quick-switcher',
- keyHint: `${cmdOrCtrlCharacter}+K`,
- label: 'Quick Switcher',
- onClick: () => {
- closeMenu();
- setSelectedModal({
- type: 'quick-switcher',
- mode: 'compositions',
- invocationTimestamp: Date.now(),
- });
- },
- type: 'item' as const,
- value: 'quick-switcher',
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'Switch composition',
- },
- {
- id: 'in-out-divider-5',
- type: 'divider' as const,
- },
- {
- id: 'in-mark',
- keyHint: 'I',
- label: 'In Mark',
- leftItem: null,
- onClick: () => {
- closeMenu();
- inOutHandles.current?.inMarkClick(null);
- },
- subMenu: null,
- type: 'item' as const,
- value: 'in-mark',
- quickSwitcherLabel: 'Timeline: Set In Mark',
- },
- {
- id: 'out-mark',
- keyHint: 'O',
- label: 'Out Mark',
- leftItem: null,
- onClick: () => {
- closeMenu();
- inOutHandles.current?.outMarkClick(null);
- },
- subMenu: null,
- type: 'item' as const,
- value: 'out-mark',
- quickSwitcherLabel: 'Timeline: Set Out Mark',
- },
- {
- id: 'x-mark',
- keyHint: 'X',
- label: 'Clear In/Out Marks',
- leftItem: null,
- onClick: () => {
- closeMenu();
- inOutHandles.current?.clearMarks();
- },
- subMenu: null,
- type: 'item' as const,
- value: 'clear-marks',
- quickSwitcherLabel: 'Timeline: Clear In and Out Mark',
- },
- {
- id: 'goto-time',
- keyHint: 'G',
- label: 'Go to frame',
- leftItem: null,
- onClick: () => {
- closeMenu();
- timeValueRef.current?.goToFrame();
- },
- subMenu: null,
- type: 'item' as const,
- value: 'clear-marks',
- quickSwitcherLabel: 'Timeline: Clear In and Out Mark',
- },
- {
- id: 'fullscreen-divider',
- type: 'divider' as const,
- },
- isFullscreenSupported
- ? {
- id: 'fullscreen',
- keyHint: null,
- label: 'Fullscreen',
- leftItem: null,
- onClick: () => {
- closeMenu();
- canvasRef.current?.requestFullscreen();
- },
- subMenu: null,
- type: 'item' as const,
- value: 'fullscreen',
- quickSwitcherLabel: 'Go Fullscreen',
- }
- : null,
- ].filter(Internals.truthy),
- },
- 'EyeDropper' in window
- ? {
- id: 'tools' as const,
- label: 'Tools',
- leaveLeftPadding: false,
- items: [
- {
- id: 'color-picker',
- value: 'color-picker',
- label: 'Color Picker',
- onClick: () => {
- closeMenu();
- pickColor();
- },
- leftItem: null,
- keyHint: null,
- subMenu: null,
- type: 'item' as const,
- quickSwitcherLabel: 'Show Color Picker',
- },
- ],
- quickSwitcherLabel: null,
- }
- : null,
- {
- id: 'help' as const,
- label: 'Help',
- leaveLeftPadding: false,
- items: [
- {
- id: 'shortcuts',
- value: 'shortcuts',
- label: areKeyboardShortcutsDisabled()
- ? 'Shortcuts (disabled)'
- : 'Shortcuts',
- onClick: () => {
- closeMenu();
-
- setSelectedModal({
- type: 'quick-switcher',
- mode: 'docs',
- invocationTimestamp: Date.now(),
- });
- },
- keyHint: '?',
- leftItem: null,
- subMenu: null,
- type: 'item' as const,
- quickSwitcherLabel: areKeyboardShortcutsDisabled()
- ? 'Show all Keyboard Shortcuts (disabled)'
- : 'Show all Keyboard Shortcuts',
- },
- {
- id: 'docs',
- value: 'docs',
- label: 'Docs',
- onClick: () => {
- closeMenu();
- openExternal('https://remotion.dev/docs');
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'Visit Documentation',
- },
- {
- id: 'file-issue',
- value: 'file-issue',
- label: 'File an issue',
- onClick: () => {
- closeMenu();
- openExternal(
- 'https://github.com/remotion-dev/remotion/issues/new/choose',
- );
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'File GitHub issue',
- },
- {
- id: 'discord',
- value: 'discord',
- label: 'Join Discord community',
- onClick: () => {
- closeMenu();
- openExternal('https://discord.com/invite/6VzzNDwUwV');
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: null,
- },
- {
- id: 'help-divider-6',
- type: 'divider' as const,
- },
- {
- id: 'insta',
- value: 'insta',
- label: 'Instagram',
- onClick: () => {
- closeMenu();
- openExternal('https://instagram.com/remotion');
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'Follow Remotion on Instagram',
- },
- {
- id: 'twitter',
- value: 'twitter',
- label: 'Twitter',
- onClick: () => {
- closeMenu();
- openExternal('https://twitter.com/remotion');
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'Follow Remotion on Twitter',
- },
- {
- id: 'linkedin',
- value: 'linkedin',
- label: 'LinkedIn',
- onClick: () => {
- closeMenu();
- openExternal('https://www.linkedin.com/company/remotion-dev/');
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'Follow Remotion on LinkedIn',
- },
- {
- id: 'tiktok',
- value: 'tiktok',
- label: 'TikTok',
- onClick: () => {
- closeMenu();
- openExternal('https://www.tiktok.com/@remotion');
- },
- type: 'item' as const,
- keyHint: null,
- leftItem: null,
- subMenu: null,
- quickSwitcherLabel: 'Follow Remotion on TikTok',
- },
- ],
- },
- ].filter(Internals.truthy);
-
- return struct;
- }, [
- sizes,
- editorZoomGestures,
- sidebarCollapsedStateLeft,
- sidebarCollapsedStateRight,
- checkerboard,
- isFullscreenSupported,
- closeMenu,
- setSelectedModal,
- type,
- size.size,
- setSize,
- setEditorZoomGestures,
- setSidebarCollapsedState,
- setCheckerboard,
- editorShowRulers,
- setEditorShowRulers,
- editorShowGuides,
- setEditorShowGuides,
- ]);
-
- return structure;
-};
-
-const getItemLabel = (item: SelectionItem) => {
- if (item.quickSwitcherLabel !== null) {
- return item.quickSwitcherLabel;
- }
-
- if (typeof item.label === 'string') {
- return item.label;
- }
-
- return item.label?.toString() as string;
-};
-
-const itemToSearchResult = (
- item: SelectionItem,
- setSelectedModal: (value: React.SetStateAction<ModalState | null>) => void,
- prefixes: string[],
-): TQuickSwitcherResult[] => {
- if (item.subMenu) {
- return item.subMenu.items
- .map((subItem) => {
- if (subItem.type === 'divider') {
- return null;
- }
-
- return itemToSearchResult(subItem, setSelectedModal, [
- ...prefixes,
- getItemLabel(item),
- ]);
- })
- .flat(1)
- .filter(NoReactInternals.truthy);
- }
-
- return [
- {
- type: 'menu-item',
- id: item.id,
- onSelected: () => {
- setSelectedModal(null);
- item.onClick(item.id, null);
- },
- title: [...prefixes, getItemLabel(item)].join(': '),
- },
- ];
-};
-
-export const makeSearchResults = (
- actions: Structure,
- setSelectedModal: (value: React.SetStateAction<ModalState | null>) => void,
-) => {
- const items: TQuickSwitcherResult[] = actions
- .map((menu) => {
- return menu.items.map((item): TQuickSwitcherResult[] | null => {
- if (item.type === 'divider') {
- return null;
- }
-
- return itemToSearchResult(item, setSelectedModal, []);
- });
- })
- .flat(Infinity)
- .filter(NoReactInternals.truthy) as TQuickSwitcherResult[];
-
- return items;
-};
diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts
index 81461b64b6..b1ce79a9d9 100644
--- a/packages/studio-server/src/index.ts
+++ b/packages/studio-server/src/index.ts
@@ -1,4 +1,31 @@
-import {AnsiDiff} from './ansi/ansi-diff';
+export type {EnumPath} from './enum-path';
+export {EventSourceEvent} from './event-source-events';
+export {ApiRoutes} from './preview-server/api-types';
+export type {PackageManager} from './preview-server/get-package-manager';
+export type {
+ HotMiddlewareOptions,
+ ModuleMap,
+} from './preview-server/hot-middleware/types';
+export {
+ CopyStillToClipboardRequest,
+ OpenInFileExplorerRequest,
+} from './preview-server/job';
+export type {
+ AggregateRenderProgress,
+ BundlingState,
+ CopyingState,
+ DownloadProgress,
+ JobProgressCallback,
+ RenderingProgressInput,
+ RenderJob,
+ RenderJobWithCleanup,
+ RenderStep,
+ StitchingProgressInput,
+} from './preview-server/job';
+export type {
+ RequiredChromiumOptions,
+ UiOpenGlOptions,
+} from './required-chromium-options';
import {installFileWatcher} from './file-watcher';
import {getDefaultOutLocation} from './get-default-out-name';
import {getLatestRemotionVersion} from './get-latest-remotion-version';
@@ -14,21 +41,6 @@ import {
import {waitForLiveEventsListener} from './preview-server/live-events';
import {getRemotionVersion} from './preview-server/update-available';
import {startStudio} from './start-studio';
-export type {AnsiDiff} from './ansi/ansi-diff';
-export type {EnumPath} from './enum-path';
-export type {PackageManager} from './preview-server/get-package-manager';
-export type {
- AggregateRenderProgress,
- BundlingState,
- CopyingState,
- DownloadProgress,
- JobProgressCallback,
- RenderingProgressInput,
- RenderJob,
- RenderJobWithCleanup,
- RenderStep,
- StitchingProgressInput,
-} from './preview-server/job';
export const StudioInternals = {
startStudio,
@@ -42,5 +54,4 @@ export const StudioInternals = {
getLatestRemotionVersion,
getDefaultOutLocation,
installFileWatcher,
- AnsiDiff,
};
diff --git a/packages/studio-server/src/preview-server/hot-middleware/client.ts b/packages/studio-server/src/preview-server/hot-middleware/client.ts
deleted file mode 100644
index d37c125ad1..0000000000
--- a/packages/studio-server/src/preview-server/hot-middleware/client.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-/// <reference lib="dom" />
-/// <reference lib="dom.iterable" />
-
-/* eslint-disable no-console */
-/**
- * Source code is adapted from
- * https://github.com/webpack-contrib/webpack-hot-middleware#readme
- * and rewritten in TypeScript. This file is MIT licensed
- */
-import {stripAnsi} from '../../ansi/ansi-split';
-import {processUpdate} from './process-update';
-import type {HotMiddlewareMessage} from './types';
-import {hotMiddlewareOptions} from './types';
-
-if (typeof window === 'undefined') {
- // do nothing
-} else if (typeof window.EventSource === 'undefined') {
- console.warn(
- 'Unsupported browser: You need a browser that supports EventSource ',
- );
-} else {
- connect();
-}
-
-function eventSourceWrapper() {
- let source: EventSource;
- let lastActivity = Date.now();
- const listeners: ((ev: MessageEvent) => void)[] = [];
-
- init();
- const timer = setInterval(() => {
- if (Date.now() - lastActivity > hotMiddlewareOptions.timeout) {
- handleDisconnect();
- }
- }, hotMiddlewareOptions.timeout / 2);
-
- function init() {
- source = new window.EventSource(hotMiddlewareOptions.path);
- source.onopen = handleOnline;
- source.onerror = handleDisconnect;
- source.onmessage = handleMessage;
- }
-
- function handleOnline() {
- lastActivity = Date.now();
- }
-
- function handleMessage(event: MessageEvent) {
- lastActivity = Date.now();
- for (let i = 0; i < listeners.length; i++) {
- listeners[i](event);
- }
- }
-
- function handleDisconnect() {
- clearInterval(timer);
- source.close();
- setTimeout(init, 1000);
- }
-
- return {
- addMessageListener(fn: (msg: MessageEvent) => void) {
- listeners.push(fn);
- },
- };
-}
-
-declare global {
- interface Window {
- __whmEventSourceWrapper: {
- [key: string]: ReturnType<typeof eventSourceWrapper>;
- };
- __webpack_hot_middleware_reporter__: Reporter;
- }
-}
-
-function getEventSourceWrapper() {
- if (!window.__whmEventSourceWrapper) {
- window.__whmEventSourceWrapper = {};
- }
-
- if (!window.__whmEventSourceWrapper[hotMiddlewareOptions.path]) {
- // cache the wrapper for other entries loaded on
- // the same page with the same hotMiddlewareOptions.path
- window.__whmEventSourceWrapper[hotMiddlewareOptions.path] =
- eventSourceWrapper();
- }
-
- return window.__whmEventSourceWrapper[hotMiddlewareOptions.path];
-}
-
-function connect() {
- getEventSourceWrapper().addMessageListener(handleMessage);
-
- function handleMessage(event: MessageEvent) {
- if (event.data === '\uD83D\uDC93') {
- return;
- }
-
- try {
- processMessage(JSON.parse(event.data));
- } catch (ex) {
- if (hotMiddlewareOptions.warn) {
- console.warn('Invalid HMR message: ' + event.data + '\n' + ex);
- }
- }
- }
-}
-
-// the reporter needs to be a singleton on the page
-// in case the client is being used by multiple bundles
-// we only want to report once.
-// all the errors will go to all clients
-const singletonKey = '__webpack_hot_middleware_reporter__' as const;
-let reporter: Reporter;
-if (typeof window !== 'undefined') {
- if (!window[singletonKey]) {
- window[singletonKey] = createReporter();
- }
-
- reporter = window[singletonKey];
-}
-
-type Reporter = ReturnType<typeof createReporter>;
-
-function createReporter() {
- const styles = {
- errors: 'color: #ff0000;',
- warnings: 'color: #999933;',
- };
- let previousProblems: string | null = null;
-
- function log(type: 'errors' | 'warnings', obj: HotMiddlewareMessage) {
- if (obj.action === 'building') {
- console.log('[Fast Refresh] Building');
- return;
- }
-
- const newProblems = obj[type]
- .map((msg) => {
- return stripAnsi(msg as string);
- })
- .join('\n');
- if (previousProblems === newProblems) {
- return;
- }
-
- previousProblems = newProblems;
-
- const style = styles[type];
- const name = obj.name ? "'" + obj.name + "' " : '';
- const title =
- '[Fast Refresh] bundle ' + name + 'has ' + obj[type].length + ' ' + type;
- // NOTE: console.warn or console.error will print the stack trace
- // which isn't helpful here, so using console.log to escape it.
- if (console.group && console.groupEnd) {
- console.group('%c' + title, style);
- console.log('%c' + newProblems, style);
- console.groupEnd();
- } else {
- console.log(
- '%c' + title + '\n\t%c' + newProblems.replace(/\n/g, '\n\t'),
- style + 'font-weight: bold;',
- style + 'font-weight: normal;',
- );
- }
- }
-
- return {
- cleanProblemsCache() {
- previousProblems = null;
- },
- problems(type: 'errors' | 'warnings', obj: HotMiddlewareMessage) {
- if (hotMiddlewareOptions.warn) {
- log(type, obj);
- }
-
- return true;
- },
- success: () => undefined,
- };
-}
-
-function processMessage(obj: HotMiddlewareMessage) {
- switch (obj.action) {
- case 'building':
- window.remotion_isBuilding?.();
-
- break;
- case 'sync':
- case 'built': {
- let applyUpdate = true;
- if (obj.errors.length > 0) {
- if (reporter) reporter.problems('errors', obj);
- applyUpdate = false;
- } else if (obj.warnings.length > 0) {
- if (reporter) {
- const overlayShown = reporter.problems('warnings', obj);
- applyUpdate = overlayShown;
- }
- } else if (reporter) {
- reporter.cleanProblemsCache();
- reporter.success();
- }
-
- if (applyUpdate) {
- window.remotion_finishedBuilding?.();
- processUpdate(obj.hash, obj.modules, hotMiddlewareOptions);
- }
-
- break;
- }
-
- default:
- break;
- }
-}
diff --git a/packages/studio-server/src/preview-server/hot-middleware/process-update.ts b/packages/studio-server/src/preview-server/hot-middleware/process-update.ts
deleted file mode 100644
index d01a6f12c3..0000000000
--- a/packages/studio-server/src/preview-server/hot-middleware/process-update.ts
+++ /dev/null
@@ -1,197 +0,0 @@
-/* eslint-disable no-console */
-/**
- * Source code is adapted from
- * https://github.com/webpack-contrib/webpack-hot-middleware#readme
- * and rewritten in TypeScript. This file is MIT licensed
- */
-
-/**
- * Based heavily on https://github.com/webpack/webpack/blob/
- * c0afdf9c6abc1dd70707c594e473802a566f7b6e/hot/only-dev-server.js
- * Original copyright Tobias Koppers @sokra (MIT license)
- */
-
-import {notificationCenter} from '../../components/Notifications/NotificationCenter';
-import type {HotMiddlewareOptions, ModuleMap} from './types';
-
-if (!__webpack_module__.hot) {
- throw new Error('[Fast refresh] Hot Module Replacement is disabled.');
-}
-
-const hmrDocsUrl = 'https://webpack.js.org/concepts/hot-module-replacement/'; // eslint-disable-line max-len
-
-let lastHash: string | undefined;
-const failureStatuses = {abort: 1, fail: 1};
-const applyOptions: AcceptOptions = {
- ignoreUnaccepted: true,
- ignoreDeclined: true,
- ignoreErrored: true,
- onUnaccepted(data) {
- console.warn(
- 'Ignored an update to unaccepted module ' +
- (data.chain ?? []).join(' -> '),
- );
- },
- onDeclined(data) {
- console.warn(
- 'Ignored an update to declined module ' + (data.chain ?? []).join(' -> '),
- );
- },
- onErrored(data) {
- console.error(data.error);
- console.warn(
- 'Ignored an error while updating module ' +
- data.moduleId +
- ' (' +
- data.type +
- ')',
- );
- },
-};
-
-function upToDate(hash?: string) {
- if (hash) lastHash = hash;
- return lastHash === __webpack_hash__;
-}
-
-export const processUpdate = function (
- hash: string | undefined,
- moduleMap: ModuleMap,
- options: HotMiddlewareOptions,
-) {
- const {reload} = options;
- if (!upToDate(hash) && __webpack_module__.hot?.status() === 'idle') {
- check();
- }
-
- async function check() {
- const cb = function (err: Error | null, updatedModules: ModuleId[] | null) {
- if (err) return handleError(err);
-
- if (!updatedModules) {
- if (options.warn) {
- console.warn(
- '[Fast refresh] Cannot find update (Full reload needed)',
- );
- console.warn(
- '[Fast refresh] (Probably because of restarting the server)',
- );
- }
-
- performReload();
- return null;
- }
-
- const applyCallback = function (
- applyErr: Error | null,
- renewedModules: ModuleId[],
- ) {
- if (applyErr) return handleError(applyErr);
-
- if (!upToDate()) {
- check();
- }
-
- logUpdates(updatedModules, renewedModules);
- };
-
- const applyResult = __webpack_module__.hot?.apply(applyOptions);
- if ((applyResult as unknown as Promise<unknown>)?.then) {
- // HotModuleReplacement.runtime.js refers to the result as `outdatedModules`
- (applyResult as unknown as Promise<ModuleId[]>)
- .then((outdatedModules) => {
- applyCallback(null, outdatedModules);
- })
- .catch((_err: Error) => applyCallback(_err, []));
- }
- };
-
- try {
- const result = await __webpack_module__.hot?.check(false);
- cb(null, result);
- } catch (err) {
- cb(err as Error, []);
- }
- }
-
- function logUpdates(updatedModules: ModuleId[], renewedModules: ModuleId[]) {
- const unacceptedModules =
- updatedModules?.filter((moduleId) => {
- return renewedModules && renewedModules.indexOf(moduleId) < 0;
- }) ?? [];
-
- if (unacceptedModules.length > 0) {
- if (options.warn) {
- console.warn(
- "[Fast refresh] The following modules couldn't be hot updated: " +
- '(Full reload needed)\n' +
- 'This is usually because the modules which have changed ' +
- '(and their parents) do not know how to hot reload themselves. ' +
- 'See ' +
- hmrDocsUrl +
- ' for more details.',
- );
- unacceptedModules.forEach((moduleId) => {
- console.warn(
- '[Fast refresh] - ' + (moduleMap[moduleId] || moduleId),
- );
- });
- }
-
- performReload();
- return;
- }
-
- if (!renewedModules || renewedModules.length === 0) {
- console.log('[Fast refresh] Nothing hot updated.');
- } else {
- renewedModules.forEach((moduleId) => {
- console.log(
- `[Fast refresh] ${moduleMap[moduleId] || moduleId} fast refreshed.`,
- );
- });
- }
- }
-
- function handleError(err: Error) {
- if ((__webpack_module__.hot?.status() ?? 'nope') in failureStatuses) {
- if (options.warn) {
- console.warn(
- '[Fast refresh] Cannot check for update (Full reload needed)',
- );
- console.warn('[Fast refresh] ' + (err.stack || err.message));
- }
-
- performReload();
- return;
- }
-
- if (options.warn) {
- console.warn(
- '[Fast refresh] Update check failed: ' + (err.stack || err.message),
- );
- if (!window.remotion_unsavedProps) {
- window.location.reload();
- }
- }
- }
-
- function performReload() {
- if (!reload) {
- return;
- }
-
- if (options.warn) console.warn('[Fast refresh] Reloading page');
- if (window.remotion_unsavedProps) {
- notificationCenter.current?.addNotification({
- id: 'random',
- content:
- 'Fast refresh needs to reload the page, but you have unsaved props. Save then reload the page to apply changes.',
- created: new Date().getMilliseconds(),
- duration: 1,
- });
- } else {
- window.location.reload();
- }
- }
-};
diff --git a/packages/studio-server/src/previewEntry.tsx b/packages/studio-server/src/previewEntry.tsx
deleted file mode 100644
index c6c902372e..0000000000
--- a/packages/studio-server/src/previewEntry.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import React from 'react';
-import type {render} from 'react-dom';
-import ReactDOM from 'react-dom/client';
-import {Internals} from 'remotion';
-import {startErrorOverlay} from '../../studio/src/error-overlay/entry-basic';
-import {Studio} from '../../studio/src/Studio';
-import '../styles/styles.css';
-import {NoRegisterRoot} from './components/NoRegisterRoot';
-
-Internals.CSSUtils.injectCSS(
- Internals.CSSUtils.makeDefaultCSS(null, '#1f2428'),
-);
-
-let root: ReturnType<typeof ReactDOM.createRoot> | null = null;
-
-const getRootForElement = () => {
- if (root) {
- return root;
- }
-
- root = ReactDOM.createRoot(Internals.getPreviewDomElement() as HTMLElement);
- return root;
-};
-
-const renderToDOM = (content: React.ReactElement) => {
- // @ts-expect-error
- if (ReactDOM.createRoot) {
- getRootForElement().render(content);
- } else {
- (ReactDOM as unknown as {render: typeof render}).render(
- content,
- Internals.getPreviewDomElement(),
- );
- }
-};
-
-renderToDOM(<NoRegisterRoot />);
-
-Internals.waitForRoot((NewRoot) => {
- renderToDOM(<Studio rootComponent={NewRoot} />);
- startErrorOverlay();
-});
diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.ts
index a8760c2f5b..fa76e148a3 100644
--- a/packages/studio-server/src/routes.ts
+++ b/packages/studio-server/src/routes.ts
@@ -5,14 +5,12 @@ import {createReadStream, existsSync, statSync} from 'node:fs';
import type {IncomingMessage, ServerResponse} from 'node:http';
import path, {join} from 'node:path';
import {URLSearchParams} from 'node:url';
-import {getFileSource} from '../../studio/src/error-overlay/react-overlay/utils/get-file-source';
+import {getFileSource} from './helpers/get-file-source';
import {
getDisplayNameForEditor,
guessEditor,
launchEditor,
-} from '../../studio/src/error-overlay/react-overlay/utils/open-in-editor';
-import {SOURCE_MAP_ENDPOINT} from '../../studio/src/error-overlay/react-overlay/utils/source-map-endpoint';
-import type {SymbolicatedStackFrame} from '../../studio/src/error-overlay/react-overlay/utils/stack-frame';
+} from './helpers/open-in-editor';
import {allApiRoutes} from './preview-server/api-routes';
import type {
ApiHandler,
@@ -27,6 +25,8 @@ import {parseRequestBody} from './preview-server/parse-body';
import {getProjectInfo} from './preview-server/project-info';
import {fetchFolder, getFiles} from './preview-server/public-folder';
import {serveStatic} from './preview-server/serve-static';
+import {SOURCE_MAP_ENDPOINT} from './source-map-endpoint';
+import type {SymbolicatedStackFrame} from './stack-frame';
const editorGuess = guessEditor();
diff --git a/packages/studio/src/error-overlay/react-overlay/utils/source-map-endpoint.ts b/packages/studio-server/src/source-map-endpoint.ts
similarity index 100%
rename from packages/studio/src/error-overlay/react-overlay/utils/source-map-endpoint.ts
rename to packages/studio-server/src/source-map-endpoint.ts
diff --git a/packages/studio/src/error-overlay/react-overlay/utils/stack-frame.ts b/packages/studio-server/src/stack-frame.ts
similarity index 100%
rename from packages/studio/src/error-overlay/react-overlay/utils/stack-frame.ts
rename to packages/studio-server/src/stack-frame.ts
diff --git a/packages/studio-server/src/test/parse-error-stack.test.ts b/packages/studio-server/src/test/parse-error-stack.test.ts
index 54cf3eccda..c1ffa763c7 100644
--- a/packages/studio-server/src/test/parse-error-stack.test.ts
+++ b/packages/studio-server/src/test/parse-error-stack.test.ts
@@ -1,5 +1,5 @@
import {expect, test} from 'vitest';
-import {getLocationFromBuildError} from '../../../studio/src/error-overlay/react-overlay/effects/map-error-to-react-stack';
+import {getLocationFromBuildError} from '../helpers/map-error-to-react-stack';
const message =
'Module build failed (from ../../node_modules/.pnpm/[email protected][email protected]/node_modules/esbuild-loader/dist/index.js):\nError: Transform failed with 1 error:\n/Users/jonathanburger/remotion/packages/example/src/Video.tsx:31:83: error: Expected ">" but found "\\": 100}\'`\\n\\t\\t\\t\\tdurationInFrames={inputProps?.duration ?? 20}\\n\\t\\t\\t/>\\n\\t\\t\\t<Composition\\n\\t\\t\\t\\tid=\\""\n at failureErrorWithLog (/Users/jonathanburger/remotion/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:1475:15)\n at /Users/jonathanburger/remotion/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:1264:29\n at /Users/jonathanburger/remotion/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:611:9\n at handleIncomingPacket (/Users/jonathanburger/remotion/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:708:9)\n at Socket.readFromStdout (/Users/jonathanburger/remotion/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:578:7)\n at Socket.emit (node:events:390:28)\n at addChunk (node:internal/streams/readable:315:12)\n at readableAddChunk (node:internal/streams/readable:289:9)\n at Socket.Readable.push (node:internal/streams/readable:228:10)\n at Pipe.onStreamRead (node:internal/stream_base_commons:199:23)';
diff --git a/packages/studio-server/src/test/parse-module-not-found.test.ts b/packages/studio-server/src/test/parse-module-not-found.test.ts
index 1122d8eb85..b6e121231e 100644
--- a/packages/studio-server/src/test/parse-module-not-found.test.ts
+++ b/packages/studio-server/src/test/parse-module-not-found.test.ts
@@ -1,5 +1,5 @@
import {expect, test} from 'vitest';
-import {getLocationFromBuildError} from '../../../studio/src/error-overlay/react-overlay/effects/map-error-to-react-stack';
+import {getLocationFromBuildError} from '../helpers/map-error-to-react-stack';
const message = "Cannot find module 'does not exist'";
const stack =
diff --git a/packages/studio-server/src/test/secure-source-read.test.ts b/packages/studio-server/src/test/secure-source-read.test.ts
index 2c4306332e..d5851c4169 100644
--- a/packages/studio-server/src/test/secure-source-read.test.ts
+++ b/packages/studio-server/src/test/secure-source-read.test.ts
@@ -1,5 +1,5 @@
import {expect, test} from 'vitest';
-import {getFileSource} from '../../../studio/src/error-overlay/react-overlay/utils/get-file-source';
+import {getFileSource} from '../helpers/get-file-source';
test('Should not allow to read files outside of the project', () => {
expect(() => getFileSource(process.cwd(), '/etc/passwd')).rejects.toMatch(
diff --git a/packages/studio-server/src/ansi/CREDITS.md b/packages/studio/src/ansi/CREDITS.md
similarity index 100%
rename from packages/studio-server/src/ansi/CREDITS.md
rename to packages/studio/src/ansi/CREDITS.md
diff --git a/packages/studio/src/components/Editor.tsx b/packages/studio/src/components/Editor.tsx
index 27ad38629d..147feee830 100644
--- a/packages/studio/src/components/Editor.tsx
+++ b/packages/studio/src/components/Editor.tsx
@@ -1,51 +1,51 @@
-import React, {useEffect} from 'react';
-import {Internals} from 'remotion';
-import {BACKGROUND} from '../helpers/colors';
-import {noop} from '../helpers/noop';
-import {TimelineZoomContext} from '../state/timeline-zoom';
-import {HigherZIndex} from '../state/z-index';
-import {EditorContent} from './EditorContent';
-import {GlobalKeybindings} from './GlobalKeybindings';
-import {Modals} from './Modals';
-import {NotificationCenter} from './Notifications/NotificationCenter';
+import React, { useEffect } from "react";
+import { Internals } from "remotion";
+import { BACKGROUND } from "../helpers/colors";
+import { noop } from "../helpers/noop";
+import { TimelineZoomContext } from "../state/timeline-zoom";
+import { HigherZIndex } from "../state/z-index";
+import { EditorContent } from "./EditorContent";
+import { GlobalKeybindings } from "./GlobalKeybindings";
+import { Modals } from "./Modals";
+import { NotificationCenter } from "./Notifications/NotificationCenter";
const background: React.CSSProperties = {
- backgroundColor: BACKGROUND,
- display: 'flex',
- width: '100%',
- height: '100%',
- flexDirection: 'column',
- position: 'absolute',
+ backgroundColor: BACKGROUND,
+ display: "flex",
+ width: "100%",
+ height: "100%",
+ flexDirection: "column",
+ position: "absolute",
};
-export const Editor: React.FC<{Root: React.FC}> = ({Root}) => {
- useEffect(() => {
- const listenToChanges = (e: BeforeUnloadEvent) => {
- if (window.remotion_unsavedProps) {
- e.returnValue = 'Are you sure you want to leave?';
- }
- };
+export const Editor: React.FC<{ Root: React.FC }> = ({ Root }) => {
+ useEffect(() => {
+ const listenToChanges = (e: BeforeUnloadEvent) => {
+ if (window.remotion_unsavedProps) {
+ e.returnValue = "Are you sure you want to leave?";
+ }
+ };
- window.addEventListener('beforeunload', listenToChanges);
+ window.addEventListener("beforeunload", listenToChanges);
- return () => {
- window.removeEventListener('beforeunload', listenToChanges);
- };
- }, []);
+ return () => {
+ window.removeEventListener("beforeunload", listenToChanges);
+ };
+ }, []);
- return (
- <HigherZIndex onEscape={noop} onOutsideClick={noop}>
- <TimelineZoomContext>
- <div style={background}>
- <Root />
- <Internals.CanUseRemotionHooksProvider>
- <EditorContent />
- <GlobalKeybindings />
- </Internals.CanUseRemotionHooksProvider>
- <NotificationCenter />
- </div>
- <Modals />
- </TimelineZoomContext>
- </HigherZIndex>
- );
+ return (
+ <HigherZIndex onEscape={noop} onOutsideClick={noop}>
+ <TimelineZoomContext>
+ <div style={background}>
+ <Root />
+ <Internals.CanUseRemotionHooksProvider>
+ <EditorContent />
+ <GlobalKeybindings />
+ </Internals.CanUseRemotionHooksProvider>
+ <NotificationCenter />
+ </div>
+ <Modals />
+ </TimelineZoomContext>
+ </HigherZIndex>
+ );
};
diff --git a/packages/studio/src/components/NewComposition/CopyHint.tsx b/packages/studio/src/components/NewComposition/CopyHint.tsx
index b3463e0a32..940f5143a0 100644
--- a/packages/studio/src/components/NewComposition/CopyHint.tsx
+++ b/packages/studio/src/components/NewComposition/CopyHint.tsx
@@ -1,39 +1,39 @@
-import React, {useEffect, useState} from 'react';
-import {LIGHT_TEXT} from '../../helpers/colors';
-import type {ProjectInfo} from '../../preview-server/project-info';
+import React, { useEffect, useState } from "react";
+import { LIGHT_TEXT } from "../../helpers/colors";
+import type { ProjectInfo } from "../../preview-server/project-info";
const style: React.CSSProperties = {
- fontSize: 12,
- color: LIGHT_TEXT,
+ fontSize: 12,
+ color: LIGHT_TEXT,
};
export const CopyHint: React.FC = () => {
- const [projectInfo, setProjectInfo] = useState<ProjectInfo | null>(null);
+ const [projectInfo, setProjectInfo] = useState<ProjectInfo | null>(null);
- useEffect(() => {
- fetch(`/api/project-info`)
- .then((res) => res.json())
- .then((res) => {
- setProjectInfo(res);
- })
- .catch((err) => {
- // eslint-disable-next-line no-console
- console.log('Error fetching info about the project', err);
- setProjectInfo(null);
- });
- }, []);
+ useEffect(() => {
+ fetch(`/api/project-info`)
+ .then((res) => res.json())
+ .then((res) => {
+ setProjectInfo(res);
+ })
+ .catch((err) => {
+ // eslint-disable-next-line no-console
+ console.log("Error fetching info about the project", err);
+ setProjectInfo(null);
+ });
+ }, []);
- if (!projectInfo?.videoFile) {
- return null;
- }
+ if (!projectInfo?.videoFile) {
+ return null;
+ }
- return (
- <div style={style}>
- Copy this into <br /> your{' '}
- <span style={style} title={projectInfo.videoFile as string}>
- {projectInfo.relativeVideoFile}
- </span>{' '}
- file.
- </div>
- );
+ return (
+ <div style={style}>
+ Copy this into <br /> your{" "}
+ <span style={style} title={projectInfo.videoFile as string}>
+ {projectInfo.relativeVideoFile}
+ </span>{" "}
+ file.
+ </div>
+ );
};
diff --git a/packages/studio/src/components/RenderModal/RenderModal.tsx b/packages/studio/src/components/RenderModal/RenderModal.tsx
index 388abf598d..400d62c9ac 100644
--- a/packages/studio/src/components/RenderModal/RenderModal.tsx
+++ b/packages/studio/src/components/RenderModal/RenderModal.tsx
@@ -40,7 +40,7 @@ import { Checkmark } from "../../icons/Checkmark";
import type {
RequiredChromiumOptions,
UiOpenGlOptions,
-} from "../../required-chromium-options";
+} from "@remotion/studio-server";
import { ModalsContext } from "../../state/modals";
import { SidebarContext } from "../../state/sidebar";
import { Spacing } from "../layout";
@@ -78,6 +78,7 @@ import { RenderModalGif } from "./RenderModalGif";
import type { QualityControl } from "./RenderModalPicture";
import { RenderModalPicture } from "./RenderModalPicture";
import { Button } from "../Button";
+import { ShortcutHint } from "../../error-overlay/remotion-overlay/ShortcutHint";
type State =
| {
diff --git a/packages/studio/src/components/RenderModal/RenderModalAdvanced.tsx b/packages/studio/src/components/RenderModal/RenderModalAdvanced.tsx
index a4b2ed0cf4..274b12459d 100644
--- a/packages/studio/src/components/RenderModal/RenderModalAdvanced.tsx
+++ b/packages/studio/src/components/RenderModal/RenderModalAdvanced.tsx
@@ -1,440 +1,440 @@
-import type {Codec, LogLevel, X264Preset} from '@remotion/renderer';
-import {BrowserSafeApis} from '@remotion/renderer/client';
-import type {ChangeEvent} from 'react';
-import React, {useCallback, useMemo} from 'react';
-import {labelx264Preset} from '../../helpers/presets-labels';
+import type { Codec, LogLevel, X264Preset } from "@remotion/renderer";
+import { BrowserSafeApis } from "@remotion/renderer/client";
+import type { ChangeEvent } from "react";
+import React, { useCallback, useMemo } from "react";
+import { labelx264Preset } from "../../helpers/presets-labels";
-import {Checkmark} from '../../icons/Checkmark';
-import type {UiOpenGlOptions} from '../../required-chromium-options';
-import {Checkbox} from '../Checkbox';
-import {Spacing} from '../layout';
-import {VERTICAL_SCROLLBAR_CLASSNAME} from '../Menu/is-menu-item';
-import type {ComboboxValue} from '../NewComposition/ComboBox';
-import {Combobox} from '../NewComposition/ComboBox';
-import {RemotionInput} from '../NewComposition/RemInput';
-import {input, label, optionRow, rightRow} from './layout';
-import {NumberSetting} from './NumberSetting';
-import {OptionExplainerBubble} from './OptionExplainerBubble';
-import {RenderModalEnvironmentVariables} from './RenderModalEnvironmentVariables';
-import {RenderModalHr} from './RenderModalHr';
+import { Checkmark } from "../../icons/Checkmark";
+import type { UiOpenGlOptions } from "@remotion/studio-server";
+import { Checkbox } from "../Checkbox";
+import { Spacing } from "../layout";
+import { VERTICAL_SCROLLBAR_CLASSNAME } from "../Menu/is-menu-item";
+import type { ComboboxValue } from "../NewComposition/ComboBox";
+import { Combobox } from "../NewComposition/ComboBox";
+import { RemotionInput } from "../NewComposition/RemInput";
+import { input, label, optionRow, rightRow } from "./layout";
+import { NumberSetting } from "./NumberSetting";
+import { OptionExplainerBubble } from "./OptionExplainerBubble";
+import { RenderModalEnvironmentVariables } from "./RenderModalEnvironmentVariables";
+import { RenderModalHr } from "./RenderModalHr";
-export type RenderType = 'still' | 'video' | 'audio' | 'sequence';
+export type RenderType = "still" | "video" | "audio" | "sequence";
const container: React.CSSProperties = {
- flex: 1,
- overflowY: 'auto',
+ flex: 1,
+ overflowY: "auto",
};
export const RenderModalAdvanced: React.FC<{
- renderMode: RenderType;
- minConcurrency: number;
- maxConcurrency: number;
- setConcurrency: React.Dispatch<React.SetStateAction<number>>;
- concurrency: number;
- setVerboseLogging: React.Dispatch<React.SetStateAction<LogLevel>>;
- logLevel: LogLevel;
- delayRenderTimeout: number;
- setDelayRenderTimeout: React.Dispatch<React.SetStateAction<number>>;
- disallowParallelEncoding: boolean;
- setDisallowParallelEncoding: React.Dispatch<React.SetStateAction<boolean>>;
- setDisableWebSecurity: React.Dispatch<React.SetStateAction<boolean>>;
- setIgnoreCertificateErrors: React.Dispatch<React.SetStateAction<boolean>>;
- setHeadless: React.Dispatch<React.SetStateAction<boolean>>;
- headless: boolean;
- ignoreCertificateErrors: boolean;
- disableWebSecurity: boolean;
- openGlOption: UiOpenGlOptions;
- setOpenGlOption: React.Dispatch<React.SetStateAction<UiOpenGlOptions>>;
- envVariables: [string, string][];
- setEnvVariables: React.Dispatch<React.SetStateAction<[string, string][]>>;
- x264Preset: X264Preset | null;
- setx264Preset: React.Dispatch<React.SetStateAction<X264Preset>>;
- offthreadVideoCacheSizeInBytes: number | null;
- setOffthreadVideoCacheSizeInBytes: React.Dispatch<
- React.SetStateAction<number | null>
- >;
- codec: Codec;
- enableMultiProcessOnLinux: boolean;
- setChromiumMultiProcessOnLinux: React.Dispatch<React.SetStateAction<boolean>>;
- userAgent: string | null;
- setUserAgent: React.Dispatch<React.SetStateAction<string | null>>;
- beep: boolean;
- setBeep: React.Dispatch<React.SetStateAction<boolean>>;
- repro: boolean;
- setRepro: React.Dispatch<React.SetStateAction<boolean>>;
+ renderMode: RenderType;
+ minConcurrency: number;
+ maxConcurrency: number;
+ setConcurrency: React.Dispatch<React.SetStateAction<number>>;
+ concurrency: number;
+ setVerboseLogging: React.Dispatch<React.SetStateAction<LogLevel>>;
+ logLevel: LogLevel;
+ delayRenderTimeout: number;
+ setDelayRenderTimeout: React.Dispatch<React.SetStateAction<number>>;
+ disallowParallelEncoding: boolean;
+ setDisallowParallelEncoding: React.Dispatch<React.SetStateAction<boolean>>;
+ setDisableWebSecurity: React.Dispatch<React.SetStateAction<boolean>>;
+ setIgnoreCertificateErrors: React.Dispatch<React.SetStateAction<boolean>>;
+ setHeadless: React.Dispatch<React.SetStateAction<boolean>>;
+ headless: boolean;
+ ignoreCertificateErrors: boolean;
+ disableWebSecurity: boolean;
+ openGlOption: UiOpenGlOptions;
+ setOpenGlOption: React.Dispatch<React.SetStateAction<UiOpenGlOptions>>;
+ envVariables: [string, string][];
+ setEnvVariables: React.Dispatch<React.SetStateAction<[string, string][]>>;
+ x264Preset: X264Preset | null;
+ setx264Preset: React.Dispatch<React.SetStateAction<X264Preset>>;
+ offthreadVideoCacheSizeInBytes: number | null;
+ setOffthreadVideoCacheSizeInBytes: React.Dispatch<
+ React.SetStateAction<number | null>
+ >;
+ codec: Codec;
+ enableMultiProcessOnLinux: boolean;
+ setChromiumMultiProcessOnLinux: React.Dispatch<React.SetStateAction<boolean>>;
+ userAgent: string | null;
+ setUserAgent: React.Dispatch<React.SetStateAction<string | null>>;
+ beep: boolean;
+ setBeep: React.Dispatch<React.SetStateAction<boolean>>;
+ repro: boolean;
+ setRepro: React.Dispatch<React.SetStateAction<boolean>>;
}> = ({
- renderMode,
- maxConcurrency,
- minConcurrency,
- setConcurrency,
- concurrency,
- setVerboseLogging,
- logLevel,
- delayRenderTimeout,
- setDelayRenderTimeout,
- disallowParallelEncoding,
- setDisallowParallelEncoding,
- setDisableWebSecurity,
- setIgnoreCertificateErrors,
- setHeadless,
- headless,
- ignoreCertificateErrors,
- disableWebSecurity,
- openGlOption,
- setOpenGlOption,
- setEnvVariables,
- envVariables,
- setx264Preset,
- x264Preset,
- codec,
- offthreadVideoCacheSizeInBytes,
- setOffthreadVideoCacheSizeInBytes,
- enableMultiProcessOnLinux,
- setChromiumMultiProcessOnLinux,
- setUserAgent,
- userAgent,
- beep,
- setBeep,
- repro,
- setRepro,
+ renderMode,
+ maxConcurrency,
+ minConcurrency,
+ setConcurrency,
+ concurrency,
+ setVerboseLogging,
+ logLevel,
+ delayRenderTimeout,
+ setDelayRenderTimeout,
+ disallowParallelEncoding,
+ setDisallowParallelEncoding,
+ setDisableWebSecurity,
+ setIgnoreCertificateErrors,
+ setHeadless,
+ headless,
+ ignoreCertificateErrors,
+ disableWebSecurity,
+ openGlOption,
+ setOpenGlOption,
+ setEnvVariables,
+ envVariables,
+ setx264Preset,
+ x264Preset,
+ codec,
+ offthreadVideoCacheSizeInBytes,
+ setOffthreadVideoCacheSizeInBytes,
+ enableMultiProcessOnLinux,
+ setChromiumMultiProcessOnLinux,
+ setUserAgent,
+ userAgent,
+ beep,
+ setBeep,
+ repro,
+ setRepro,
}) => {
- const extendedOpenGlOptions: UiOpenGlOptions[] = useMemo(() => {
- return [
- 'angle',
- 'egl',
- 'swangle',
- 'swiftshader',
- 'vulkan',
- 'angle-egl',
- 'default',
- ];
- }, []);
- const onVerboseLoggingChanged = useCallback(
- (e: ChangeEvent<HTMLInputElement>) => {
- setVerboseLogging(e.target.checked ? 'verbose' : 'info');
- },
- [setVerboseLogging],
- );
+ const extendedOpenGlOptions: UiOpenGlOptions[] = useMemo(() => {
+ return [
+ "angle",
+ "egl",
+ "swangle",
+ "swiftshader",
+ "vulkan",
+ "angle-egl",
+ "default",
+ ];
+ }, []);
+ const onVerboseLoggingChanged = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ setVerboseLogging(e.target.checked ? "verbose" : "info");
+ },
+ [setVerboseLogging]
+ );
- const toggleCustomOffthreadVideoCacheSizeInBytes = useCallback(() => {
- setOffthreadVideoCacheSizeInBytes((previous) => {
- if (previous === null) {
- return 512 * 1024 * 1024;
- }
+ const toggleCustomOffthreadVideoCacheSizeInBytes = useCallback(() => {
+ setOffthreadVideoCacheSizeInBytes((previous) => {
+ if (previous === null) {
+ return 512 * 1024 * 1024;
+ }
- return null;
- });
- }, [setOffthreadVideoCacheSizeInBytes]);
+ return null;
+ });
+ }, [setOffthreadVideoCacheSizeInBytes]);
- const toggleCustomUserAgent = useCallback(() => {
- setUserAgent((previous) => {
- if (previous === null) {
- return 'Mozilla/5.0 (Remotion)';
- }
+ const toggleCustomUserAgent = useCallback(() => {
+ setUserAgent((previous) => {
+ if (previous === null) {
+ return "Mozilla/5.0 (Remotion)";
+ }
- return null;
- });
- }, [setUserAgent]);
+ return null;
+ });
+ }, [setUserAgent]);
- const onDisallowParallelEncodingChanged = useCallback(
- (e: ChangeEvent<HTMLInputElement>) => {
- setDisallowParallelEncoding(e.target.checked);
- },
- [setDisallowParallelEncoding],
- );
+ const onDisallowParallelEncodingChanged = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ setDisallowParallelEncoding(e.target.checked);
+ },
+ [setDisallowParallelEncoding]
+ );
- const onDisableWebSecurityChanged = useCallback(
- (e: ChangeEvent<HTMLInputElement>) => {
- setDisableWebSecurity(e.target.checked);
- },
- [setDisableWebSecurity],
- );
+ const onDisableWebSecurityChanged = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ setDisableWebSecurity(e.target.checked);
+ },
+ [setDisableWebSecurity]
+ );
- const onEnableMultiProcessOnLinux = useCallback(
- (e: ChangeEvent<HTMLInputElement>) => {
- setChromiumMultiProcessOnLinux(e.target.checked);
- },
- [setChromiumMultiProcessOnLinux],
- );
+ const onEnableMultiProcessOnLinux = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ setChromiumMultiProcessOnLinux(e.target.checked);
+ },
+ [setChromiumMultiProcessOnLinux]
+ );
- const onIgnoreCertificatErrors = useCallback(
- (e: ChangeEvent<HTMLInputElement>) => {
- setIgnoreCertificateErrors(e.target.checked);
- },
- [setIgnoreCertificateErrors],
- );
+ const onIgnoreCertificatErrors = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ setIgnoreCertificateErrors(e.target.checked);
+ },
+ [setIgnoreCertificateErrors]
+ );
- const onHeadless = useCallback(
- (e: ChangeEvent<HTMLInputElement>) => {
- setHeadless(e.target.checked);
- },
- [setHeadless],
- );
+ const onHeadless = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ setHeadless(e.target.checked);
+ },
+ [setHeadless]
+ );
- const onUserAgentChanged: React.ChangeEventHandler<HTMLInputElement> =
- useCallback(
- (e) => {
- setUserAgent(e.target.value);
- },
- [setUserAgent],
- );
+ const onUserAgentChanged: React.ChangeEventHandler<HTMLInputElement> =
+ useCallback(
+ (e) => {
+ setUserAgent(e.target.value);
+ },
+ [setUserAgent]
+ );
- const onPlayBeepSound = useCallback(
- (e: ChangeEvent<HTMLInputElement>) => {
- setBeep(e.target.checked);
- },
- [setBeep],
- );
+ const onPlayBeepSound = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ setBeep(e.target.checked);
+ },
+ [setBeep]
+ );
- const onReproToggle = useCallback(
- (e: ChangeEvent<HTMLInputElement>) => {
- setRepro(e.target.checked);
- },
- [setRepro],
- );
+ const onReproToggle = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ setRepro(e.target.checked);
+ },
+ [setRepro]
+ );
- const openGlOptions = useMemo((): ComboboxValue[] => {
- return extendedOpenGlOptions.map((option) => {
- return {
- label: option === 'default' ? 'Default' : option,
- onClick: () => setOpenGlOption(option),
- key: option,
- leftItem: openGlOption === option ? <Checkmark /> : null,
- id: option,
- keyHint: null,
- quickSwitcherLabel: null,
- subMenu: null,
- type: 'item',
- value: option,
- };
- });
- }, [extendedOpenGlOptions, openGlOption, setOpenGlOption]);
+ const openGlOptions = useMemo((): ComboboxValue[] => {
+ return extendedOpenGlOptions.map((option) => {
+ return {
+ label: option === "default" ? "Default" : option,
+ onClick: () => setOpenGlOption(option),
+ key: option,
+ leftItem: openGlOption === option ? <Checkmark /> : null,
+ id: option,
+ keyHint: null,
+ quickSwitcherLabel: null,
+ subMenu: null,
+ type: "item",
+ value: option,
+ };
+ });
+ }, [extendedOpenGlOptions, openGlOption, setOpenGlOption]);
- const x264PresetOptions = useMemo((): ComboboxValue[] => {
- return BrowserSafeApis.x264PresetOptions.map((option) => {
- return {
- label: labelx264Preset(option),
- onClick: () => setx264Preset(option),
- key: option,
- selected: x264Preset === option,
- type: 'item',
- id: option,
- keyHint: null,
- leftItem: null,
- quickSwitcherLabel: null,
- subMenu: null,
- value: option,
- };
- });
- }, [setx264Preset, x264Preset]);
+ const x264PresetOptions = useMemo((): ComboboxValue[] => {
+ return BrowserSafeApis.x264PresetOptions.map((option) => {
+ return {
+ label: labelx264Preset(option),
+ onClick: () => setx264Preset(option),
+ key: option,
+ selected: x264Preset === option,
+ type: "item",
+ id: option,
+ keyHint: null,
+ leftItem: null,
+ quickSwitcherLabel: null,
+ subMenu: null,
+ value: option,
+ };
+ });
+ }, [setx264Preset, x264Preset]);
- const changeOffthreadVideoCacheSizeInBytes: React.Dispatch<
- React.SetStateAction<number>
- > = useCallback(
- (cb) => {
- setOffthreadVideoCacheSizeInBytes((prev) => {
- if (prev === null) {
- throw new TypeError('Expected previous value');
- }
+ const changeOffthreadVideoCacheSizeInBytes: React.Dispatch<
+ React.SetStateAction<number>
+ > = useCallback(
+ (cb) => {
+ setOffthreadVideoCacheSizeInBytes((prev) => {
+ if (prev === null) {
+ throw new TypeError("Expected previous value");
+ }
- if (typeof cb === 'function') {
- return cb(prev);
- }
+ if (typeof cb === "function") {
+ return cb(prev);
+ }
- return cb;
- });
- },
- [setOffthreadVideoCacheSizeInBytes],
- );
+ return cb;
+ });
+ },
+ [setOffthreadVideoCacheSizeInBytes]
+ );
- return (
- <div style={container} className={VERTICAL_SCROLLBAR_CLASSNAME}>
- <div style={optionRow}>
- <div style={label}>Verbose logging</div>
- <div style={rightRow}>
- <Checkbox
- checked={logLevel === 'verbose'}
- onChange={onVerboseLoggingChanged}
- name="verbose-logging"
- />
- </div>
- </div>
- {renderMode === 'still' ? null : (
- <NumberSetting
- min={minConcurrency}
- max={maxConcurrency}
- step={1}
- name="Concurrency"
- formatter={(w) => `${w}x`}
- onValueChanged={setConcurrency}
- value={concurrency}
- />
- )}
- {renderMode === 'video' && codec === 'h264' ? (
- <div style={optionRow}>
- <div style={label}>x264 Preset</div>
- <div style={rightRow}>
- <Combobox
- title={x264Preset as string}
- selectedId={x264Preset as string}
- values={x264PresetOptions}
- />
- </div>
- </div>
- ) : null}
+ return (
+ <div style={container} className={VERTICAL_SCROLLBAR_CLASSNAME}>
+ <div style={optionRow}>
+ <div style={label}>Verbose logging</div>
+ <div style={rightRow}>
+ <Checkbox
+ checked={logLevel === "verbose"}
+ onChange={onVerboseLoggingChanged}
+ name="verbose-logging"
+ />
+ </div>
+ </div>
+ {renderMode === "still" ? null : (
+ <NumberSetting
+ min={minConcurrency}
+ max={maxConcurrency}
+ step={1}
+ name="Concurrency"
+ formatter={(w) => `${w}x`}
+ onValueChanged={setConcurrency}
+ value={concurrency}
+ />
+ )}
+ {renderMode === "video" && codec === "h264" ? (
+ <div style={optionRow}>
+ <div style={label}>x264 Preset</div>
+ <div style={rightRow}>
+ <Combobox
+ title={x264Preset as string}
+ selectedId={x264Preset as string}
+ values={x264PresetOptions}
+ />
+ </div>
+ </div>
+ ) : null}
- <NumberSetting
- // Also appears in packages/renderer/src/validate-puppeteer-timeout.ts
- min={7_000}
- max={900_000}
- name="delayRender() timeout"
- onValueChanged={setDelayRenderTimeout}
- formatter={(w) => `${w}ms`}
- step={1000}
- value={delayRenderTimeout}
- />
- <div style={optionRow}>
- <div style={label}>No parallel encoding</div>
- <div style={rightRow}>
- <Checkbox
- checked={disallowParallelEncoding}
- onChange={onDisallowParallelEncodingChanged}
- name="disallow-parallel-encoding"
- />
- </div>
- </div>
- {renderMode === 'audio' ? null : (
- <div style={optionRow}>
- <div style={label}>Custom OffthreadVideo cache</div>
- <Spacing x={0.5} />
- <OptionExplainerBubble id="offthreadVideoCacheSizeInBytes" />
- <div style={rightRow}>
- <Checkbox
- checked={offthreadVideoCacheSizeInBytes !== null}
- onChange={toggleCustomOffthreadVideoCacheSizeInBytes}
- name="custom-audio-bitrate"
- />
- </div>
- </div>
- )}
- {renderMode === 'audio' ||
- offthreadVideoCacheSizeInBytes === null ? null : (
- <NumberSetting
- min={minConcurrency}
- max={2000 * 1024 * 1024}
- step={1024}
- name="OffthreadVideo cache size"
- formatter={(w) => `${w} bytes`}
- onValueChanged={changeOffthreadVideoCacheSizeInBytes}
- value={offthreadVideoCacheSizeInBytes}
- />
- )}
- <RenderModalHr />
- <div style={optionRow}>
- <div style={label}>Disable web security</div>
- <div style={rightRow}>
- <Checkbox
- checked={disableWebSecurity}
- onChange={onDisableWebSecurityChanged}
- name="disable-web-security"
- />
- </div>
- </div>
- <div style={optionRow}>
- <div style={label}>Ignore certificate errors</div>
- <div style={rightRow}>
- <Checkbox
- checked={ignoreCertificateErrors}
- onChange={onIgnoreCertificatErrors}
- name="ignore-certificate-errors"
- />
- </div>
- </div>
- <div style={optionRow}>
- <div style={label}>Headless mode</div>
- <div style={rightRow}>
- <Checkbox checked={headless} onChange={onHeadless} name="headless" />
- </div>
- </div>
- <div style={optionRow}>
- <div style={label}>
- OpenGL render backend <Spacing x={0.5} />
- <OptionExplainerBubble id="glOption" />
- </div>
+ <NumberSetting
+ // Also appears in packages/renderer/src/validate-puppeteer-timeout.ts
+ min={7_000}
+ max={900_000}
+ name="delayRender() timeout"
+ onValueChanged={setDelayRenderTimeout}
+ formatter={(w) => `${w}ms`}
+ step={1000}
+ value={delayRenderTimeout}
+ />
+ <div style={optionRow}>
+ <div style={label}>No parallel encoding</div>
+ <div style={rightRow}>
+ <Checkbox
+ checked={disallowParallelEncoding}
+ onChange={onDisallowParallelEncodingChanged}
+ name="disallow-parallel-encoding"
+ />
+ </div>
+ </div>
+ {renderMode === "audio" ? null : (
+ <div style={optionRow}>
+ <div style={label}>Custom OffthreadVideo cache</div>
+ <Spacing x={0.5} />
+ <OptionExplainerBubble id="offthreadVideoCacheSizeInBytes" />
+ <div style={rightRow}>
+ <Checkbox
+ checked={offthreadVideoCacheSizeInBytes !== null}
+ onChange={toggleCustomOffthreadVideoCacheSizeInBytes}
+ name="custom-audio-bitrate"
+ />
+ </div>
+ </div>
+ )}
+ {renderMode === "audio" ||
+ offthreadVideoCacheSizeInBytes === null ? null : (
+ <NumberSetting
+ min={minConcurrency}
+ max={2000 * 1024 * 1024}
+ step={1024}
+ name="OffthreadVideo cache size"
+ formatter={(w) => `${w} bytes`}
+ onValueChanged={changeOffthreadVideoCacheSizeInBytes}
+ value={offthreadVideoCacheSizeInBytes}
+ />
+ )}
+ <RenderModalHr />
+ <div style={optionRow}>
+ <div style={label}>Disable web security</div>
+ <div style={rightRow}>
+ <Checkbox
+ checked={disableWebSecurity}
+ onChange={onDisableWebSecurityChanged}
+ name="disable-web-security"
+ />
+ </div>
+ </div>
+ <div style={optionRow}>
+ <div style={label}>Ignore certificate errors</div>
+ <div style={rightRow}>
+ <Checkbox
+ checked={ignoreCertificateErrors}
+ onChange={onIgnoreCertificatErrors}
+ name="ignore-certificate-errors"
+ />
+ </div>
+ </div>
+ <div style={optionRow}>
+ <div style={label}>Headless mode</div>
+ <div style={rightRow}>
+ <Checkbox checked={headless} onChange={onHeadless} name="headless" />
+ </div>
+ </div>
+ <div style={optionRow}>
+ <div style={label}>
+ OpenGL render backend <Spacing x={0.5} />
+ <OptionExplainerBubble id="glOption" />
+ </div>
- <div style={rightRow}>
- <Combobox
- values={openGlOptions}
- selectedId={openGlOption}
- title="OpenGl option"
- />
- </div>
- </div>
- <div style={optionRow}>
- <div style={label}>Multi-process Chrome on Linux</div>
- <Spacing x={0.5} />
- <OptionExplainerBubble id="enableMultiprocessOnLinuxOption" />
- <div style={rightRow}>
- <Checkbox
- checked={enableMultiProcessOnLinux}
- onChange={onEnableMultiProcessOnLinux}
- name="enable-multi-process-on-linux"
- />
- </div>
- </div>
- <div style={optionRow}>
- <div style={label}>Custom User Agent</div>
- <div style={rightRow}>
- <Checkbox
- checked={userAgent !== null}
- onChange={toggleCustomUserAgent}
- name="custom-user-agent"
- />
- </div>
- </div>
- {userAgent === null ? null : (
- <div style={optionRow}>
- <div style={label}>User Agent</div>
- <div style={rightRow}>
- <div>
- <RemotionInput
- style={input}
- value={userAgent}
- onChange={onUserAgentChanged}
- status="ok"
- rightAlign
- />
- </div>
- </div>
- </div>
- )}
- <div style={optionRow}>
- <div style={label}>
- Create a reproduction <OptionExplainerBubble id="reproOption" />
- </div>
+ <div style={rightRow}>
+ <Combobox
+ values={openGlOptions}
+ selectedId={openGlOption}
+ title="OpenGl option"
+ />
+ </div>
+ </div>
+ <div style={optionRow}>
+ <div style={label}>Multi-process Chrome on Linux</div>
+ <Spacing x={0.5} />
+ <OptionExplainerBubble id="enableMultiprocessOnLinuxOption" />
+ <div style={rightRow}>
+ <Checkbox
+ checked={enableMultiProcessOnLinux}
+ onChange={onEnableMultiProcessOnLinux}
+ name="enable-multi-process-on-linux"
+ />
+ </div>
+ </div>
+ <div style={optionRow}>
+ <div style={label}>Custom User Agent</div>
+ <div style={rightRow}>
+ <Checkbox
+ checked={userAgent !== null}
+ onChange={toggleCustomUserAgent}
+ name="custom-user-agent"
+ />
+ </div>
+ </div>
+ {userAgent === null ? null : (
+ <div style={optionRow}>
+ <div style={label}>User Agent</div>
+ <div style={rightRow}>
+ <div>
+ <RemotionInput
+ style={input}
+ value={userAgent}
+ onChange={onUserAgentChanged}
+ status="ok"
+ rightAlign
+ />
+ </div>
+ </div>
+ </div>
+ )}
+ <div style={optionRow}>
+ <div style={label}>
+ Create a reproduction <OptionExplainerBubble id="reproOption" />
+ </div>
- <div style={rightRow}>
- <Checkbox checked={repro} onChange={onReproToggle} name="repro" />
- </div>
- </div>
- <div style={optionRow}>
- <div style={label}>
- Beep when finished <OptionExplainerBubble id="beepOnFinishOption" />
- </div>
+ <div style={rightRow}>
+ <Checkbox checked={repro} onChange={onReproToggle} name="repro" />
+ </div>
+ </div>
+ <div style={optionRow}>
+ <div style={label}>
+ Beep when finished <OptionExplainerBubble id="beepOnFinishOption" />
+ </div>
- <div style={rightRow}>
- <Checkbox
- checked={beep}
- onChange={onPlayBeepSound}
- name="beep-when-finished"
- />
- </div>
- </div>
- <RenderModalHr />
- <RenderModalEnvironmentVariables
- envVariables={envVariables}
- setEnvVariables={setEnvVariables}
- />
- </div>
- );
+ <div style={rightRow}>
+ <Checkbox
+ checked={beep}
+ onChange={onPlayBeepSound}
+ name="beep-when-finished"
+ />
+ </div>
+ </div>
+ <RenderModalHr />
+ <RenderModalEnvironmentVariables
+ envVariables={envVariables}
+ setEnvVariables={setEnvVariables}
+ />
+ </div>
+ );
};
diff --git a/packages/studio/src/components/RenderModal/RenderModalEnvironmentVariables.tsx b/packages/studio/src/components/RenderModal/RenderModalEnvironmentVariables.tsx
index 724ac414a5..2f8010ff43 100644
--- a/packages/studio/src/components/RenderModal/RenderModalEnvironmentVariables.tsx
+++ b/packages/studio/src/components/RenderModal/RenderModalEnvironmentVariables.tsx
@@ -1,95 +1,95 @@
-import React, {useCallback} from 'react';
-import {Button} from '../../error-overlay/remotion-overlay/Button';
-import {LIGHT_TEXT} from '../../helpers/colors';
-import {Spacing} from '../layout';
-import {EnvInput} from './EnvInput';
+import React, { useCallback } from "react";
+import { LIGHT_TEXT } from "../../helpers/colors";
+import { Button } from "../Button";
+import { Spacing } from "../layout";
+import { EnvInput } from "./EnvInput";
const title: React.CSSProperties = {
- fontSize: 14,
- fontWeight: 'bold',
- color: LIGHT_TEXT,
- marginLeft: 16,
+ fontSize: 14,
+ fontWeight: "bold",
+ color: LIGHT_TEXT,
+ marginLeft: 16,
};
const container: React.CSSProperties = {
- marginTop: 20,
+ marginTop: 20,
};
const button: React.CSSProperties = {
- marginLeft: 16,
+ marginLeft: 16,
};
export const RenderModalEnvironmentVariables: React.FC<{
- envVariables: [string, string][];
- setEnvVariables: React.Dispatch<React.SetStateAction<[string, string][]>>;
-}> = ({envVariables, setEnvVariables}) => {
- const onEnvValChange = useCallback(
- (index: number, value: string) => {
- setEnvVariables((oldEnv) => {
- const newEnv = [...oldEnv];
- newEnv[index][1] = value;
- return newEnv;
- });
- },
- [setEnvVariables],
- );
+ envVariables: [string, string][];
+ setEnvVariables: React.Dispatch<React.SetStateAction<[string, string][]>>;
+}> = ({ envVariables, setEnvVariables }) => {
+ const onEnvValChange = useCallback(
+ (index: number, value: string) => {
+ setEnvVariables((oldEnv) => {
+ const newEnv = [...oldEnv];
+ newEnv[index][1] = value;
+ return newEnv;
+ });
+ },
+ [setEnvVariables]
+ );
- const onEnvKeyChange = useCallback(
- (index: number, value: string) => {
- setEnvVariables((oldEnv) => {
- const newEnv = [...oldEnv];
- newEnv[index][0] = value;
- return newEnv;
- });
- },
- [setEnvVariables],
- );
+ const onEnvKeyChange = useCallback(
+ (index: number, value: string) => {
+ setEnvVariables((oldEnv) => {
+ const newEnv = [...oldEnv];
+ newEnv[index][0] = value;
+ return newEnv;
+ });
+ },
+ [setEnvVariables]
+ );
- const onDelete = useCallback(
- (index: number) => {
- setEnvVariables((oldEnv) => oldEnv.filter((_, idx) => idx !== index));
- },
- [setEnvVariables],
- );
+ const onDelete = useCallback(
+ (index: number) => {
+ setEnvVariables((oldEnv) => oldEnv.filter((_, idx) => idx !== index));
+ },
+ [setEnvVariables]
+ );
- const addField = useCallback(() => {
- setEnvVariables((oldEnv) => [...oldEnv, ['', '']]);
- }, [setEnvVariables]);
+ const addField = useCallback(() => {
+ setEnvVariables((oldEnv) => [...oldEnv, ["", ""]]);
+ }, [setEnvVariables]);
- const usedKeys: string[] = [];
+ const usedKeys: string[] = [];
- return (
- <div style={container}>
- <strong style={title}>Environment variables</strong>
- {envVariables.map((env, i) => {
- let isDuplicate = false;
+ return (
+ <div style={container}>
+ <strong style={title}>Environment variables</strong>
+ {envVariables.map((env, i) => {
+ let isDuplicate = false;
- if (usedKeys.includes(env[0].toUpperCase())) {
- isDuplicate = true;
- }
+ if (usedKeys.includes(env[0].toUpperCase())) {
+ isDuplicate = true;
+ }
- usedKeys.push(env[0].toUpperCase());
+ usedKeys.push(env[0].toUpperCase());
- return (
- <EnvInput
- // eslint-disable-next-line react/no-array-index-key
- key={i}
- onEnvKeyChange={onEnvKeyChange}
- onEnvValChange={onEnvValChange}
- envKey={env[0]}
- envVal={env[1]}
- onDelete={onDelete}
- index={i}
- isDuplicate={isDuplicate}
- autoFocus={i === envVariables.length - 1 && env[0] === ''}
- />
- );
- })}
- <Spacing y={1} block />
- <Button style={button} onClick={addField}>
- + Add env variable
- </Button>
- <Spacing y={1} block />
- </div>
- );
+ return (
+ <EnvInput
+ // eslint-disable-next-line react/no-array-index-key
+ key={i}
+ onEnvKeyChange={onEnvKeyChange}
+ onEnvValChange={onEnvValChange}
+ envKey={env[0]}
+ envVal={env[1]}
+ onDelete={onDelete}
+ index={i}
+ isDuplicate={isDuplicate}
+ autoFocus={i === envVariables.length - 1 && env[0] === ""}
+ />
+ );
+ })}
+ <Spacing y={1} block />
+ <Button style={button} onClick={addField}>
+ + Add env variable
+ </Button>
+ <Spacing y={1} block />
+ </div>
+ );
};
diff --git a/packages/studio/src/components/RenderQueue/RenderQueueItemStatus.tsx b/packages/studio/src/components/RenderQueue/RenderQueueItemStatus.tsx
index 1520df15ad..d4f8e36d5f 100644
--- a/packages/studio/src/components/RenderQueue/RenderQueueItemStatus.tsx
+++ b/packages/studio/src/components/RenderQueue/RenderQueueItemStatus.tsx
@@ -1,101 +1,101 @@
-import React, {useCallback, useContext} from 'react';
-import {FAIL_COLOR, LIGHT_TEXT} from '../../helpers/colors';
-import type {RenderJob} from '../../preview-server/job';
-import {ModalsContext} from '../../state/modals';
+import type { RenderJob } from "@remotion/studio-server";
+import React, { useCallback, useContext } from "react";
+import { FAIL_COLOR, LIGHT_TEXT } from "../../helpers/colors";
+import { ModalsContext } from "../../state/modals";
import {
- CircularProgress,
- RENDER_STATUS_INDICATOR_SIZE,
-} from './CircularProgress';
+ CircularProgress,
+ RENDER_STATUS_INDICATOR_SIZE,
+} from "./CircularProgress";
const iconStyle: React.CSSProperties = {
- height: RENDER_STATUS_INDICATOR_SIZE,
- width: RENDER_STATUS_INDICATOR_SIZE,
+ height: RENDER_STATUS_INDICATOR_SIZE,
+ width: RENDER_STATUS_INDICATOR_SIZE,
};
const invisibleStyle: React.CSSProperties = {
- appearance: 'none',
- border: 'none',
- padding: 0,
- cursor: 'pointer',
- display: 'flex',
+ appearance: "none",
+ border: "none",
+ padding: 0,
+ cursor: "pointer",
+ display: "flex",
};
export const RenderQueueItemStatus: React.FC<{
- job: RenderJob;
-}> = ({job}) => {
- const {setSelectedModal} = useContext(ModalsContext);
- const [hovered, setHovered] = React.useState(false);
+ job: RenderJob;
+}> = ({ job }) => {
+ const { setSelectedModal } = useContext(ModalsContext);
+ const [hovered, setHovered] = React.useState(false);
- const onPointerEnter = useCallback(() => {
- setHovered(true);
- }, []);
+ const onPointerEnter = useCallback(() => {
+ setHovered(true);
+ }, []);
- const onPointerLeave = useCallback(() => {
- setHovered(false);
- }, []);
+ const onPointerLeave = useCallback(() => {
+ setHovered(false);
+ }, []);
- const onClick: React.MouseEventHandler = useCallback(
- (e) => {
- e.stopPropagation();
- setSelectedModal({
- type: 'render-progress',
- jobId: job.id,
- });
- },
- [job.id, setSelectedModal],
- );
+ const onClick: React.MouseEventHandler = useCallback(
+ (e) => {
+ e.stopPropagation();
+ setSelectedModal({
+ type: "render-progress",
+ jobId: job.id,
+ });
+ },
+ [job.id, setSelectedModal]
+ );
- if (job.status === 'failed') {
- return (
- <div>
- <svg style={iconStyle} viewBox="0 0 512 512">
- <path
- fill={FAIL_COLOR}
- d="M0 160V352L160 512H352L512 352V160L352 0H160L0 160zm353.9 32l-17 17-47 47 47 47 17 17L320 353.9l-17-17-47-47-47 47-17 17L158.1 320l17-17 47-47-47-47-17-17L192 158.1l17 17 47 47 47-47 17-17L353.9 192z"
- />
- </svg>
- </div>
- );
- }
+ if (job.status === "failed") {
+ return (
+ <div>
+ <svg style={iconStyle} viewBox="0 0 512 512">
+ <path
+ fill={FAIL_COLOR}
+ d="M0 160V352L160 512H352L512 352V160L352 0H160L0 160zm353.9 32l-17 17-47 47 47 47 17 17L320 353.9l-17-17-47-47-47 47-17 17L158.1 320l17-17 47-47-47-47-17-17L192 158.1l17 17 47 47 47-47 17-17L353.9 192z"
+ />
+ </svg>
+ </div>
+ );
+ }
- if (job.status === 'idle') {
- return (
- <svg style={iconStyle} viewBox="0 0 512 512">
- <path
- fill={LIGHT_TEXT}
- d="M256 512C114.6 512 0 397.4 0 256S114.6 0 256 0S512 114.6 512 256s-114.6 256-256 256zM232 120V256c0 8 4 15.5 10.7 20l96 64c11 7.4 25.9 4.4 33.3-6.7s4.4-25.9-6.7-33.3L280 243.2V120c0-13.3-10.7-24-24-24s-24 10.7-24 24z"
- />
- </svg>
- );
- }
+ if (job.status === "idle") {
+ return (
+ <svg style={iconStyle} viewBox="0 0 512 512">
+ <path
+ fill={LIGHT_TEXT}
+ d="M256 512C114.6 512 0 397.4 0 256S114.6 0 256 0S512 114.6 512 256s-114.6 256-256 256zM232 120V256c0 8 4 15.5 10.7 20l96 64c11 7.4 25.9 4.4 33.3-6.7s4.4-25.9-6.7-33.3L280 243.2V120c0-13.3-10.7-24-24-24s-24 10.7-24 24z"
+ />
+ </svg>
+ );
+ }
- if (job.status === 'done') {
- return (
- <button
- type="button"
- style={invisibleStyle}
- onPointerEnter={onPointerEnter}
- onPointerLeave={onPointerLeave}
- onClick={onClick}
- >
- <svg style={iconStyle} viewBox="0 0 512 512">
- <path
- fill={hovered ? 'white' : LIGHT_TEXT}
- d="M256 512c141.4 0 256-114.6 256-256S397.4 0 256 0S0 114.6 0 256S114.6 512 256 512zM369 209L241 337l-17 17-17-17-64-64-17-17L160 222.1l17 17 47 47L335 175l17-17L385.9 192l-17 17z"
- />
- </svg>
- </button>
- );
- }
+ if (job.status === "done") {
+ return (
+ <button
+ type="button"
+ style={invisibleStyle}
+ onPointerEnter={onPointerEnter}
+ onPointerLeave={onPointerLeave}
+ onClick={onClick}
+ >
+ <svg style={iconStyle} viewBox="0 0 512 512">
+ <path
+ fill={hovered ? "white" : LIGHT_TEXT}
+ d="M256 512c141.4 0 256-114.6 256-256S397.4 0 256 0S0 114.6 0 256S114.6 512 256 512zM369 209L241 337l-17 17-17-17-64-64-17-17L160 222.1l17 17 47 47L335 175l17-17L385.9 192l-17 17z"
+ />
+ </svg>
+ </button>
+ );
+ }
- if (job.status === 'running') {
- // Add a minimum progress to avoid the progress bar from disappearing
- return (
- <button type="button" style={invisibleStyle} onClick={onClick}>
- <CircularProgress progress={Math.max(0.07, job.progress.value)} />
- </button>
- );
- }
+ if (job.status === "running") {
+ // Add a minimum progress to avoid the progress bar from disappearing
+ return (
+ <button type="button" style={invisibleStyle} onClick={onClick}>
+ <CircularProgress progress={Math.max(0.07, job.progress.value)} />
+ </button>
+ );
+ }
- throw new Error('Unknown job status');
+ throw new Error("Unknown job status");
};
diff --git a/packages/studio/src/components/RenderQueue/RenderQueueRepeat.tsx b/packages/studio/src/components/RenderQueue/RenderQueueRepeat.tsx
index 18e12e6425..d13b2f1426 100644
--- a/packages/studio/src/components/RenderQueue/RenderQueueRepeat.tsx
+++ b/packages/studio/src/components/RenderQueue/RenderQueueRepeat.tsx
@@ -1,44 +1,44 @@
-import React, {useCallback, useContext, useMemo} from 'react';
-import type {RenderJob} from '../../preview-server/job';
-import {makeRetryPayload} from '../../preview-server/retry-payload';
-import {ModalsContext} from '../../state/modals';
-import type {RenderInlineAction} from '../InlineAction';
-import {InlineAction} from '../InlineAction';
+import type { RenderJob } from "@remotion/studio-server";
+import React, { useCallback, useContext, useMemo } from "react";
+import { makeRetryPayload } from "../../helpers/retry-payload";
+import { ModalsContext } from "../../state/modals";
+import type { RenderInlineAction } from "../InlineAction";
+import { InlineAction } from "../InlineAction";
export const RenderQueueRepeatItem: React.FC<{
- job: RenderJob;
-}> = ({job}) => {
- const {setSelectedModal} = useContext(ModalsContext);
+ job: RenderJob;
+}> = ({ job }) => {
+ const { setSelectedModal } = useContext(ModalsContext);
- const onClick: React.MouseEventHandler = useCallback(
- (e) => {
- e.stopPropagation();
- const retryPayload = makeRetryPayload(job);
- setSelectedModal(retryPayload);
- },
- [job, setSelectedModal],
- );
+ const onClick: React.MouseEventHandler = useCallback(
+ (e) => {
+ e.stopPropagation();
+ const retryPayload = makeRetryPayload(job);
+ setSelectedModal(retryPayload);
+ },
+ [job, setSelectedModal]
+ );
- const icon: React.CSSProperties = useMemo(() => {
- return {
- height: 12,
- color: 'currentColor',
- };
- }, []);
+ const icon: React.CSSProperties = useMemo(() => {
+ return {
+ height: 12,
+ color: "currentColor",
+ };
+ }, []);
- const renderAction: RenderInlineAction = useCallback(
- (color) => {
- return (
- <svg style={icon} viewBox="0 0 512 512">
- <path
- fill={color}
- d="M386.3 160H336c-17.7 0-32 14.3-32 32s14.3 32 32 32H464c17.7 0 32-14.3 32-32V64c0-17.7-14.3-32-32-32s-32 14.3-32 32v51.2L414.4 97.6c-87.5-87.5-229.3-87.5-316.8 0s-87.5 229.3 0 316.8s229.3 87.5 316.8 0c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0c-62.5 62.5-163.8 62.5-226.3 0s-62.5-163.8 0-226.3s163.8-62.5 226.3 0L386.3 160z"
- />
- </svg>
- );
- },
- [icon],
- );
+ const renderAction: RenderInlineAction = useCallback(
+ (color) => {
+ return (
+ <svg style={icon} viewBox="0 0 512 512">
+ <path
+ fill={color}
+ d="M386.3 160H336c-17.7 0-32 14.3-32 32s14.3 32 32 32H464c17.7 0 32-14.3 32-32V64c0-17.7-14.3-32-32-32s-32 14.3-32 32v51.2L414.4 97.6c-87.5-87.5-229.3-87.5-316.8 0s-87.5 229.3 0 316.8s229.3 87.5 316.8 0c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0c-62.5 62.5-163.8 62.5-226.3 0s-62.5-163.8 0-226.3s163.8-62.5 226.3 0L386.3 160z"
+ />
+ </svg>
+ );
+ },
+ [icon]
+ );
- return <InlineAction onClick={onClick} renderAction={renderAction} />;
+ return <InlineAction onClick={onClick} renderAction={renderAction} />;
};
diff --git a/packages/studio/src/components/RenderQueue/actions.ts b/packages/studio/src/components/RenderQueue/actions.ts
index 6107bc6b28..8be88336cb 100644
--- a/packages/studio/src/components/RenderQueue/actions.ts
+++ b/packages/studio/src/components/RenderQueue/actions.ts
@@ -1,365 +1,362 @@
import type {
- AudioCodec,
- Codec,
- ColorSpace,
- LogLevel,
- PixelFormat,
- ProResProfile,
- StillImageFormat,
- VideoImageFormat,
- X264Preset,
-} from '@remotion/renderer';
-import {NoReactInternals} from 'remotion/no-react';
-import type {ApiRoutes} from '../../preview-server/api-types';
+ AudioCodec,
+ Codec,
+ ColorSpace,
+ LogLevel,
+ PixelFormat,
+ ProResProfile,
+ StillImageFormat,
+ VideoImageFormat,
+ X264Preset,
+} from "@remotion/renderer";
+import { NoReactInternals } from "remotion/no-react";
+import type { ApiRoutes, EnumPath, RenderJob } from "@remotion/studio-server";
+import type { RequiredChromiumOptions } from "../../required-chromium-options";
import type {
- CopyStillToClipboardRequest,
- OpenInFileExplorerRequest,
- RenderJob,
-} from '../../preview-server/job';
-import type {RequiredChromiumOptions} from '../../required-chromium-options';
-
-import type {EnumPath} from '../RenderModal/SchemaEditor/extract-enum-json-paths';
+ CopyStillToClipboardRequest,
+ OpenInFileExplorerRequest,
+} from "@remotion/studio-server";
const callApi = <Endpoint extends keyof ApiRoutes>(
- endpoint: Endpoint,
- body: ApiRoutes[Endpoint]['Request'],
- signal?: AbortSignal,
-): Promise<ApiRoutes[Endpoint]['Response']> => {
- return new Promise<ApiRoutes[Endpoint]['Response']>((resolve, reject) => {
- fetch(endpoint, {
- method: 'post',
- headers: {
- 'content-type': 'application/json',
- },
- signal,
- body: JSON.stringify(body),
- })
- .then((res) => res.json())
- .then(
- (
- data:
- | {success: true; data: ApiRoutes[Endpoint]['Response']}
- | {success: false; error: string},
- ) => {
- if (data.success) {
- resolve(data.data);
- } else {
- reject(new Error(data.error));
- }
- },
- )
- .catch((err) => {
- reject(err);
- });
- });
+ endpoint: Endpoint,
+ body: ApiRoutes[Endpoint]["Request"],
+ signal?: AbortSignal
+): Promise<ApiRoutes[Endpoint]["Response"]> => {
+ return new Promise<ApiRoutes[Endpoint]["Response"]>((resolve, reject) => {
+ fetch(endpoint, {
+ method: "post",
+ headers: {
+ "content-type": "application/json",
+ },
+ signal,
+ body: JSON.stringify(body),
+ })
+ .then((res) => res.json())
+ .then(
+ (
+ data:
+ | { success: true; data: ApiRoutes[Endpoint]["Response"] }
+ | { success: false; error: string }
+ ) => {
+ if (data.success) {
+ resolve(data.data);
+ } else {
+ reject(new Error(data.error));
+ }
+ }
+ )
+ .catch((err) => {
+ reject(err);
+ });
+ });
};
export const addStillRenderJob = ({
- compositionId,
- outName,
- imageFormat,
- jpegQuality,
- frame,
- scale,
- logLevel,
- chromiumOptions,
- delayRenderTimeout,
- envVariables,
- inputProps,
- offthreadVideoCacheSizeInBytes,
- multiProcessOnLinux,
- beepOnFinish,
+ compositionId,
+ outName,
+ imageFormat,
+ jpegQuality,
+ frame,
+ scale,
+ logLevel,
+ chromiumOptions,
+ delayRenderTimeout,
+ envVariables,
+ inputProps,
+ offthreadVideoCacheSizeInBytes,
+ multiProcessOnLinux,
+ beepOnFinish,
}: {
- compositionId: string;
- outName: string;
- imageFormat: StillImageFormat;
- jpegQuality: number;
- frame: number;
- scale: number;
- logLevel: LogLevel;
- chromiumOptions: RequiredChromiumOptions;
- delayRenderTimeout: number;
- envVariables: Record<string, string>;
- inputProps: Record<string, unknown>;
- offthreadVideoCacheSizeInBytes: number | null;
- multiProcessOnLinux: boolean;
- beepOnFinish: boolean;
+ compositionId: string;
+ outName: string;
+ imageFormat: StillImageFormat;
+ jpegQuality: number;
+ frame: number;
+ scale: number;
+ logLevel: LogLevel;
+ chromiumOptions: RequiredChromiumOptions;
+ delayRenderTimeout: number;
+ envVariables: Record<string, string>;
+ inputProps: Record<string, unknown>;
+ offthreadVideoCacheSizeInBytes: number | null;
+ multiProcessOnLinux: boolean;
+ beepOnFinish: boolean;
}) => {
- return callApi('/api/render', {
- compositionId,
- type: 'still',
- outName,
- imageFormat,
- jpegQuality,
- frame,
- scale,
- logLevel,
- chromiumOptions,
- delayRenderTimeout,
- envVariables,
- serializedInputPropsWithCustomSchema:
- NoReactInternals.serializeJSONWithDate({
- data: inputProps,
- staticBase: window.remotion_staticBase,
- indent: undefined,
- }).serializedString,
- offthreadVideoCacheSizeInBytes,
- multiProcessOnLinux,
- beepOnFinish,
- });
+ return callApi("/api/render", {
+ compositionId,
+ type: "still",
+ outName,
+ imageFormat,
+ jpegQuality,
+ frame,
+ scale,
+ logLevel,
+ chromiumOptions,
+ delayRenderTimeout,
+ envVariables,
+ serializedInputPropsWithCustomSchema:
+ NoReactInternals.serializeJSONWithDate({
+ data: inputProps,
+ staticBase: window.remotion_staticBase,
+ indent: undefined,
+ }).serializedString,
+ offthreadVideoCacheSizeInBytes,
+ multiProcessOnLinux,
+ beepOnFinish,
+ });
};
export const addSequenceRenderJob = ({
- compositionId,
- outName,
- imageFormat,
- startFrame,
- endFrame,
- scale,
- logLevel,
- chromiumOptions,
- delayRenderTimeout,
- envVariables,
- inputProps,
- concurrency,
- offthreadVideoCacheSizeInBytes,
- jpegQuality,
- disallowParallelEncoding,
- multiProcessOnLinux,
- beepOnFinish,
- repro,
+ compositionId,
+ outName,
+ imageFormat,
+ startFrame,
+ endFrame,
+ scale,
+ logLevel,
+ chromiumOptions,
+ delayRenderTimeout,
+ envVariables,
+ inputProps,
+ concurrency,
+ offthreadVideoCacheSizeInBytes,
+ jpegQuality,
+ disallowParallelEncoding,
+ multiProcessOnLinux,
+ beepOnFinish,
+ repro,
}: {
- compositionId: string;
- outName: string;
- imageFormat: VideoImageFormat;
- jpegQuality: number;
- startFrame: number;
- endFrame: number;
- scale: number;
- logLevel: LogLevel;
- chromiumOptions: RequiredChromiumOptions;
- concurrency: number;
- delayRenderTimeout: number;
- envVariables: Record<string, string>;
- inputProps: Record<string, unknown>;
- offthreadVideoCacheSizeInBytes: number | null;
- disallowParallelEncoding: boolean;
- multiProcessOnLinux: boolean;
- beepOnFinish: boolean;
- repro: boolean;
+ compositionId: string;
+ outName: string;
+ imageFormat: VideoImageFormat;
+ jpegQuality: number;
+ startFrame: number;
+ endFrame: number;
+ scale: number;
+ logLevel: LogLevel;
+ chromiumOptions: RequiredChromiumOptions;
+ concurrency: number;
+ delayRenderTimeout: number;
+ envVariables: Record<string, string>;
+ inputProps: Record<string, unknown>;
+ offthreadVideoCacheSizeInBytes: number | null;
+ disallowParallelEncoding: boolean;
+ multiProcessOnLinux: boolean;
+ beepOnFinish: boolean;
+ repro: boolean;
}) => {
- return callApi('/api/render', {
- compositionId,
- type: 'sequence',
- outName,
- imageFormat,
- jpegQuality,
- scale,
- startFrame,
- endFrame,
- logLevel,
- chromiumOptions,
- delayRenderTimeout,
- envVariables,
- concurrency,
- serializedInputPropsWithCustomSchema:
- NoReactInternals.serializeJSONWithDate({
- data: inputProps,
- staticBase: window.remotion_staticBase,
- indent: undefined,
- }).serializedString,
- offthreadVideoCacheSizeInBytes,
- disallowParallelEncoding,
- multiProcessOnLinux,
- beepOnFinish,
- repro,
- });
+ return callApi("/api/render", {
+ compositionId,
+ type: "sequence",
+ outName,
+ imageFormat,
+ jpegQuality,
+ scale,
+ startFrame,
+ endFrame,
+ logLevel,
+ chromiumOptions,
+ delayRenderTimeout,
+ envVariables,
+ concurrency,
+ serializedInputPropsWithCustomSchema:
+ NoReactInternals.serializeJSONWithDate({
+ data: inputProps,
+ staticBase: window.remotion_staticBase,
+ indent: undefined,
+ }).serializedString,
+ offthreadVideoCacheSizeInBytes,
+ disallowParallelEncoding,
+ multiProcessOnLinux,
+ beepOnFinish,
+ repro,
+ });
};
export const addVideoRenderJob = ({
- compositionId,
- outName,
- imageFormat,
- jpegQuality,
- scale,
- logLevel,
- codec,
- concurrency,
- crf,
- startFrame,
- endFrame,
- muted,
- enforceAudioTrack,
- proResProfile,
- x264Preset,
- pixelFormat,
- audioBitrate,
- videoBitrate,
- everyNthFrame,
- numberOfGifLoops,
- delayRenderTimeout,
- audioCodec,
- disallowParallelEncoding,
- chromiumOptions,
- envVariables,
- inputProps,
- offthreadVideoCacheSizeInBytes,
- colorSpace,
- multiProcessOnLinux,
- encodingMaxRate,
- encodingBufferSize,
- beepOnFinish,
- repro,
+ compositionId,
+ outName,
+ imageFormat,
+ jpegQuality,
+ scale,
+ logLevel,
+ codec,
+ concurrency,
+ crf,
+ startFrame,
+ endFrame,
+ muted,
+ enforceAudioTrack,
+ proResProfile,
+ x264Preset,
+ pixelFormat,
+ audioBitrate,
+ videoBitrate,
+ everyNthFrame,
+ numberOfGifLoops,
+ delayRenderTimeout,
+ audioCodec,
+ disallowParallelEncoding,
+ chromiumOptions,
+ envVariables,
+ inputProps,
+ offthreadVideoCacheSizeInBytes,
+ colorSpace,
+ multiProcessOnLinux,
+ encodingMaxRate,
+ encodingBufferSize,
+ beepOnFinish,
+ repro,
}: {
- compositionId: string;
- outName: string;
- imageFormat: VideoImageFormat;
- jpegQuality: number | null;
- scale: number;
- logLevel: LogLevel;
- codec: Codec;
- concurrency: number;
- crf: number | null;
- startFrame: number;
- endFrame: number;
- muted: boolean;
- enforceAudioTrack: boolean;
- proResProfile: ProResProfile | null;
- x264Preset: X264Preset | null;
- pixelFormat: PixelFormat;
- audioBitrate: string | null;
- videoBitrate: string | null;
- everyNthFrame: number;
- numberOfGifLoops: number | null;
- delayRenderTimeout: number;
- audioCodec: AudioCodec;
- disallowParallelEncoding: boolean;
- chromiumOptions: RequiredChromiumOptions;
- envVariables: Record<string, string>;
- inputProps: Record<string, unknown>;
- offthreadVideoCacheSizeInBytes: number | null;
- colorSpace: ColorSpace;
- multiProcessOnLinux: boolean;
- encodingMaxRate: string | null;
- encodingBufferSize: string | null;
- beepOnFinish: boolean;
- repro: boolean;
+ compositionId: string;
+ outName: string;
+ imageFormat: VideoImageFormat;
+ jpegQuality: number | null;
+ scale: number;
+ logLevel: LogLevel;
+ codec: Codec;
+ concurrency: number;
+ crf: number | null;
+ startFrame: number;
+ endFrame: number;
+ muted: boolean;
+ enforceAudioTrack: boolean;
+ proResProfile: ProResProfile | null;
+ x264Preset: X264Preset | null;
+ pixelFormat: PixelFormat;
+ audioBitrate: string | null;
+ videoBitrate: string | null;
+ everyNthFrame: number;
+ numberOfGifLoops: number | null;
+ delayRenderTimeout: number;
+ audioCodec: AudioCodec;
+ disallowParallelEncoding: boolean;
+ chromiumOptions: RequiredChromiumOptions;
+ envVariables: Record<string, string>;
+ inputProps: Record<string, unknown>;
+ offthreadVideoCacheSizeInBytes: number | null;
+ colorSpace: ColorSpace;
+ multiProcessOnLinux: boolean;
+ encodingMaxRate: string | null;
+ encodingBufferSize: string | null;
+ beepOnFinish: boolean;
+ repro: boolean;
}) => {
- return callApi('/api/render', {
- compositionId,
- type: 'video',
- outName,
- imageFormat,
- jpegQuality,
- scale,
- logLevel,
- codec,
- concurrency,
- crf,
- endFrame,
- startFrame,
- muted,
- enforceAudioTrack,
- proResProfile,
- x264Preset,
- pixelFormat,
- audioBitrate,
- videoBitrate,
- everyNthFrame,
- numberOfGifLoops,
- delayRenderTimeout,
- audioCodec,
- disallowParallelEncoding,
- chromiumOptions,
- envVariables,
- serializedInputPropsWithCustomSchema:
- NoReactInternals.serializeJSONWithDate({
- data: inputProps,
- staticBase: window.remotion_staticBase,
- indent: undefined,
- }).serializedString,
- offthreadVideoCacheSizeInBytes,
- colorSpace,
- multiProcessOnLinux,
- encodingBufferSize,
- encodingMaxRate,
- beepOnFinish,
- repro,
- });
+ return callApi("/api/render", {
+ compositionId,
+ type: "video",
+ outName,
+ imageFormat,
+ jpegQuality,
+ scale,
+ logLevel,
+ codec,
+ concurrency,
+ crf,
+ endFrame,
+ startFrame,
+ muted,
+ enforceAudioTrack,
+ proResProfile,
+ x264Preset,
+ pixelFormat,
+ audioBitrate,
+ videoBitrate,
+ everyNthFrame,
+ numberOfGifLoops,
+ delayRenderTimeout,
+ audioCodec,
+ disallowParallelEncoding,
+ chromiumOptions,
+ envVariables,
+ serializedInputPropsWithCustomSchema:
+ NoReactInternals.serializeJSONWithDate({
+ data: inputProps,
+ staticBase: window.remotion_staticBase,
+ indent: undefined,
+ }).serializedString,
+ offthreadVideoCacheSizeInBytes,
+ colorSpace,
+ multiProcessOnLinux,
+ encodingBufferSize,
+ encodingMaxRate,
+ beepOnFinish,
+ repro,
+ });
};
export const unsubscribeFromFileExistenceWatcher = ({
- file,
- clientId,
+ file,
+ clientId,
}: {
- file: string;
- clientId: string;
+ file: string;
+ clientId: string;
}) => {
- return callApi('/api/unsubscribe-from-file-existence', {file, clientId});
+ return callApi("/api/unsubscribe-from-file-existence", { file, clientId });
};
export const subscribeToFileExistenceWatcher = async ({
- file,
- clientId,
+ file,
+ clientId,
}: {
- file: string;
- clientId: string;
+ file: string;
+ clientId: string;
}): Promise<boolean> => {
- const {exists} = await callApi('/api/subscribe-to-file-existence', {
- file,
- clientId,
- });
- return exists;
+ const { exists } = await callApi("/api/subscribe-to-file-existence", {
+ file,
+ clientId,
+ });
+ return exists;
};
-export const openInFileExplorer = ({directory}: {directory: string}) => {
- const body: OpenInFileExplorerRequest = {
- directory,
- };
- return callApi('/api/open-in-file-explorer', body);
+export const openInFileExplorer = ({ directory }: { directory: string }) => {
+ const body: OpenInFileExplorerRequest = {
+ directory,
+ };
+ return callApi("/api/open-in-file-explorer", body);
};
-export const copyToClipboard = ({outName}: {outName: string}) => {
- const body: CopyStillToClipboardRequest = {
- outName,
- };
- return callApi('/api/copy-still-to-clipboard', body);
+export const copyToClipboard = ({ outName }: { outName: string }) => {
+ const body: CopyStillToClipboardRequest = {
+ outName,
+ };
+ return callApi("/api/copy-still-to-clipboard", body);
};
export const removeRenderJob = (job: RenderJob) => {
- return callApi('/api/remove-render', {
- jobId: job.id,
- });
+ return callApi("/api/remove-render", {
+ jobId: job.id,
+ });
};
export const cancelRenderJob = (job: RenderJob) => {
- return callApi('/api/cancel', {
- jobId: job.id,
- });
+ return callApi("/api/cancel", {
+ jobId: job.id,
+ });
};
export const updateAvailable = (signal: AbortSignal) => {
- return callApi('/api/update-available', {}, signal);
+ return callApi("/api/update-available", {}, signal);
};
export const updateDefaultProps = (
- compositionId: string,
- defaultProps: Record<string, unknown>,
- enumPaths: EnumPath[],
+ compositionId: string,
+ defaultProps: Record<string, unknown>,
+ enumPaths: EnumPath[]
) => {
- return callApi('/api/update-default-props', {
- compositionId,
- defaultProps: NoReactInternals.serializeJSONWithDate({
- data: defaultProps,
- indent: undefined,
- staticBase: window.remotion_staticBase,
- }).serializedString,
- enumPaths,
- });
+ return callApi("/api/update-default-props", {
+ compositionId,
+ defaultProps: NoReactInternals.serializeJSONWithDate({
+ data: defaultProps,
+ indent: undefined,
+ staticBase: window.remotion_staticBase,
+ }).serializedString,
+ enumPaths,
+ });
};
export const canUpdateDefaultProps = (compositionId: string) => {
- return callApi('/api/can-update-default-props', {
- compositionId,
- });
+ return callApi("/api/can-update-default-props", {
+ compositionId,
+ });
};
diff --git a/packages/studio/src/components/Timeline/TimelineStack/index.tsx b/packages/studio/src/components/Timeline/TimelineStack/index.tsx
index ae0313af4e..4b2e666dd1 100644
--- a/packages/studio/src/components/Timeline/TimelineStack/index.tsx
+++ b/packages/studio/src/components/Timeline/TimelineStack/index.tsx
@@ -1,211 +1,211 @@
-import React, {useCallback, useEffect, useMemo, useState} from 'react';
-import type {TSequence} from 'remotion';
-import {SourceMapConsumer} from 'source-map';
-import type {OriginalPosition} from '../../../error-overlay/react-overlay/utils/get-source-map';
-import {SOURCE_MAP_ENDPOINT} from '../../../error-overlay/react-overlay/utils/source-map-endpoint';
+import React, { useCallback, useEffect, useMemo, useState } from "react";
+import type { TSequence } from "remotion";
+import { SourceMapConsumer } from "source-map";
+import type { OriginalPosition } from "../../../error-overlay/react-overlay/utils/get-source-map";
+import { SOURCE_MAP_ENDPOINT } from "@remotion/studio-server/src/source-map-endpoint";
import {
- LIGHT_COLOR,
- LIGHT_TEXT,
- VERY_LIGHT_TEXT,
-} from '../../../helpers/colors';
-import {openInEditor} from '../../../helpers/open-in-editor';
-import {useSelectAsset} from '../../InitialCompositionLoader';
-import {Spacing} from '../../layout';
-import {sendErrorNotification} from '../../Notifications/NotificationCenter';
-import {Spinner} from '../../Spinner';
-import {getOriginalLocationFromStack} from './get-stack';
-import {getOriginalSourceAttribution} from './source-attribution';
+ LIGHT_COLOR,
+ LIGHT_TEXT,
+ VERY_LIGHT_TEXT,
+} from "../../../helpers/colors";
+import { openInEditor } from "../../../helpers/open-in-editor";
+import { useSelectAsset } from "../../InitialCompositionLoader";
+import { Spacing } from "../../layout";
+import { sendErrorNotification } from "../../Notifications/NotificationCenter";
+import { Spinner } from "../../Spinner";
+import { getOriginalLocationFromStack } from "./get-stack";
+import { getOriginalSourceAttribution } from "./source-attribution";
// @ts-expect-error
SourceMapConsumer.initialize({
- 'lib/mappings.wasm': SOURCE_MAP_ENDPOINT,
+ "lib/mappings.wasm": SOURCE_MAP_ENDPOINT,
});
export const TimelineStack: React.FC<{
- isCompact: boolean;
- sequence: TSequence;
-}> = ({isCompact, sequence}) => {
- const [originalLocation, setOriginalLocation] =
- useState<OriginalPosition | null>(null);
-
- const [stackHovered, setStackHovered] = useState(false);
- const [titleHovered, setTitleHovered] = useState(false);
- const [opening, setOpening] = useState(false);
- const selectAsset = useSelectAsset();
-
- const assetPath = useMemo(() => {
- if (sequence.type !== 'video' && sequence.type !== 'audio') {
- return null;
- }
-
- const isStatic = sequence.src.startsWith(window.remotion_staticBase);
- if (!isStatic) {
- return null;
- }
-
- const relativePath = sequence.src.replace(
- window.remotion_staticBase + '/',
- '',
- );
- return relativePath;
- }, [sequence]);
-
- const navigateToAsset = useCallback(
- (asset: string) => {
- selectAsset(asset);
- window.history.pushState({}, 'Studio', `/assets/${asset}`);
- },
- [selectAsset],
- );
-
- const openEditor = useCallback(async (location: OriginalPosition) => {
- if (!window.remotion_editorName) {
- return;
- }
-
- setOpening(true);
- try {
- await openInEditor({
- originalColumnNumber: location.column,
- originalFileName: location.source,
- originalFunctionName: null,
- originalLineNumber: location.line,
- originalScriptCode: null,
- });
- } catch (err) {
- sendErrorNotification((err as Error).message);
- } finally {
- setOpening(false);
- }
- }, []);
-
- const onClickTitle = useCallback(() => {
- if (assetPath) {
- navigateToAsset(assetPath);
- return;
- }
-
- if (!originalLocation) {
- return;
- }
-
- openEditor(originalLocation);
- }, [assetPath, navigateToAsset, openEditor, originalLocation]);
-
- const onClickStack = useCallback(() => {
- if (!originalLocation) {
- return;
- }
-
- openEditor(originalLocation);
- }, [openEditor, originalLocation]);
-
- useEffect(() => {
- if (!sequence.stack) {
- return;
- }
-
- getOriginalLocationFromStack(sequence.stack)
- .then((frame) => {
- setOriginalLocation(frame);
- })
- .catch((err) => {
- // eslint-disable-next-line no-console
- console.error('Could not get original location of Sequence', err);
- });
- }, [sequence.stack]);
-
- const onStackPointerEnter = useCallback(() => {
- setStackHovered(true);
- }, []);
-
- const onStackPointerLeave = useCallback(() => {
- setStackHovered(false);
- }, []);
-
- const onTitlePointerEnter = useCallback(() => {
- setTitleHovered(true);
- }, []);
-
- const onTitlePointerLeave = useCallback(() => {
- setTitleHovered(false);
- }, []);
-
- const style = useMemo((): React.CSSProperties => {
- return {
- fontSize: 12,
- color: opening
- ? VERY_LIGHT_TEXT
- : stackHovered
- ? LIGHT_TEXT
- : VERY_LIGHT_TEXT,
- marginLeft: 10,
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'row',
- alignItems: 'center',
- whiteSpace: 'nowrap',
- textOverflow: 'ellipsis',
- overflow: 'hidden',
- flexShrink: 100000,
- };
- }, [stackHovered, opening]);
-
- const hoverable =
- (originalLocation && isCompact) ||
- (assetPath && window.remotion_editorName);
-
- const textStyle: React.CSSProperties = useMemo(() => {
- const hoverEffect = titleHovered && hoverable;
- return {
- fontSize: 12,
- whiteSpace: 'nowrap',
- textOverflow: 'ellipsis',
- overflow: 'hidden',
- lineHeight: 1,
- color: opening && isCompact ? VERY_LIGHT_TEXT : LIGHT_COLOR,
- userSelect: 'none',
- borderBottom: hoverEffect ? '1px solid #fff' : 'none',
- cursor: hoverEffect ? 'pointer' : undefined,
- };
- }, [hoverable, isCompact, opening, titleHovered]);
-
- const text =
- sequence.displayName.length > 1000
- ? sequence.displayName.slice(0, 1000) + '...'
- : sequence.displayName;
-
- return (
- <>
- <div
- onPointerEnter={onTitlePointerEnter}
- onPointerLeave={onTitlePointerLeave}
- title={
- originalLocation
- ? getOriginalSourceAttribution(originalLocation)
- : text || '<Sequence>'
- }
- style={textStyle}
- onClick={onClickTitle}
- >
- {text || '<Sequence>'}
- </div>
- {isCompact || !originalLocation ? null : (
- <div
- onPointerEnter={onStackPointerEnter}
- onPointerLeave={onStackPointerLeave}
- onClick={onClickStack}
- style={style}
- >
- {getOriginalSourceAttribution(originalLocation)}
- </div>
- )}
- {opening ? (
- <>
- <Spacing x={0.5} />
- <Spinner duration={0.5} size={12} />
- </>
- ) : null}
- </>
- );
+ isCompact: boolean;
+ sequence: TSequence;
+}> = ({ isCompact, sequence }) => {
+ const [originalLocation, setOriginalLocation] =
+ useState<OriginalPosition | null>(null);
+
+ const [stackHovered, setStackHovered] = useState(false);
+ const [titleHovered, setTitleHovered] = useState(false);
+ const [opening, setOpening] = useState(false);
+ const selectAsset = useSelectAsset();
+
+ const assetPath = useMemo(() => {
+ if (sequence.type !== "video" && sequence.type !== "audio") {
+ return null;
+ }
+
+ const isStatic = sequence.src.startsWith(window.remotion_staticBase);
+ if (!isStatic) {
+ return null;
+ }
+
+ const relativePath = sequence.src.replace(
+ window.remotion_staticBase + "/",
+ ""
+ );
+ return relativePath;
+ }, [sequence]);
+
+ const navigateToAsset = useCallback(
+ (asset: string) => {
+ selectAsset(asset);
+ window.history.pushState({}, "Studio", `/assets/${asset}`);
+ },
+ [selectAsset]
+ );
+
+ const openEditor = useCallback(async (location: OriginalPosition) => {
+ if (!window.remotion_editorName) {
+ return;
+ }
+
+ setOpening(true);
+ try {
+ await openInEditor({
+ originalColumnNumber: location.column,
+ originalFileName: location.source,
+ originalFunctionName: null,
+ originalLineNumber: location.line,
+ originalScriptCode: null,
+ });
+ } catch (err) {
+ sendErrorNotification((err as Error).message);
+ } finally {
+ setOpening(false);
+ }
+ }, []);
+
+ const onClickTitle = useCallback(() => {
+ if (assetPath) {
+ navigateToAsset(assetPath);
+ return;
+ }
+
+ if (!originalLocation) {
+ return;
+ }
+
+ openEditor(originalLocation);
+ }, [assetPath, navigateToAsset, openEditor, originalLocation]);
+
+ const onClickStack = useCallback(() => {
+ if (!originalLocation) {
+ return;
+ }
+
+ openEditor(originalLocation);
+ }, [openEditor, originalLocation]);
+
+ useEffect(() => {
+ if (!sequence.stack) {
+ return;
+ }
+
+ getOriginalLocationFromStack(sequence.stack)
+ .then((frame) => {
+ setOriginalLocation(frame);
+ })
+ .catch((err) => {
+ // eslint-disable-next-line no-console
+ console.error("Could not get original location of Sequence", err);
+ });
+ }, [sequence.stack]);
+
+ const onStackPointerEnter = useCallback(() => {
+ setStackHovered(true);
+ }, []);
+
+ const onStackPointerLeave = useCallback(() => {
+ setStackHovered(false);
+ }, []);
+
+ const onTitlePointerEnter = useCallback(() => {
+ setTitleHovered(true);
+ }, []);
+
+ const onTitlePointerLeave = useCallback(() => {
+ setTitleHovered(false);
+ }, []);
+
+ const style = useMemo((): React.CSSProperties => {
+ return {
+ fontSize: 12,
+ color: opening
+ ? VERY_LIGHT_TEXT
+ : stackHovered
+ ? LIGHT_TEXT
+ : VERY_LIGHT_TEXT,
+ marginLeft: 10,
+ cursor: "pointer",
+ display: "flex",
+ flexDirection: "row",
+ alignItems: "center",
+ whiteSpace: "nowrap",
+ textOverflow: "ellipsis",
+ overflow: "hidden",
+ flexShrink: 100000,
+ };
+ }, [stackHovered, opening]);
+
+ const hoverable =
+ (originalLocation && isCompact) ||
+ (assetPath && window.remotion_editorName);
+
+ const textStyle: React.CSSProperties = useMemo(() => {
+ const hoverEffect = titleHovered && hoverable;
+ return {
+ fontSize: 12,
+ whiteSpace: "nowrap",
+ textOverflow: "ellipsis",
+ overflow: "hidden",
+ lineHeight: 1,
+ color: opening && isCompact ? VERY_LIGHT_TEXT : LIGHT_COLOR,
+ userSelect: "none",
+ borderBottom: hoverEffect ? "1px solid #fff" : "none",
+ cursor: hoverEffect ? "pointer" : undefined,
+ };
+ }, [hoverable, isCompact, opening, titleHovered]);
+
+ const text =
+ sequence.displayName.length > 1000
+ ? sequence.displayName.slice(0, 1000) + "..."
+ : sequence.displayName;
+
+ return (
+ <>
+ <div
+ onPointerEnter={onTitlePointerEnter}
+ onPointerLeave={onTitlePointerLeave}
+ title={
+ originalLocation
+ ? getOriginalSourceAttribution(originalLocation)
+ : text || "<Sequence>"
+ }
+ style={textStyle}
+ onClick={onClickTitle}
+ >
+ {text || "<Sequence>"}
+ </div>
+ {isCompact || !originalLocation ? null : (
+ <div
+ onPointerEnter={onStackPointerEnter}
+ onPointerLeave={onStackPointerLeave}
+ onClick={onClickStack}
+ style={style}
+ >
+ {getOriginalSourceAttribution(originalLocation)}
+ </div>
+ )}
+ {opening ? (
+ <>
+ <Spacing x={0.5} />
+ <Spinner duration={0.5} size={12} />
+ </>
+ ) : null}
+ </>
+ );
};
diff --git a/packages/studio/src/components/UpdateCheck.tsx b/packages/studio/src/components/UpdateCheck.tsx
index 3551771726..45b5fcd9d0 100644
--- a/packages/studio/src/components/UpdateCheck.tsx
+++ b/packages/studio/src/components/UpdateCheck.tsx
@@ -1,154 +1,154 @@
import React, {
- useCallback,
- useContext,
- useEffect,
- useMemo,
- useState,
-} from 'react';
-import {VERSION} from 'remotion';
-import {BLUE, LIGHT_TEXT, WARNING_COLOR} from '../helpers/colors';
-import type {PackageManager} from '../preview-server/get-package-manager';
-import {ModalsContext} from '../state/modals';
-import {useZIndex} from '../state/z-index';
-import {updateAvailable} from './RenderQueue/actions';
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import { VERSION } from "remotion";
+import { BLUE, LIGHT_TEXT, WARNING_COLOR } from "../helpers/colors";
+import { ModalsContext } from "../state/modals";
+import { useZIndex } from "../state/z-index";
+import { updateAvailable } from "./RenderQueue/actions";
+import type { PackageManager } from "@remotion/studio-server";
export type UpdateInfo = {
- currentVersion: string;
- latestVersion: string;
- updateAvailable: boolean;
- timedOut: boolean;
- packageManager: PackageManager | 'unknown';
+ currentVersion: string;
+ latestVersion: string;
+ updateAvailable: boolean;
+ timedOut: boolean;
+ packageManager: PackageManager | "unknown";
};
const buttonStyle: React.CSSProperties = {
- appearance: 'none',
- color: BLUE,
- border: 'none',
- fontWeight: 'bold',
- backgroundColor: 'transparent',
- cursor: 'pointer',
- fontSize: 14,
- display: 'inline-flex',
- justifyContent: 'center',
+ appearance: "none",
+ color: BLUE,
+ border: "none",
+ fontWeight: "bold",
+ backgroundColor: "transparent",
+ cursor: "pointer",
+ fontSize: 14,
+ display: "inline-flex",
+ justifyContent: "center",
};
// Keep in sync with packages/bugs/api/[v].ts
export type Bug = {
- title: string;
- description: string;
- link: string;
- versions: string[];
+ title: string;
+ description: string;
+ link: string;
+ versions: string[];
};
export const UpdateCheck = () => {
- const [info, setInfo] = useState<UpdateInfo | null>(null);
- const {setSelectedModal} = useContext(ModalsContext);
- const {tabIndex} = useZIndex();
- const [knownBugs, setKnownBugs] = useState<Bug[] | null>(null);
-
- const hasKnownBugs = useMemo(() => {
- return knownBugs && knownBugs.length > 0;
- }, [knownBugs]);
-
- const checkForUpdates = useCallback(() => {
- const controller = new AbortController();
-
- updateAvailable(controller.signal)
- .then((d) => {
- setInfo(d);
- })
- .catch((err: Error) => {
- if (err.message.includes('aborted')) {
- return;
- }
-
- // eslint-disable-next-line no-console
- console.log('Could not check for updates', err);
- });
-
- return controller;
- }, []);
-
- const checkForBugs = useCallback(() => {
- const controller = new AbortController();
-
- fetch(`https://bugs.remotion.dev/api/${VERSION}`, {
- signal: controller.signal,
- })
- .then(async (res) => {
- const body = await res.json();
- setKnownBugs(body.bugs);
- })
- .catch((err: Error) => {
- if (err.message.includes('aborted')) {
- return;
- }
-
- // eslint-disable-next-line no-console
- console.log('Could not check for bugs in this version', err);
- });
-
- return controller;
- }, []);
-
- useEffect(() => {
- const abortUpdate = checkForUpdates();
- const abortBugs = checkForBugs();
-
- return () => {
- abortUpdate.abort();
- abortBugs.abort();
- };
- }, [checkForBugs, checkForUpdates]);
-
- const openModal = useCallback(() => {
- setSelectedModal({
- type: 'update',
- info: info as UpdateInfo,
- knownBugs: knownBugs as Bug[],
- });
- }, [info, knownBugs, setSelectedModal]);
-
- const dynButtonStyle: React.CSSProperties = useMemo(() => {
- return {
- ...buttonStyle,
- color: hasKnownBugs ? WARNING_COLOR : LIGHT_TEXT,
- };
- }, [hasKnownBugs]);
-
- if (!info) {
- return null;
- }
-
- if (!info.updateAvailable) {
- return null;
- }
-
- return (
- <button
- tabIndex={tabIndex}
- style={dynButtonStyle}
- onClick={openModal}
- type="button"
- title={hasKnownBugs ? 'Bugfixes available' : 'Update available'}
- >
- {hasKnownBugs ? (
- 'Bugfixes available'
- ) : (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- style={{
- height: 16,
- width: 16,
- }}
- viewBox="0 0 512 512"
- >
- <path
- fill="currentcolor"
- d="M256 48a208 208 0 1 1 0 416 208 208 0 1 1 0-416zm0 464A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM135.1 217.4c-4.5 4.2-7.1 10.1-7.1 16.3c0 12.3 10 22.3 22.3 22.3H208v96c0 17.7 14.3 32 32 32h32c17.7 0 32-14.3 32-32V256h57.7c12.3 0 22.3-10 22.3-22.3c0-6.2-2.6-12.1-7.1-16.3L269.8 117.5c-3.8-3.5-8.7-5.5-13.8-5.5s-10.1 2-13.8 5.5L135.1 217.4z"
- />
- </svg>
- )}
- </button>
- );
+ const [info, setInfo] = useState<UpdateInfo | null>(null);
+ const { setSelectedModal } = useContext(ModalsContext);
+ const { tabIndex } = useZIndex();
+ const [knownBugs, setKnownBugs] = useState<Bug[] | null>(null);
+
+ const hasKnownBugs = useMemo(() => {
+ return knownBugs && knownBugs.length > 0;
+ }, [knownBugs]);
+
+ const checkForUpdates = useCallback(() => {
+ const controller = new AbortController();
+
+ updateAvailable(controller.signal)
+ .then((d) => {
+ setInfo(d);
+ })
+ .catch((err: Error) => {
+ if (err.message.includes("aborted")) {
+ return;
+ }
+
+ // eslint-disable-next-line no-console
+ console.log("Could not check for updates", err);
+ });
+
+ return controller;
+ }, []);
+
+ const checkForBugs = useCallback(() => {
+ const controller = new AbortController();
+
+ fetch(`https://bugs.remotion.dev/api/${VERSION}`, {
+ signal: controller.signal,
+ })
+ .then(async (res) => {
+ const body = await res.json();
+ setKnownBugs(body.bugs);
+ })
+ .catch((err: Error) => {
+ if (err.message.includes("aborted")) {
+ return;
+ }
+
+ // eslint-disable-next-line no-console
+ console.log("Could not check for bugs in this version", err);
+ });
+
+ return controller;
+ }, []);
+
+ useEffect(() => {
+ const abortUpdate = checkForUpdates();
+ const abortBugs = checkForBugs();
+
+ return () => {
+ abortUpdate.abort();
+ abortBugs.abort();
+ };
+ }, [checkForBugs, checkForUpdates]);
+
+ const openModal = useCallback(() => {
+ setSelectedModal({
+ type: "update",
+ info: info as UpdateInfo,
+ knownBugs: knownBugs as Bug[],
+ });
+ }, [info, knownBugs, setSelectedModal]);
+
+ const dynButtonStyle: React.CSSProperties = useMemo(() => {
+ return {
+ ...buttonStyle,
+ color: hasKnownBugs ? WARNING_COLOR : LIGHT_TEXT,
+ };
+ }, [hasKnownBugs]);
+
+ if (!info) {
+ return null;
+ }
+
+ if (!info.updateAvailable) {
+ return null;
+ }
+
+ return (
+ <button
+ tabIndex={tabIndex}
+ style={dynButtonStyle}
+ onClick={openModal}
+ type="button"
+ title={hasKnownBugs ? "Bugfixes available" : "Update available"}
+ >
+ {hasKnownBugs ? (
+ "Bugfixes available"
+ ) : (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ style={{
+ height: 16,
+ width: 16,
+ }}
+ viewBox="0 0 512 512"
+ >
+ <path
+ fill="currentcolor"
+ d="M256 48a208 208 0 1 1 0 416 208 208 0 1 1 0-416zm0 464A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM135.1 217.4c-4.5 4.2-7.1 10.1-7.1 16.3c0 12.3 10 22.3 22.3 22.3H208v96c0 17.7 14.3 32 32 32h32c17.7 0 32-14.3 32-32V256h57.7c12.3 0 22.3-10 22.3-22.3c0-6.2-2.6-12.1-7.1-16.3L269.8 117.5c-3.8-3.5-8.7-5.5-13.8-5.5s-10.1 2-13.8 5.5L135.1 217.4z"
+ />
+ </svg>
+ )}
+ </button>
+ );
};
diff --git a/packages/studio/src/error-overlay/react-overlay/effects/resolve-file-source.ts b/packages/studio/src/error-overlay/react-overlay/effects/resolve-file-source.ts
index 62dd20fe9d..6952a89c0b 100644
--- a/packages/studio/src/error-overlay/react-overlay/effects/resolve-file-source.ts
+++ b/packages/studio/src/error-overlay/react-overlay/effects/resolve-file-source.ts
@@ -1,40 +1,40 @@
-import type {SymbolicatedStackFrame} from '../utils/stack-frame';
-import type {ErrorLocation} from './map-error-to-react-stack';
+import type { SymbolicatedStackFrame } from "@remotion/studio-server/src/stack-frame";
+import type { ErrorLocation } from "@remotion/studio-server/src/helpers/map-error-to-react-stack";
export const resolveFileSource = async (
- location: ErrorLocation,
- contextLines: number,
+ location: ErrorLocation,
+ contextLines: number
): Promise<SymbolicatedStackFrame> => {
- const res = await fetch(
- `/api/file-source?f=${encodeURIComponent(location.fileName)}`,
- );
- const text = await res.text();
+ const res = await fetch(
+ `/api/file-source?f=${encodeURIComponent(location.fileName)}`
+ );
+ const text = await res.text();
- const lines = text
- .split('\n')
- .map((l, i) => {
- const oneIndexedLineNumber = i + 1;
- return [oneIndexedLineNumber, l] as [number, string];
- })
- .filter(([oneIndexedLineNumber]) => {
- return (
- Math.abs(oneIndexedLineNumber - location.lineNumber) <= contextLines
- );
- });
+ const lines = text
+ .split("\n")
+ .map((l, i) => {
+ const oneIndexedLineNumber = i + 1;
+ return [oneIndexedLineNumber, l] as [number, string];
+ })
+ .filter(([oneIndexedLineNumber]) => {
+ return (
+ Math.abs(oneIndexedLineNumber - location.lineNumber) <= contextLines
+ );
+ });
- const scriptCode = lines.map(([num, line]) => {
- return {
- content: line,
- highlight: location.lineNumber === num,
- lineNumber: num,
- };
- });
+ const scriptCode = lines.map(([num, line]) => {
+ return {
+ content: line,
+ highlight: location.lineNumber === num,
+ lineNumber: num,
+ };
+ });
- return {
- originalColumnNumber: location.columnNumber,
- originalFunctionName: null,
- originalFileName: location.fileName,
- originalLineNumber: location.lineNumber,
- originalScriptCode: scriptCode,
- };
+ return {
+ originalColumnNumber: location.columnNumber,
+ originalFunctionName: null,
+ originalFileName: location.fileName,
+ originalLineNumber: location.lineNumber,
+ originalScriptCode: scriptCode,
+ };
};
diff --git a/packages/studio/src/error-overlay/react-overlay/listen-to-runtime-errors.ts b/packages/studio/src/error-overlay/react-overlay/listen-to-runtime-errors.ts
index ee3957cec9..1b1f7abaef 100644
--- a/packages/studio/src/error-overlay/react-overlay/listen-to-runtime-errors.ts
+++ b/packages/studio/src/error-overlay/react-overlay/listen-to-runtime-errors.ts
@@ -1,14 +1,14 @@
-import {setErrorsRef} from '../remotion-overlay/Overlay';
-import {massageWarning} from './effects/format-warning';
+import { setErrorsRef } from "../remotion-overlay/Overlay";
+import { massageWarning } from "./effects/format-warning";
import {
- permanentRegister as permanentRegisterConsole,
- registerReactStack,
- unregisterReactStack,
-} from './effects/proxy-console';
+ permanentRegister as permanentRegisterConsole,
+ registerReactStack,
+ unregisterReactStack,
+} from "./effects/proxy-console";
import {
- register as registerStackTraceLimit,
- unregister as unregisterStackTraceLimit,
-} from './effects/stack-trace-limit';
+ register as registerStackTraceLimit,
+ unregister as unregisterStackTraceLimit,
+} from "./effects/stack-trace-limit";
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
@@ -16,108 +16,108 @@ import {
* LICENSE file in the root directory of this source tree.
*/
import {
- register as registerError,
- unregister as unregisterError,
-} from './effects/unhandled-error';
+ register as registerError,
+ unregister as unregisterError,
+} from "./effects/unhandled-error";
import {
- register as registerPromise,
- unregister as unregisterPromise,
-} from './effects/unhandled-rejection';
-import {getStackFrames} from './utils/get-stack-frames';
-import type {SymbolicatedStackFrame} from './utils/stack-frame';
+ register as registerPromise,
+ unregister as unregisterPromise,
+} from "./effects/unhandled-rejection";
+import { getStackFrames } from "./utils/get-stack-frames";
+import type { SymbolicatedStackFrame } from "@remotion/studio-server/src/stack-frame";
export type ErrorRecord = {
- error: Error;
- contextSize: number;
- stackFrames: SymbolicatedStackFrame[];
+ error: Error;
+ contextSize: number;
+ stackFrames: SymbolicatedStackFrame[];
};
const CONTEXT_SIZE = 3;
export const getErrorRecord = async (
- error: Error,
+ error: Error
): Promise<ErrorRecord | null> => {
- const stackFrames = await getStackFrames(error, CONTEXT_SIZE);
+ const stackFrames = await getStackFrames(error, CONTEXT_SIZE);
- if (stackFrames === null || stackFrames === undefined) {
- return null;
- }
+ if (stackFrames === null || stackFrames === undefined) {
+ return null;
+ }
- return {
- error,
- contextSize: CONTEXT_SIZE,
- stackFrames,
- };
+ return {
+ error,
+ contextSize: CONTEXT_SIZE,
+ stackFrames,
+ };
};
const crashWithFrames = (crash: () => void) => (error: Error) => {
- const didHookOrderChange =
- error.message.startsWith('Rendered fewer hooks') ||
- error.message.startsWith('Rendered more hooks');
-
- const key = 'remotion.lastCrashBecauseOfHooks';
- const previousCrashWasBecauseOfHooks = window.localStorage.getItem(key);
-
- // When rendering conditional hooks, refreshing does not help.
- // So we only refresh once.
- const justRefreshedBecauseOfHooks = previousCrashWasBecauseOfHooks
- ? Date.now() - Number(previousCrashWasBecauseOfHooks) < 5000
- : false;
-
- window.localStorage.setItem(
- 'remotion.lastCrashBecauseOfHooks',
- String(Date.now()),
- );
-
- if (didHookOrderChange && !justRefreshedBecauseOfHooks) {
- // eslint-disable-next-line no-console
- console.log('Hook order changed. Reloading app...');
-
- window.remotion_unsavedProps = false;
- window.location.reload();
- } else {
- setErrorsRef.current?.addError(error);
-
- crash();
- }
+ const didHookOrderChange =
+ error.message.startsWith("Rendered fewer hooks") ||
+ error.message.startsWith("Rendered more hooks");
+
+ const key = "remotion.lastCrashBecauseOfHooks";
+ const previousCrashWasBecauseOfHooks = window.localStorage.getItem(key);
+
+ // When rendering conditional hooks, refreshing does not help.
+ // So we only refresh once.
+ const justRefreshedBecauseOfHooks = previousCrashWasBecauseOfHooks
+ ? Date.now() - Number(previousCrashWasBecauseOfHooks) < 5000
+ : false;
+
+ window.localStorage.setItem(
+ "remotion.lastCrashBecauseOfHooks",
+ String(Date.now())
+ );
+
+ if (didHookOrderChange && !justRefreshedBecauseOfHooks) {
+ // eslint-disable-next-line no-console
+ console.log("Hook order changed. Reloading app...");
+
+ window.remotion_unsavedProps = false;
+ window.location.reload();
+ } else {
+ setErrorsRef.current?.addError(error);
+
+ crash();
+ }
};
export function listenToRuntimeErrors(crash: () => void) {
- const crashWithFramesRunTime = crashWithFrames(crash);
-
- registerError(window, (error) => {
- return crashWithFramesRunTime({
- message: error.message,
- stack: error.stack,
- name: error.name,
- });
- });
- registerPromise(window, (error) => {
- return crashWithFramesRunTime(error);
- });
- registerStackTraceLimit();
- registerReactStack();
- permanentRegisterConsole('error', (d) => {
- if (d.type === 'webpack-error') {
- const {message, frames} = d;
- const data = massageWarning(message, frames);
-
- crashWithFramesRunTime({
- message: data.message,
- stack: data.stack,
- name: '',
- });
- }
-
- if (d.type === 'build-error') {
- crashWithFramesRunTime(d.error);
- }
- });
-
- return function () {
- unregisterStackTraceLimit();
- unregisterPromise(window);
- unregisterError(window);
- unregisterReactStack();
- };
+ const crashWithFramesRunTime = crashWithFrames(crash);
+
+ registerError(window, (error) => {
+ return crashWithFramesRunTime({
+ message: error.message,
+ stack: error.stack,
+ name: error.name,
+ });
+ });
+ registerPromise(window, (error) => {
+ return crashWithFramesRunTime(error);
+ });
+ registerStackTraceLimit();
+ registerReactStack();
+ permanentRegisterConsole("error", (d) => {
+ if (d.type === "webpack-error") {
+ const { message, frames } = d;
+ const data = massageWarning(message, frames);
+
+ crashWithFramesRunTime({
+ message: data.message,
+ stack: data.stack,
+ name: "",
+ });
+ }
+
+ if (d.type === "build-error") {
+ crashWithFramesRunTime(d.error);
+ }
+ });
+
+ return function () {
+ unregisterStackTraceLimit();
+ unregisterPromise(window);
+ unregisterError(window);
+ unregisterReactStack();
+ };
}
diff --git a/packages/studio/src/error-overlay/react-overlay/utils/get-lines-around.ts b/packages/studio/src/error-overlay/react-overlay/utils/get-lines-around.ts
index 70647f30a3..c53da32d4a 100644
--- a/packages/studio/src/error-overlay/react-overlay/utils/get-lines-around.ts
+++ b/packages/studio/src/error-overlay/react-overlay/utils/get-lines-around.ts
@@ -9,7 +9,7 @@
* LICENSE file in the root directory of this source tree.
*/
-import type {ScriptLine} from './stack-frame';
+import type { ScriptLine } from "@remotion/studio-server/src/stack-frame";
/**
*
@@ -18,22 +18,22 @@ import type {ScriptLine} from './stack-frame';
* @param {string[] | string} lines The source code.
*/
export function getLinesAround(
- line: number,
- count: number,
- lines: string[],
+ line: number,
+ count: number,
+ lines: string[]
): ScriptLine[] {
- const result: ScriptLine[] = [];
- for (
- let index = Math.max(0, line - 1 - count);
- index <= Math.min(lines.length - 1, line - 1 + count);
- ++index
- ) {
- result.push({
- lineNumber: index + 1,
- content: lines[index],
- highlight: index === line - 1,
- });
- }
+ const result: ScriptLine[] = [];
+ for (
+ let index = Math.max(0, line - 1 - count);
+ index <= Math.min(lines.length - 1, line - 1 + count);
+ ++index
+ ) {
+ result.push({
+ lineNumber: index + 1,
+ content: lines[index],
+ highlight: index === line - 1,
+ });
+ }
- return result;
+ return result;
}
diff --git a/packages/studio/src/error-overlay/react-overlay/utils/get-stack-frames.ts b/packages/studio/src/error-overlay/react-overlay/utils/get-stack-frames.ts
index 1e1045c194..b3f9cb76fa 100644
--- a/packages/studio/src/error-overlay/react-overlay/utils/get-stack-frames.ts
+++ b/packages/studio/src/error-overlay/react-overlay/utils/get-stack-frames.ts
@@ -9,23 +9,23 @@
* LICENSE file in the root directory of this source tree.
*/
-import {parseError} from './parser';
-import type {SymbolicatedStackFrame} from './stack-frame';
-import {unmap} from './unmapper';
+import { parseError } from "./parser";
+import type { SymbolicatedStackFrame } from "@remotion/studio-server/src/stack-frame";
+import { unmap } from "./unmapper";
export const getStackFrames = async (
- error: Error,
- contextSize: number,
+ error: Error,
+ contextSize: number
): Promise<SymbolicatedStackFrame[] | null> => {
- const parsedFrames = await parseError(error, contextSize);
- const enhancedFrames = await unmap(parsedFrames, contextSize);
- if (
- enhancedFrames
- .map((f) => f.originalFileName)
- .filter((f_1) => f_1 !== null && f_1 !== undefined).length === 0
- ) {
- return null;
- }
+ const parsedFrames = await parseError(error, contextSize);
+ const enhancedFrames = await unmap(parsedFrames, contextSize);
+ if (
+ enhancedFrames
+ .map((f) => f.originalFileName)
+ .filter((f_1) => f_1 !== null && f_1 !== undefined).length === 0
+ ) {
+ return null;
+ }
- return enhancedFrames;
+ return enhancedFrames;
};
diff --git a/packages/studio/src/error-overlay/react-overlay/utils/parser.ts b/packages/studio/src/error-overlay/react-overlay/utils/parser.ts
index 440c72ddbd..cf48195491 100644
--- a/packages/studio/src/error-overlay/react-overlay/utils/parser.ts
+++ b/packages/studio/src/error-overlay/react-overlay/utils/parser.ts
@@ -9,136 +9,139 @@
* LICENSE file in the root directory of this source tree.
*/
-import {getLocationFromBuildError} from '../effects/map-error-to-react-stack';
-import {resolveFileSource} from '../effects/resolve-file-source';
-import type {SomeStackFrame, StackFrame} from './stack-frame';
-import {makeStackFrame} from './stack-frame';
+import { getLocationFromBuildError } from "@remotion/studio-server/src/helpers/map-error-to-react-stack";
+import { resolveFileSource } from "../effects/resolve-file-source";
+import type {
+ SomeStackFrame,
+ StackFrame,
+} from "@remotion/studio-server/src/stack-frame";
+import { makeStackFrame } from "@remotion/studio-server/src/stack-frame";
const regexExtractLocation = /\(?(.+?)(?::(\d+))?(?::(\d+))?\)?$/;
function extractLocation(token: string): [string, number, number] {
- const execed = regexExtractLocation.exec(token);
- if (!execed) {
- throw new Error('Could not match in extractLocation');
- }
-
- return execed.slice(1).map((v) => {
- const p = Number(v);
- if (!isNaN(p)) {
- return p;
- }
-
- return v;
- }) as [string, number, number];
+ const execed = regexExtractLocation.exec(token);
+ if (!execed) {
+ throw new Error("Could not match in extractLocation");
+ }
+
+ return execed.slice(1).map((v) => {
+ const p = Number(v);
+ if (!isNaN(p)) {
+ return p;
+ }
+
+ return v;
+ }) as [string, number, number];
}
const regexValidFrame_Chrome = /^\s*(at|in)\s.+(:\d+)/;
const regexValidFrame_FireFox =
- /(^|@)\S+:\d+|.+line\s+\d+\s+>\s+(eval|Function).+/;
+ /(^|@)\S+:\d+|.+line\s+\d+\s+>\s+(eval|Function).+/;
export function parseStack(stack: string[]): StackFrame[] {
- const frames = stack
- .filter(
- (e) => regexValidFrame_Chrome.test(e) || regexValidFrame_FireFox.test(e),
- )
- .map((e) => {
- if (regexValidFrame_FireFox.test(e)) {
- // Strip eval, we don't care about it
- let isEval = false;
- if (/ > (eval|Function)/.test(e)) {
- e = e.replace(
- / line (\d+)(?: > eval line \d+)* > (eval|Function):\d+:\d+/g,
- ':$1',
- );
- isEval = true;
- }
-
- const _data = e.split(/[@]/g);
- const _last = _data.pop();
- if (!_last) {
- throw new Error('could not get last');
- }
-
- const [_fileName, _lineNumber, _columnNumber] = extractLocation(_last);
- return makeStackFrame({
- functionName: _data.join('@') || (isEval ? 'eval' : null),
- fileName: _fileName,
- lineNumber: _lineNumber,
- columnNumber: _columnNumber,
- });
- }
-
- // Strip eval, we don't care about it
- if (e.indexOf('(eval ') !== -1) {
- e = e.replace(/(\(eval at [^()]*)|(\),.*$)/g, '');
- }
-
- if (e.indexOf('(at ') !== -1) {
- e = e.replace(/\(at /, '(');
- }
-
- const data = e.trim().split(/\s+/g).slice(1);
- const last = data.pop();
- if (!last) {
- throw new Error('could not get last');
- }
-
- const [fileName, lineNumber, columnNumber] = extractLocation(last);
- return makeStackFrame({
- functionName: data.join(' ') || null,
- fileName,
- lineNumber,
- columnNumber,
- });
- });
- return frames;
+ const frames = stack
+ .filter(
+ (e) => regexValidFrame_Chrome.test(e) || regexValidFrame_FireFox.test(e)
+ )
+ .map((e) => {
+ if (regexValidFrame_FireFox.test(e)) {
+ // Strip eval, we don't care about it
+ let isEval = false;
+ if (/ > (eval|Function)/.test(e)) {
+ e = e.replace(
+ / line (\d+)(?: > eval line \d+)* > (eval|Function):\d+:\d+/g,
+ ":$1"
+ );
+ isEval = true;
+ }
+
+ const _data = e.split(/[@]/g);
+ const _last = _data.pop();
+ if (!_last) {
+ throw new Error("could not get last");
+ }
+
+ const [_fileName, _lineNumber, _columnNumber] = extractLocation(_last);
+ return makeStackFrame({
+ functionName: _data.join("@") || (isEval ? "eval" : null),
+ fileName: _fileName,
+ lineNumber: _lineNumber,
+ columnNumber: _columnNumber,
+ });
+ }
+
+ // Strip eval, we don't care about it
+ if (e.indexOf("(eval ") !== -1) {
+ e = e.replace(/(\(eval at [^()]*)|(\),.*$)/g, "");
+ }
+
+ if (e.indexOf("(at ") !== -1) {
+ e = e.replace(/\(at /, "(");
+ }
+
+ const data = e.trim().split(/\s+/g).slice(1);
+ const last = data.pop();
+ if (!last) {
+ throw new Error("could not get last");
+ }
+
+ const [fileName, lineNumber, columnNumber] = extractLocation(last);
+ return makeStackFrame({
+ functionName: data.join(" ") || null,
+ fileName,
+ lineNumber,
+ columnNumber,
+ });
+ });
+ return frames;
}
export const parseError = async (
- error: Error | string | string[],
- contextLines: number,
+ error: Error | string | string[],
+ contextLines: number
): Promise<SomeStackFrame[]> => {
- if (error === null) {
- throw new Error('You cannot pass a null object.');
- }
-
- if (typeof error === 'string') {
- return parseStack(error.split('\n')).map((frame): SomeStackFrame => {
- return {
- type: 'transpiled',
- frame,
- };
- });
- }
-
- if (Array.isArray(error)) {
- return parseStack(error).map((frame): SomeStackFrame => {
- return {
- type: 'transpiled',
- frame,
- };
- });
- }
-
- const errorLocation = getLocationFromBuildError(error);
-
- if (errorLocation) {
- return [
- {
- type: 'symbolicated',
- frame: await resolveFileSource(errorLocation, contextLines),
- },
- ];
- }
-
- if (typeof error.stack === 'string') {
- return parseStack(error.stack.split('\n')).map((frame): SomeStackFrame => {
- return {
- type: 'transpiled',
- frame,
- };
- });
- }
-
- return [];
+ if (error === null) {
+ throw new Error("You cannot pass a null object.");
+ }
+
+ if (typeof error === "string") {
+ return parseStack(error.split("\n")).map((frame): SomeStackFrame => {
+ return {
+ type: "transpiled",
+ frame,
+ };
+ });
+ }
+
+ if (Array.isArray(error)) {
+ return parseStack(error).map((frame): SomeStackFrame => {
+ return {
+ type: "transpiled",
+ frame,
+ };
+ });
+ }
+
+ const errorLocation = getLocationFromBuildError(error);
+
+ if (errorLocation) {
+ return [
+ {
+ type: "symbolicated",
+ frame: await resolveFileSource(errorLocation, contextLines),
+ },
+ ];
+ }
+
+ if (typeof error.stack === "string") {
+ return parseStack(error.stack.split("\n")).map((frame): SomeStackFrame => {
+ return {
+ type: "transpiled",
+ frame,
+ };
+ });
+ }
+
+ return [];
};
diff --git a/packages/studio/src/error-overlay/react-overlay/utils/unmapper.ts b/packages/studio/src/error-overlay/react-overlay/utils/unmapper.ts
index 410d195fe5..60a84cf85e 100644
--- a/packages/studio/src/error-overlay/react-overlay/utils/unmapper.ts
+++ b/packages/studio/src/error-overlay/react-overlay/utils/unmapper.ts
@@ -11,76 +11,76 @@
* LICENSE file in the root directory of this source tree.
*/
-import {Internals} from 'remotion';
-import type {SourceMapConsumer} from 'source-map';
-import {getLinesAround} from './get-lines-around';
-import {getOriginalPosition, getSourceMap} from './get-source-map';
+import { Internals } from "remotion";
+import type { SourceMapConsumer } from "source-map";
+import { getLinesAround } from "./get-lines-around";
+import { getOriginalPosition, getSourceMap } from "./get-source-map";
import type {
- SomeStackFrame,
- StackFrame,
- SymbolicatedStackFrame,
-} from './stack-frame';
+ SomeStackFrame,
+ StackFrame,
+ SymbolicatedStackFrame,
+} from "@remotion/studio-server/src/stack-frame";
export const getFileContents = async (fileName: string) => {
- const res = await fetch(fileName as string);
- const fileContents = await res.text();
+ const res = await fetch(fileName as string);
+ const fileContents = await res.text();
- return fileContents;
+ return fileContents;
};
export const unmap = async (
- frames: SomeStackFrame[],
- contextLines: number,
+ frames: SomeStackFrame[],
+ contextLines: number
): Promise<SymbolicatedStackFrame[]> => {
- const transpiled = frames
- .filter((s) => s.type === 'transpiled')
- .map((s) => s.frame) as StackFrame[];
- const uniqueFileNames = [
- ...new Set(transpiled.map((f) => f.fileName).filter(Internals.truthy)),
- ];
- const maps = await Promise.all(
- uniqueFileNames.map(async (fileName) => {
- const fileContents = await getFileContents(fileName);
- return getSourceMap(fileName as string, fileContents as string);
- }),
- );
- const mapValues: Record<string, SourceMapConsumer | null> = {};
- for (let i = 0; i < uniqueFileNames.length; i++) {
- mapValues[uniqueFileNames[i]] = maps[i];
- }
+ const transpiled = frames
+ .filter((s) => s.type === "transpiled")
+ .map((s) => s.frame) as StackFrame[];
+ const uniqueFileNames = [
+ ...new Set(transpiled.map((f) => f.fileName).filter(Internals.truthy)),
+ ];
+ const maps = await Promise.all(
+ uniqueFileNames.map(async (fileName) => {
+ const fileContents = await getFileContents(fileName);
+ return getSourceMap(fileName as string, fileContents as string);
+ })
+ );
+ const mapValues: Record<string, SourceMapConsumer | null> = {};
+ for (let i = 0; i < uniqueFileNames.length; i++) {
+ mapValues[uniqueFileNames[i]] = maps[i];
+ }
- return frames
- .map((frame): SymbolicatedStackFrame | null => {
- if (frame.type === 'symbolicated') {
- return frame.frame;
- }
+ return frames
+ .map((frame): SymbolicatedStackFrame | null => {
+ if (frame.type === "symbolicated") {
+ return frame.frame;
+ }
- const map = mapValues[frame.frame.fileName as string];
- if (!map) {
- return null;
- }
+ const map = mapValues[frame.frame.fileName as string];
+ if (!map) {
+ return null;
+ }
- const pos = getOriginalPosition(
- map,
- frame.frame.lineNumber as number,
- frame.frame.columnNumber as number,
- );
- const {functionName} = frame.frame;
- let hasSource: string | null = null;
- hasSource = pos.source ? map.sourceContentFor(pos.source, false) : null;
+ const pos = getOriginalPosition(
+ map,
+ frame.frame.lineNumber as number,
+ frame.frame.columnNumber as number
+ );
+ const { functionName } = frame.frame;
+ let hasSource: string | null = null;
+ hasSource = pos.source ? map.sourceContentFor(pos.source, false) : null;
- const scriptCode =
- hasSource && pos.line
- ? getLinesAround(pos.line, contextLines, hasSource.split('\n'))
- : null;
+ const scriptCode =
+ hasSource && pos.line
+ ? getLinesAround(pos.line, contextLines, hasSource.split("\n"))
+ : null;
- return {
- originalColumnNumber: pos.column,
- originalFileName: pos.source,
- originalFunctionName: functionName,
- originalLineNumber: pos.line,
- originalScriptCode: scriptCode,
- };
- })
- .filter(Internals.truthy);
+ return {
+ originalColumnNumber: pos.column,
+ originalFileName: pos.source,
+ originalFunctionName: functionName,
+ originalLineNumber: pos.line,
+ originalScriptCode: scriptCode,
+ };
+ })
+ .filter(Internals.truthy);
};
diff --git a/packages/studio/src/error-overlay/remotion-overlay/CodeFrame.tsx b/packages/studio/src/error-overlay/remotion-overlay/CodeFrame.tsx
index 02bc135f17..d192385af2 100644
--- a/packages/studio/src/error-overlay/remotion-overlay/CodeFrame.tsx
+++ b/packages/studio/src/error-overlay/remotion-overlay/CodeFrame.tsx
@@ -1,73 +1,73 @@
-import React from 'react';
-import {HORIZONTAL_SCROLLBAR_CLASSNAME} from '../../components/Menu/is-menu-item';
-import {BLUE} from '../../helpers/colors';
-import type {ScriptLine} from '../react-overlay/utils/stack-frame';
+import React from "react";
+import { HORIZONTAL_SCROLLBAR_CLASSNAME } from "../../components/Menu/is-menu-item";
+import { BLUE } from "../../helpers/colors";
+import type { ScriptLine } from "@remotion/studio-server/src/stack-frame";
const container: React.CSSProperties = {
- display: 'flex',
- flexDirection: 'row',
- width: '100%',
+ display: "flex",
+ flexDirection: "row",
+ width: "100%",
};
const frame: React.CSSProperties = {
- backgroundColor: '#070707',
- marginBottom: 20,
- overflowY: 'auto',
+ backgroundColor: "#070707",
+ marginBottom: 20,
+ overflowY: "auto",
};
const lineNumber: React.CSSProperties = {
- whiteSpace: 'pre',
- paddingRight: 12,
- color: 'inherit',
- fontSize: 14,
- lineHeight: 1.7,
- width: 60,
- flexShrink: 0,
- display: 'inline-flex',
- alignItems: 'center',
- justifyContent: 'flex-end',
- fontFamily: 'monospace',
+ whiteSpace: "pre",
+ paddingRight: 12,
+ color: "inherit",
+ fontSize: 14,
+ lineHeight: 1.7,
+ width: 60,
+ flexShrink: 0,
+ display: "inline-flex",
+ alignItems: "center",
+ justifyContent: "flex-end",
+ fontFamily: "monospace",
};
export const CodeFrame: React.FC<{
- source: ScriptLine[];
- lineNumberWidth: number;
-}> = ({source, lineNumberWidth}) => {
- return (
- <div style={frame} className={HORIZONTAL_SCROLLBAR_CLASSNAME}>
- {source.map((s, j) => {
- return (
- <div
- // eslint-disable-next-line react/no-array-index-key
- key={j}
- style={container}
- >
- <div
- style={{
- ...lineNumber,
- backgroundColor: s.highlight ? 'white' : '#121212',
- color: s.highlight ? 'black' : 'rgba(255, 255, 255, 0.6)',
- }}
- >
- {String(s.lineNumber).padStart(lineNumberWidth, ' ')}
- </div>
- <div
- style={{
- fontFamily: 'monospace',
- whiteSpace: 'pre',
- tabSize: 2,
- color: s.highlight ? 'white' : 'rgba(255, 255, 255, 0.6)',
- backgroundColor: s.highlight ? BLUE : 'transparent',
- lineHeight: 1.7,
- paddingRight: 12,
- paddingLeft: 12,
- }}
- >
- {s.content}
- </div>
- </div>
- );
- })}
- </div>
- );
+ source: ScriptLine[];
+ lineNumberWidth: number;
+}> = ({ source, lineNumberWidth }) => {
+ return (
+ <div style={frame} className={HORIZONTAL_SCROLLBAR_CLASSNAME}>
+ {source.map((s, j) => {
+ return (
+ <div
+ // eslint-disable-next-line react/no-array-index-key
+ key={j}
+ style={container}
+ >
+ <div
+ style={{
+ ...lineNumber,
+ backgroundColor: s.highlight ? "white" : "#121212",
+ color: s.highlight ? "black" : "rgba(255, 255, 255, 0.6)",
+ }}
+ >
+ {String(s.lineNumber).padStart(lineNumberWidth, " ")}
+ </div>
+ <div
+ style={{
+ fontFamily: "monospace",
+ whiteSpace: "pre",
+ tabSize: 2,
+ color: s.highlight ? "white" : "rgba(255, 255, 255, 0.6)",
+ backgroundColor: s.highlight ? BLUE : "transparent",
+ lineHeight: 1.7,
+ paddingRight: 12,
+ paddingLeft: 12,
+ }}
+ >
+ {s.content}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
};
diff --git a/packages/studio/src/error-overlay/remotion-overlay/ErrorDisplay.tsx b/packages/studio/src/error-overlay/remotion-overlay/ErrorDisplay.tsx
index 167b15b83a..3745ea73a4 100644
--- a/packages/studio/src/error-overlay/remotion-overlay/ErrorDisplay.tsx
+++ b/packages/studio/src/error-overlay/remotion-overlay/ErrorDisplay.tsx
@@ -1,128 +1,128 @@
-import React, {useMemo} from 'react';
-import {Spacing} from '../../components/layout';
-import {HORIZONTAL_SCROLLBAR_CLASSNAME} from '../../components/Menu/is-menu-item';
-import {getLocationFromBuildError} from '../react-overlay/effects/map-error-to-react-stack';
-import type {ErrorRecord} from '../react-overlay/listen-to-runtime-errors';
-import {AskOnDiscord} from './AskOnDiscord';
-import {CalculateMetadataErrorExplainer} from './CalculateMetadataErrorExplainer';
-import {ErrorTitle} from './ErrorTitle';
-import {getHelpLink} from './get-help-link';
-import {HelpLink} from './HelpLink';
-import {OpenInEditor} from './OpenInEditor';
-import {RetryButton} from './Retry';
-import {SearchGithubIssues} from './SearchGitHubIssues';
-import {StackElement} from './StackFrame';
+import React, { useMemo } from "react";
+import { Spacing } from "../../components/layout";
+import { HORIZONTAL_SCROLLBAR_CLASSNAME } from "../../components/Menu/is-menu-item";
+import { getLocationFromBuildError } from "@remotion/studio-server/src/helpers/map-error-to-react-stack";
+import type { ErrorRecord } from "../react-overlay/listen-to-runtime-errors";
+import { AskOnDiscord } from "./AskOnDiscord";
+import { CalculateMetadataErrorExplainer } from "./CalculateMetadataErrorExplainer";
+import { ErrorTitle } from "./ErrorTitle";
+import { getHelpLink } from "./get-help-link";
+import { HelpLink } from "./HelpLink";
+import { OpenInEditor } from "./OpenInEditor";
+import { RetryButton } from "./Retry";
+import { SearchGithubIssues } from "./SearchGitHubIssues";
+import { StackElement } from "./StackFrame";
const stack: React.CSSProperties = {
- marginTop: 17,
- overflowX: 'scroll',
- marginBottom: '10vh',
+ marginTop: 17,
+ overflowX: "scroll",
+ marginBottom: "10vh",
};
const spacer: React.CSSProperties = {
- width: 5,
- display: 'inline-block',
+ width: 5,
+ display: "inline-block",
};
export type OnRetry = null | (() => void);
export const ErrorDisplay: React.FC<{
- display: ErrorRecord;
- keyboardShortcuts: boolean;
- onRetry: OnRetry;
- canHaveDismissButton: boolean;
- calculateMetadata: boolean;
+ display: ErrorRecord;
+ keyboardShortcuts: boolean;
+ onRetry: OnRetry;
+ canHaveDismissButton: boolean;
+ calculateMetadata: boolean;
}> = ({
- display,
- keyboardShortcuts,
- onRetry,
- canHaveDismissButton,
- calculateMetadata,
+ display,
+ keyboardShortcuts,
+ onRetry,
+ canHaveDismissButton,
+ calculateMetadata,
}) => {
- const highestLineNumber = Math.max(
- ...display.stackFrames
- .map((s) => s.originalScriptCode)
- .flat(1)
- .map((s) => s?.lineNumber ?? 0),
- );
+ const highestLineNumber = Math.max(
+ ...display.stackFrames
+ .map((s) => s.originalScriptCode)
+ .flat(1)
+ .map((s) => s?.lineNumber ?? 0)
+ );
- const message = useMemo(() => {
- // Format compilation errors
- const location = getLocationFromBuildError(display.error);
- if (!location) {
- return display.error.message;
- }
+ const message = useMemo(() => {
+ // Format compilation errors
+ const location = getLocationFromBuildError(display.error);
+ if (!location) {
+ return display.error.message;
+ }
- return location.message
- .replace(/\\n/g, '\n')
- .replace(/\\t/g, ' ')
- .replace(/^error:/, '')
- .trim();
- }, [display.error]);
+ return location.message
+ .replace(/\\n/g, "\n")
+ .replace(/\\t/g, " ")
+ .replace(/^error:/, "")
+ .trim();
+ }, [display.error]);
- const lineNumberWidth = String(highestLineNumber).length;
+ const lineNumberWidth = String(highestLineNumber).length;
- const helpLink = getHelpLink(message);
+ const helpLink = getHelpLink(message);
- return (
- <div>
- <ErrorTitle
- symbolicating={false}
- name={display.error.name}
- message={message}
- canHaveDismissButton={canHaveDismissButton}
- />
- {helpLink ? (
- <>
- <HelpLink
- link={helpLink}
- canHaveKeyboardShortcuts={keyboardShortcuts}
- />
- <div style={spacer} />
- </>
- ) : null}
- {display.stackFrames.length > 0 && window.remotion_editorName ? (
- <>
- <OpenInEditor
- canHaveKeyboardShortcuts={keyboardShortcuts}
- stack={display.stackFrames[0]}
- />
- <div style={spacer} />
- </>
- ) : null}
- <SearchGithubIssues
- canHaveKeyboardShortcuts={keyboardShortcuts}
- message={display.error.message}
- />
- <div style={spacer} />
- <AskOnDiscord canHaveKeyboardShortcuts={keyboardShortcuts} />
- {onRetry ? (
- <>
- <div style={spacer} />
- <RetryButton onClick={onRetry} />
- </>
- ) : null}
- {calculateMetadata ? (
- <>
- <br />
- <Spacing y={0.5} />
- <CalculateMetadataErrorExplainer />
- </>
- ) : null}
- <div style={stack} className={HORIZONTAL_SCROLLBAR_CLASSNAME}>
- {display.stackFrames.map((s, i) => {
- return (
- <StackElement
- // eslint-disable-next-line react/no-array-index-key
- key={i}
- isFirst={i === 0}
- s={s}
- lineNumberWidth={lineNumberWidth}
- defaultFunctionName={'(anonymous function)'}
- />
- );
- })}
- </div>
- </div>
- );
+ return (
+ <div>
+ <ErrorTitle
+ symbolicating={false}
+ name={display.error.name}
+ message={message}
+ canHaveDismissButton={canHaveDismissButton}
+ />
+ {helpLink ? (
+ <>
+ <HelpLink
+ link={helpLink}
+ canHaveKeyboardShortcuts={keyboardShortcuts}
+ />
+ <div style={spacer} />
+ </>
+ ) : null}
+ {display.stackFrames.length > 0 && window.remotion_editorName ? (
+ <>
+ <OpenInEditor
+ canHaveKeyboardShortcuts={keyboardShortcuts}
+ stack={display.stackFrames[0]}
+ />
+ <div style={spacer} />
+ </>
+ ) : null}
+ <SearchGithubIssues
+ canHaveKeyboardShortcuts={keyboardShortcuts}
+ message={display.error.message}
+ />
+ <div style={spacer} />
+ <AskOnDiscord canHaveKeyboardShortcuts={keyboardShortcuts} />
+ {onRetry ? (
+ <>
+ <div style={spacer} />
+ <RetryButton onClick={onRetry} />
+ </>
+ ) : null}
+ {calculateMetadata ? (
+ <>
+ <br />
+ <Spacing y={0.5} />
+ <CalculateMetadataErrorExplainer />
+ </>
+ ) : null}
+ <div style={stack} className={HORIZONTAL_SCROLLBAR_CLASSNAME}>
+ {display.stackFrames.map((s, i) => {
+ return (
+ <StackElement
+ // eslint-disable-next-line react/no-array-index-key
+ key={i}
+ isFirst={i === 0}
+ s={s}
+ lineNumberWidth={lineNumberWidth}
+ defaultFunctionName={"(anonymous function)"}
+ />
+ );
+ })}
+ </div>
+ </div>
+ );
};
diff --git a/packages/studio/src/error-overlay/remotion-overlay/OpenInEditor.tsx b/packages/studio/src/error-overlay/remotion-overlay/OpenInEditor.tsx
index b23d8d444e..b470d226f4 100644
--- a/packages/studio/src/error-overlay/remotion-overlay/OpenInEditor.tsx
+++ b/packages/studio/src/error-overlay/remotion-overlay/OpenInEditor.tsx
@@ -9,7 +9,7 @@ import React, {
import { Button } from "../../components/Button";
import { openInEditor } from "../../helpers/open-in-editor";
import { useKeybinding } from "../../helpers/use-keybinding";
-import type { SymbolicatedStackFrame } from "../react-overlay/utils/stack-frame";
+import type { SymbolicatedStackFrame } from "@remotion/studio-server/src/stack-frame";
import { ShortcutHint } from "./ShortcutHint";
type State =
diff --git a/packages/studio/src/error-overlay/remotion-overlay/StackFrame.tsx b/packages/studio/src/error-overlay/remotion-overlay/StackFrame.tsx
index 40e2dd752d..41bdd631cc 100644
--- a/packages/studio/src/error-overlay/remotion-overlay/StackFrame.tsx
+++ b/packages/studio/src/error-overlay/remotion-overlay/StackFrame.tsx
@@ -1,6 +1,6 @@
import React, { useCallback, useState } from "react";
import { Button } from "../../components/Button";
-import type { SymbolicatedStackFrame } from "../react-overlay/utils/stack-frame";
+import type { SymbolicatedStackFrame } from "@remotion/studio-server/src/stack-frame";
import { CaretDown, CaretRight } from "./carets";
import { CodeFrame } from "./CodeFrame";
import { formatLocation } from "./format-location";
diff --git a/packages/studio/src/helpers/client-id.tsx b/packages/studio/src/helpers/client-id.tsx
index c7b241a1a6..0779e5282a 100644
--- a/packages/studio/src/helpers/client-id.tsx
+++ b/packages/studio/src/helpers/client-id.tsx
@@ -1,167 +1,167 @@
-import React, {useCallback, useEffect, useMemo, useRef} from 'react';
-import type {WatchRemotionStaticFilesPayload} from 'remotion';
-import {Internals} from 'remotion';
-import {sendErrorNotification} from '../components/Notifications/NotificationCenter';
-import playBeepSound from '../components/PlayBeepSound';
-import {renderJobsRef} from '../components/RenderQueue/context';
-import type {EventSourceEvent} from '../event-source-events';
+import type { EventSourceEvent } from "@remotion/studio-server";
+import React, { useCallback, useEffect, useMemo, useRef } from "react";
+import type { WatchRemotionStaticFilesPayload } from "remotion";
+import { Internals } from "remotion";
+import { sendErrorNotification } from "../components/Notifications/NotificationCenter";
+import playBeepSound from "../components/PlayBeepSound";
+import { renderJobsRef } from "../components/RenderQueue/context";
type PreviewServerState =
- | {
- type: 'init';
- }
- | {
- type: 'connected';
- clientId: string;
- }
- | {
- type: 'disconnected';
- };
+ | {
+ type: "init";
+ }
+ | {
+ type: "connected";
+ clientId: string;
+ }
+ | {
+ type: "disconnected";
+ };
type Context = {
- previewServerState: PreviewServerState;
- subscribeToEvent: (
- type: EventSourceEvent['type'],
- listener: (event: EventSourceEvent) => void,
- ) => () => void;
+ previewServerState: PreviewServerState;
+ subscribeToEvent: (
+ type: EventSourceEvent["type"],
+ listener: (event: EventSourceEvent) => void
+ ) => () => void;
};
export const StudioServerConnectionCtx = React.createContext<Context>({
- previewServerState: {
- type: 'init',
- },
- subscribeToEvent: () => {
- throw new Error('Context not initalized');
- },
+ previewServerState: {
+ type: "init",
+ },
+ subscribeToEvent: () => {
+ throw new Error("Context not initalized");
+ },
});
type Listeners = {
- type: string;
- listener: (event: EventSourceEvent) => void;
+ type: string;
+ listener: (event: EventSourceEvent) => void;
}[];
export const PreviewServerConnection: React.FC<{
- children: React.ReactNode;
-}> = ({children}) => {
- const listeners = useRef<Listeners>([]);
-
- const subscribeToEvent = useCallback(
- (
- type: EventSourceEvent['type'],
- listener: (event: EventSourceEvent) => void,
- ) => {
- listeners.current.push({type, listener});
-
- return () => {
- listeners.current = listeners.current.filter(
- (l) => l.type !== type || l.listener !== listener,
- );
- };
- },
- [],
- );
-
- const openEventSource = useCallback(() => {
- const source = new EventSource('/events');
-
- source.addEventListener('message', (event) => {
- const newEvent = JSON.parse(event.data) as EventSourceEvent;
- if (
- newEvent.type === 'new-input-props' ||
- newEvent.type === 'new-env-variables'
- ) {
- window.location.reload();
- }
-
- if (newEvent.type === 'init') {
- setState({
- type: 'connected',
- clientId: newEvent.clientId,
- });
- }
-
- if (newEvent.type === 'render-queue-updated') {
- renderJobsRef.current?.updateRenderJobs(newEvent.queue);
- for (const job of newEvent.queue) {
- if (job.status === 'done' && job.beepOnFinish) {
- playBeepSound(job.id);
- }
- }
- }
-
- if (newEvent.type === 'render-job-failed') {
- sendErrorNotification(`Rendering "${newEvent.compositionId}" failed`);
- }
-
- if (newEvent.type === 'new-public-folder') {
- const payload: WatchRemotionStaticFilesPayload = {
- files: newEvent.files,
- };
-
- window.dispatchEvent(
- new CustomEvent(Internals.WATCH_REMOTION_STATIC_FILES, {
- detail: payload,
- }),
- );
- window.remotion_staticFiles = newEvent.files;
- window.remotion_publicFolderExists = newEvent.folderExists;
- }
-
- listeners.current.forEach((l) => {
- if (l.type === newEvent.type) {
- l.listener(newEvent);
- }
- });
- });
-
- source.addEventListener('open', () => {
- (source as EventSource).addEventListener(
- 'error',
- () => {
- setState({type: 'disconnected'});
- // Display an error message that the studio server has disconnected.
- source?.close();
-
- // Retry later
- setTimeout(() => {
- openEventSource();
- }, 1000);
- },
- {once: true},
- );
- });
-
- const close = () => {
- source.close();
- };
-
- return {
- close,
- };
- }, []);
-
- useEffect(() => {
- const {close} = openEventSource();
-
- return () => {
- close();
- };
- }, [openEventSource]);
-
- const [state, setState] = React.useState<PreviewServerState>({
- type: 'init',
- });
-
- const context: Context = useMemo(() => {
- return {
- previewServerState: state,
- subscribeToEvent,
- };
- }, [state, subscribeToEvent]);
-
- return (
- <StudioServerConnectionCtx.Provider value={context}>
- {children}
- </StudioServerConnectionCtx.Provider>
- );
+ children: React.ReactNode;
+}> = ({ children }) => {
+ const listeners = useRef<Listeners>([]);
+
+ const subscribeToEvent = useCallback(
+ (
+ type: EventSourceEvent["type"],
+ listener: (event: EventSourceEvent) => void
+ ) => {
+ listeners.current.push({ type, listener });
+
+ return () => {
+ listeners.current = listeners.current.filter(
+ (l) => l.type !== type || l.listener !== listener
+ );
+ };
+ },
+ []
+ );
+
+ const openEventSource = useCallback(() => {
+ const source = new EventSource("/events");
+
+ source.addEventListener("message", (event) => {
+ const newEvent = JSON.parse(event.data) as EventSourceEvent;
+ if (
+ newEvent.type === "new-input-props" ||
+ newEvent.type === "new-env-variables"
+ ) {
+ window.location.reload();
+ }
+
+ if (newEvent.type === "init") {
+ setState({
+ type: "connected",
+ clientId: newEvent.clientId,
+ });
+ }
+
+ if (newEvent.type === "render-queue-updated") {
+ renderJobsRef.current?.updateRenderJobs(newEvent.queue);
+ for (const job of newEvent.queue) {
+ if (job.status === "done" && job.beepOnFinish) {
+ playBeepSound(job.id);
+ }
+ }
+ }
+
+ if (newEvent.type === "render-job-failed") {
+ sendErrorNotification(`Rendering "${newEvent.compositionId}" failed`);
+ }
+
+ if (newEvent.type === "new-public-folder") {
+ const payload: WatchRemotionStaticFilesPayload = {
+ files: newEvent.files,
+ };
+
+ window.dispatchEvent(
+ new CustomEvent(Internals.WATCH_REMOTION_STATIC_FILES, {
+ detail: payload,
+ })
+ );
+ window.remotion_staticFiles = newEvent.files;
+ window.remotion_publicFolderExists = newEvent.folderExists;
+ }
+
+ listeners.current.forEach((l) => {
+ if (l.type === newEvent.type) {
+ l.listener(newEvent);
+ }
+ });
+ });
+
+ source.addEventListener("open", () => {
+ (source as EventSource).addEventListener(
+ "error",
+ () => {
+ setState({ type: "disconnected" });
+ // Display an error message that the studio server has disconnected.
+ source?.close();
+
+ // Retry later
+ setTimeout(() => {
+ openEventSource();
+ }, 1000);
+ },
+ { once: true }
+ );
+ });
+
+ const close = () => {
+ source.close();
+ };
+
+ return {
+ close,
+ };
+ }, []);
+
+ useEffect(() => {
+ const { close } = openEventSource();
+
+ return () => {
+ close();
+ };
+ }, [openEventSource]);
+
+ const [state, setState] = React.useState<PreviewServerState>({
+ type: "init",
+ });
+
+ const context: Context = useMemo(() => {
+ return {
+ previewServerState: state,
+ subscribeToEvent,
+ };
+ }, [state, subscribeToEvent]);
+
+ return (
+ <StudioServerConnectionCtx.Provider value={context}>
+ {children}
+ </StudioServerConnectionCtx.Provider>
+ );
};
diff --git a/packages/studio/src/helpers/use-file-existence.ts b/packages/studio/src/helpers/use-file-existence.ts
index 4e3a928254..3fad8d3f5d 100644
--- a/packages/studio/src/helpers/use-file-existence.ts
+++ b/packages/studio/src/helpers/use-file-existence.ts
@@ -1,82 +1,82 @@
-import {useContext, useEffect, useRef, useState} from 'react';
+import type { EventSourceEvent } from "@remotion/studio-server";
+import { useContext, useEffect, useRef, useState } from "react";
import {
- subscribeToFileExistenceWatcher,
- unsubscribeFromFileExistenceWatcher,
-} from '../components/RenderQueue/actions';
-import type {EventSourceEvent} from '../event-source-events';
-import {StudioServerConnectionCtx} from './client-id';
+ subscribeToFileExistenceWatcher,
+ unsubscribeFromFileExistenceWatcher,
+} from "../components/RenderQueue/actions";
+import { StudioServerConnectionCtx } from "./client-id";
export const useFileExistence = (outName: string) => {
- const [exists, setExists] = useState(false);
+ const [exists, setExists] = useState(false);
- const {previewServerState: state, subscribeToEvent} = useContext(
- StudioServerConnectionCtx,
- );
- const clientId = state.type === 'connected' ? state.clientId : undefined;
+ const { previewServerState: state, subscribeToEvent } = useContext(
+ StudioServerConnectionCtx
+ );
+ const clientId = state.type === "connected" ? state.clientId : undefined;
- const currentOutName = useRef('');
- currentOutName.current = outName;
+ const currentOutName = useRef("");
+ currentOutName.current = outName;
- useEffect(() => {
- if (!clientId) {
- return;
- }
+ useEffect(() => {
+ if (!clientId) {
+ return;
+ }
- subscribeToFileExistenceWatcher({
- file: outName,
- clientId,
- }).then((_exists) => {
- if (currentOutName.current === outName) {
- setExists(_exists);
- }
- });
+ subscribeToFileExistenceWatcher({
+ file: outName,
+ clientId,
+ }).then((_exists) => {
+ if (currentOutName.current === outName) {
+ setExists(_exists);
+ }
+ });
- return () => {
- unsubscribeFromFileExistenceWatcher({file: outName, clientId});
- };
- }, [clientId, outName]);
+ return () => {
+ unsubscribeFromFileExistenceWatcher({ file: outName, clientId });
+ };
+ }, [clientId, outName]);
- useEffect(() => {
- const listener = (event: EventSourceEvent) => {
- if (event.type !== 'watched-file-deleted') {
- return;
- }
+ useEffect(() => {
+ const listener = (event: EventSourceEvent) => {
+ if (event.type !== "watched-file-deleted") {
+ return;
+ }
- if (event.file !== currentOutName.current) {
- return;
- }
+ if (event.file !== currentOutName.current) {
+ return;
+ }
- if (currentOutName.current === outName) {
- setExists(false);
- }
- };
+ if (currentOutName.current === outName) {
+ setExists(false);
+ }
+ };
- const unsub = subscribeToEvent('watched-file-deleted', listener);
- return () => {
- unsub();
- };
- }, [outName, subscribeToEvent]);
+ const unsub = subscribeToEvent("watched-file-deleted", listener);
+ return () => {
+ unsub();
+ };
+ }, [outName, subscribeToEvent]);
- useEffect(() => {
- const listener = (event: EventSourceEvent) => {
- if (event.type !== 'watched-file-undeleted') {
- return;
- }
+ useEffect(() => {
+ const listener = (event: EventSourceEvent) => {
+ if (event.type !== "watched-file-undeleted") {
+ return;
+ }
- if (event.file !== outName) {
- return;
- }
+ if (event.file !== outName) {
+ return;
+ }
- if (currentOutName.current === outName) {
- setExists(true);
- }
- };
+ if (currentOutName.current === outName) {
+ setExists(true);
+ }
+ };
- const unsub = subscribeToEvent('watched-file-undeleted', listener);
- return () => {
- unsub();
- };
- }, [outName, subscribeToEvent]);
+ const unsub = subscribeToEvent("watched-file-undeleted", listener);
+ return () => {
+ unsub();
+ };
+ }, [outName, subscribeToEvent]);
- return exists;
+ return exists;
};
diff --git a/packages/studio/src/hot-middleware-client/client.ts b/packages/studio/src/hot-middleware-client/client.ts
new file mode 100644
index 0000000000..451969afbd
--- /dev/null
+++ b/packages/studio/src/hot-middleware-client/client.ts
@@ -0,0 +1,220 @@
+/// <reference lib="dom" />
+/// <reference lib="dom.iterable" />
+
+/* eslint-disable no-console */
+/**
+ * Source code is adapted from
+ * https://github.com/webpack-contrib/webpack-hot-middleware#readme
+ * and rewritten in TypeScript. This file is MIT licensed
+ */
+import type { HotMiddlewareMessage } from "@remotion/studio-server/client";
+import { StudioServerClientAPIs } from "@remotion/studio-server/client";
+import { processUpdate } from "./process-update";
+
+if (typeof window === "undefined") {
+ // do nothing
+} else if (typeof window.EventSource === "undefined") {
+ console.warn(
+ "Unsupported browser: You need a browser that supports EventSource "
+ );
+} else {
+ connect();
+}
+
+const { hotMiddlewareOptions } = StudioServerClientAPIs;
+
+function eventSourceWrapper() {
+ let source: EventSource;
+ let lastActivity = Date.now();
+ const listeners: ((ev: MessageEvent) => void)[] = [];
+
+ init();
+ const timer = setInterval(() => {
+ if (
+ Date.now() - lastActivity >
+ StudioServerClientAPIs.hotMiddlewareOptions.timeout
+ ) {
+ handleDisconnect();
+ }
+ }, StudioServerClientAPIs.hotMiddlewareOptions.timeout / 2);
+
+ function init() {
+ source = new window.EventSource(
+ StudioServerClientAPIs.hotMiddlewareOptions.path
+ );
+ source.onopen = handleOnline;
+ source.onerror = handleDisconnect;
+ source.onmessage = handleMessage;
+ }
+
+ function handleOnline() {
+ lastActivity = Date.now();
+ }
+
+ function handleMessage(event: MessageEvent) {
+ lastActivity = Date.now();
+ for (let i = 0; i < listeners.length; i++) {
+ listeners[i](event);
+ }
+ }
+
+ function handleDisconnect() {
+ clearInterval(timer);
+ source.close();
+ setTimeout(init, 1000);
+ }
+
+ return {
+ addMessageListener(fn: (msg: MessageEvent) => void) {
+ listeners.push(fn);
+ },
+ };
+}
+
+declare global {
+ interface Window {
+ __whmEventSourceWrapper: {
+ [key: string]: ReturnType<typeof eventSourceWrapper>;
+ };
+ __webpack_hot_middleware_reporter__: Reporter;
+ }
+}
+
+function getEventSourceWrapper() {
+ if (!window.__whmEventSourceWrapper) {
+ window.__whmEventSourceWrapper = {};
+ }
+
+ if (!window.__whmEventSourceWrapper[hotMiddlewareOptions.path]) {
+ // cache the wrapper for other entries loaded on
+ // the same page with the same hotMiddlewareOptions.path
+ window.__whmEventSourceWrapper[hotMiddlewareOptions.path] =
+ eventSourceWrapper();
+ }
+
+ return window.__whmEventSourceWrapper[hotMiddlewareOptions.path];
+}
+
+function connect() {
+ getEventSourceWrapper().addMessageListener(handleMessage);
+
+ function handleMessage(event: MessageEvent) {
+ if (event.data === "\uD83D\uDC93") {
+ return;
+ }
+
+ try {
+ processMessage(JSON.parse(event.data));
+ } catch (ex) {
+ if (hotMiddlewareOptions.warn) {
+ console.warn("Invalid HMR message: " + event.data + "\n" + ex);
+ }
+ }
+ }
+}
+
+const singletonKey = "__webpack_hot_middleware_reporter__" as const;
+
+let reporter: Reporter;
+if (typeof window !== "undefined") {
+ if (!window[singletonKey]) {
+ window[singletonKey] = createReporter();
+ }
+
+ reporter = window[singletonKey];
+}
+
+type Reporter = ReturnType<typeof createReporter>;
+
+function createReporter() {
+ const styles = {
+ errors: "color: #ff0000;",
+ warnings: "color: #999933;",
+ };
+ let previousProblems: string | null = null;
+
+ function log(type: "errors" | "warnings", obj: HotMiddlewareMessage) {
+ if (obj.action === "building") {
+ console.log("[Fast Refresh] Building");
+ return;
+ }
+
+ const newProblems = obj[type]
+ .map((msg) => {
+ return StudioServerClientAPIs.stripAnsi(msg as string);
+ })
+ .join("\n");
+ if (previousProblems === newProblems) {
+ return;
+ }
+
+ previousProblems = newProblems;
+
+ const style = styles[type];
+ const name = obj.name ? "'" + obj.name + "' " : "";
+ const title =
+ "[Fast Refresh] bundle " + name + "has " + obj[type].length + " " + type;
+ // NOTE: console.warn or console.error will print the stack trace
+ // which isn't helpful here, so using console.log to escape it.
+ if (console.group && console.groupEnd) {
+ console.group("%c" + title, style);
+ console.log("%c" + newProblems, style);
+ console.groupEnd();
+ } else {
+ console.log(
+ "%c" + title + "\n\t%c" + newProblems.replace(/\n/g, "\n\t"),
+ style + "font-weight: bold;",
+ style + "font-weight: normal;"
+ );
+ }
+ }
+
+ return {
+ cleanProblemsCache() {
+ previousProblems = null;
+ },
+ problems(type: "errors" | "warnings", obj: HotMiddlewareMessage) {
+ if (hotMiddlewareOptions.warn) {
+ log(type, obj);
+ }
+
+ return true;
+ },
+ success: () => undefined,
+ };
+}
+
+function processMessage(obj: HotMiddlewareMessage) {
+ switch (obj.action) {
+ case "building":
+ window.remotion_isBuilding?.();
+
+ break;
+ case "sync":
+ case "built": {
+ let applyUpdate = true;
+ if (obj.errors.length > 0) {
+ if (reporter) reporter.problems("errors", obj);
+ applyUpdate = false;
+ } else if (obj.warnings.length > 0) {
+ if (reporter) {
+ const overlayShown = reporter.problems("warnings", obj);
+ applyUpdate = overlayShown;
+ }
+ } else if (reporter) {
+ reporter.cleanProblemsCache();
+ reporter.success();
+ }
+
+ if (applyUpdate) {
+ window.remotion_finishedBuilding?.();
+ processUpdate(obj.hash, obj.modules, hotMiddlewareOptions);
+ }
+
+ break;
+ }
+
+ default:
+ break;
+ }
+}
diff --git a/packages/studio/src/hot-middleware-client/process-update.ts b/packages/studio/src/hot-middleware-client/process-update.ts
new file mode 100644
index 0000000000..44f5b0f242
--- /dev/null
+++ b/packages/studio/src/hot-middleware-client/process-update.ts
@@ -0,0 +1,197 @@
+/* eslint-disable no-console */
+/**
+ * Source code is adapted from
+ * https://github.com/webpack-contrib/webpack-hot-middleware#readme
+ * and rewritten in TypeScript. This file is MIT licensed
+ */
+
+/**
+ * Based heavily on https://github.com/webpack/webpack/blob/
+ * c0afdf9c6abc1dd70707c594e473802a566f7b6e/hot/only-dev-server.js
+ * Original copyright Tobias Koppers @sokra (MIT license)
+ */
+
+import type { HotMiddlewareOptions, ModuleMap } from "@remotion/studio-server";
+import { notificationCenter } from "../components/Notifications/NotificationCenter";
+
+if (!__webpack_module__.hot) {
+ throw new Error("[Fast refresh] Hot Module Replacement is disabled.");
+}
+
+const hmrDocsUrl = "https://webpack.js.org/concepts/hot-module-replacement/"; // eslint-disable-line max-len
+
+let lastHash: string | undefined;
+const failureStatuses = { abort: 1, fail: 1 };
+const applyOptions: AcceptOptions = {
+ ignoreUnaccepted: true,
+ ignoreDeclined: true,
+ ignoreErrored: true,
+ onUnaccepted(data) {
+ console.warn(
+ "Ignored an update to unaccepted module " +
+ (data.chain ?? []).join(" -> ")
+ );
+ },
+ onDeclined(data) {
+ console.warn(
+ "Ignored an update to declined module " + (data.chain ?? []).join(" -> ")
+ );
+ },
+ onErrored(data) {
+ console.error(data.error);
+ console.warn(
+ "Ignored an error while updating module " +
+ data.moduleId +
+ " (" +
+ data.type +
+ ")"
+ );
+ },
+};
+
+function upToDate(hash?: string) {
+ if (hash) lastHash = hash;
+ return lastHash === __webpack_hash__;
+}
+
+export const processUpdate = function (
+ hash: string | undefined,
+ moduleMap: ModuleMap,
+ options: HotMiddlewareOptions
+) {
+ const { reload } = options;
+ if (!upToDate(hash) && __webpack_module__.hot?.status() === "idle") {
+ check();
+ }
+
+ async function check() {
+ const cb = function (err: Error | null, updatedModules: ModuleId[] | null) {
+ if (err) return handleError(err);
+
+ if (!updatedModules) {
+ if (options.warn) {
+ console.warn(
+ "[Fast refresh] Cannot find update (Full reload needed)"
+ );
+ console.warn(
+ "[Fast refresh] (Probably because of restarting the server)"
+ );
+ }
+
+ performReload();
+ return null;
+ }
+
+ const applyCallback = function (
+ applyErr: Error | null,
+ renewedModules: ModuleId[]
+ ) {
+ if (applyErr) return handleError(applyErr);
+
+ if (!upToDate()) {
+ check();
+ }
+
+ logUpdates(updatedModules, renewedModules);
+ };
+
+ const applyResult = __webpack_module__.hot?.apply(applyOptions);
+ if ((applyResult as unknown as Promise<unknown>)?.then) {
+ // HotModuleReplacement.runtime.js refers to the result as `outdatedModules`
+ (applyResult as unknown as Promise<ModuleId[]>)
+ .then((outdatedModules) => {
+ applyCallback(null, outdatedModules);
+ })
+ .catch((_err: Error) => applyCallback(_err, []));
+ }
+ };
+
+ try {
+ const result = await __webpack_module__.hot?.check(false);
+ cb(null, result);
+ } catch (err) {
+ cb(err as Error, []);
+ }
+ }
+
+ function logUpdates(updatedModules: ModuleId[], renewedModules: ModuleId[]) {
+ const unacceptedModules =
+ updatedModules?.filter((moduleId) => {
+ return renewedModules && renewedModules.indexOf(moduleId) < 0;
+ }) ?? [];
+
+ if (unacceptedModules.length > 0) {
+ if (options.warn) {
+ console.warn(
+ "[Fast refresh] The following modules couldn't be hot updated: " +
+ "(Full reload needed)\n" +
+ "This is usually because the modules which have changed " +
+ "(and their parents) do not know how to hot reload themselves. " +
+ "See " +
+ hmrDocsUrl +
+ " for more details."
+ );
+ unacceptedModules.forEach((moduleId) => {
+ console.warn(
+ "[Fast refresh] - " + (moduleMap[moduleId] || moduleId)
+ );
+ });
+ }
+
+ performReload();
+ return;
+ }
+
+ if (!renewedModules || renewedModules.length === 0) {
+ console.log("[Fast refresh] Nothing hot updated.");
+ } else {
+ renewedModules.forEach((moduleId) => {
+ console.log(
+ `[Fast refresh] ${moduleMap[moduleId] || moduleId} fast refreshed.`
+ );
+ });
+ }
+ }
+
+ function handleError(err: Error) {
+ if ((__webpack_module__.hot?.status() ?? "nope") in failureStatuses) {
+ if (options.warn) {
+ console.warn(
+ "[Fast refresh] Cannot check for update (Full reload needed)"
+ );
+ console.warn("[Fast refresh] " + (err.stack || err.message));
+ }
+
+ performReload();
+ return;
+ }
+
+ if (options.warn) {
+ console.warn(
+ "[Fast refresh] Update check failed: " + (err.stack || err.message)
+ );
+ if (!window.remotion_unsavedProps) {
+ window.location.reload();
+ }
+ }
+ }
+
+ function performReload() {
+ if (!reload) {
+ return;
+ }
+
+ if (options.warn) console.warn("[Fast refresh] Reloading page");
+ if (window.remotion_unsavedProps) {
+ notificationCenter.current?.addNotification({
+ id: "random",
+ content:
+ "Fast refresh needs to reload the page, but you have unsaved props. Save then reload the page to apply changes.",
+ created: new Date().getMilliseconds(),
+ duration: 1,
+ });
+ } else {
+ window.location.reload();
+ }
+ }
+};
diff --git a/packages/studio/src/previewEntry.tsx b/packages/studio/src/previewEntry.tsx
new file mode 100644
index 0000000000..2d4a924229
--- /dev/null
+++ b/packages/studio/src/previewEntry.tsx
@@ -0,0 +1,42 @@
+import React from "react";
+import type { render } from "react-dom";
+import ReactDOM from "react-dom/client";
+import { Internals } from "remotion";
+import { startErrorOverlay } from "./error-overlay/entry-basic";
+import { Studio } from "./Studio";
+import "../styles/styles.css";
+import { NoRegisterRoot } from "./components/NoRegisterRoot";
+
+Internals.CSSUtils.injectCSS(
+ Internals.CSSUtils.makeDefaultCSS(null, "#1f2428")
+);
+
+let root: ReturnType<typeof ReactDOM.createRoot> | null = null;
+
+const getRootForElement = () => {
+ if (root) {
+ return root;
+ }
+
+ root = ReactDOM.createRoot(Internals.getPreviewDomElement() as HTMLElement);
+ return root;
+};
+
+const renderToDOM = (content: React.ReactElement) => {
+ // @ts-expect-error
+ if (ReactDOM.createRoot) {
+ getRootForElement().render(content);
+ } else {
+ (ReactDOM as unknown as { render: typeof render }).render(
+ content,
+ Internals.getPreviewDomElement()
+ );
+ }
+};
+
+renderToDOM(<NoRegisterRoot />);
+
+Internals.waitForRoot((NewRoot) => {
+ renderToDOM(<Studio rootComponent={NewRoot} />);
+ startErrorOverlay();
+});
diff --git a/packages/studio/tsconfig.json b/packages/studio/tsconfig.json
index 3746d36bcf..b90cb01511 100644
--- a/packages/studio/tsconfig.json
+++ b/packages/studio/tsconfig.json
@@ -6,7 +6,7 @@
"outDir": "dist",
"skipLibCheck": true
},
- "include": ["src", "../studio-server/src/helpers/format-bytes.ts"],
+ "include": ["src"],
"references": [
{
"path": "../core"