Skip to content

🎥 Make videos programmatically with React

`@remotion/studio-server`: Suppress HMR building spinner on sequence props save

Jonny Burger64be35d42703
diff --git a/packages/studio-server/src/codemods/update-sequence-props.ts b/packages/studio-server/src/codemods/update-sequence-props.ts
index 47f9de0610..9ce3797849 100644
--- a/packages/studio-server/src/codemods/update-sequence-props.ts
+++ b/packages/studio-server/src/codemods/update-sequence-props.ts
@@ -16,9 +16,10 @@ export const updateSequenceProps = async ({
key: string;
value: unknown;
enumPaths: EnumPath[];
-}): Promise<string> => {
+}): Promise<{output: string; oldValueString: string}> => {
const ast = parseAst(input);
let found = false;
+ let oldValueString = '';
recast.types.visit(ast, {
visitJSXOpeningElement(path) {
@@ -46,6 +47,15 @@ export const updateSequenceProps = async ({
);
}
+ if (attr.value) {
+ const printed = recast.print(attr.value).code;
+ // Strip JSX expression container braces, e.g. "{30}" -> "30"
+ oldValueString =
+ printed.startsWith('{') && printed.endsWith('}')
+ ? printed.slice(1, -1)
+ : printed;
+ }
+
const parsed = (
(
parseAst(`a = ${stringifyDefaultProps({props: value, enumPaths})}`)
@@ -98,5 +108,5 @@ export const updateSequenceProps = async ({
plugins: [],
endOfLine: 'auto',
});
- return prettified;
+ return {output: prettified, oldValueString};
};
diff --git a/packages/studio-server/src/hyperlinks/is-supported.ts b/packages/studio-server/src/hyperlinks/is-supported.ts
new file mode 100644
index 0000000000..a87f351463
--- /dev/null
+++ b/packages/studio-server/src/hyperlinks/is-supported.ts
@@ -0,0 +1,103 @@
+// From https://github.com/jamestalmage/supports-hyperlinks/blob/master/index.js
+
+// MIT License
+// Copyright (c) James Talmage <[email protected]> (github.com/jamestalmage)
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+import {RenderInternals} from '@remotion/renderer';
+
+function parseVersion(versionString: string) {
+ if (/^\d{3,4}$/.test(versionString)) {
+ // Env var doesn't always use dots. example: 4601 => 46.1.0
+ const m = /(\d{1,2})(\d{2})/.exec(versionString) || [];
+ return {
+ major: 0,
+ minor: parseInt(m[1] as string, 10),
+ patch: parseInt(m[2] as string, 10),
+ };
+ }
+
+ const versions = (versionString || '').split('.').map((n) => parseInt(n, 10));
+ return {
+ major: versions[0],
+ minor: versions[1],
+ patch: versions[2],
+ };
+}
+
+export function supportsHyperlink(): false | string {
+ const {
+ CI,
+ NETLIFY,
+ TEAMCITY_VERSION,
+ TERM_PROGRAM,
+ TERM_PROGRAM_VERSION,
+ VTE_VERSION,
+ } = process.env;
+
+ // Netlify does not run a TTY, it does not need `supportsColor` check
+ if (NETLIFY) {
+ return 'Click';
+ }
+
+ // If they specify no colors, they probably don't want hyperlinks.
+ if (!RenderInternals.isColorSupported()) {
+ return false;
+ }
+
+ if (process.platform === 'win32') {
+ return false;
+ }
+
+ if (CI) {
+ return false;
+ }
+
+ if (TEAMCITY_VERSION) {
+ return false;
+ }
+
+ if (TERM_PROGRAM) {
+ const version = parseVersion(TERM_PROGRAM_VERSION || '');
+
+ switch (TERM_PROGRAM) {
+ case 'iTerm.app':
+ if (version.major === 3) {
+ return (version.minor as number) >= 1 ? 'Cmd+Click' : false;
+ }
+
+ return (version.major as number) > 3 ? 'Cmd+Click' : false;
+ case 'WezTerm':
+ return (version.major as number) >= 20200620 ? 'Click' : false;
+ case 'vscode':
+ // Cursor is at v0
+ if (version.major === 0) {
+ return process.platform === 'darwin' ? 'Option+Click' : 'Ctrl+Click';
+ }
+
+ return (version.major as number) > 1 ||
+ (version.major === 1 && (version.minor as number) >= 72)
+ ? process.platform === 'darwin'
+ ? 'Option+Click'
+ : 'Ctrl+Click'
+ : false;
+ // No default
+ }
+ }
+
+ if (VTE_VERSION) {
+ // 0.50.0 was supposed to support hyperlinks, but throws a segfault
+ if (VTE_VERSION === '0.50.0') {
+ return false;
+ }
+
+ const version = parseVersion(VTE_VERSION);
+ return (version.major as number) > 0 || (version.minor as number) >= 50
+ ? 'Click'
+ : false;
+ }
+
+ return false;
+}
diff --git a/packages/studio-server/src/hyperlinks/make-link.ts b/packages/studio-server/src/hyperlinks/make-link.ts
new file mode 100644
index 0000000000..4398f1ed04
--- /dev/null
+++ b/packages/studio-server/src/hyperlinks/make-link.ts
@@ -0,0 +1,26 @@
+import {supportsHyperlink} from './is-supported';
+
+const OSC = '\u001B]';
+const SEP = ';';
+const BEL = '\u0007';
+
+export const makeHyperlink = ({
+ text,
+ url,
+ fallback,
+}: {
+ text: string | ((clickInstruction: string) => string);
+ url: string;
+ fallback: string;
+}) => {
+ const supports = supportsHyperlink();
+ if (!supports) {
+ return fallback;
+ }
+
+ const label = typeof text === 'function' ? text(supports) : text;
+
+ return [OSC, '8', SEP, SEP, url, BEL, label, OSC, '8', SEP, SEP, BEL].join(
+ '',
+ );
+};
diff --git a/packages/studio-server/src/preview-server/hmr-suppression.ts b/packages/studio-server/src/preview-server/hmr-suppression.ts
new file mode 100644
index 0000000000..51b2a435a5
--- /dev/null
+++ b/packages/studio-server/src/preview-server/hmr-suppression.ts
@@ -0,0 +1,18 @@
+const suppressedFiles = new Set<string>();
+
+export function suppressHmrForFile(absolutePath: string) {
+ suppressedFiles.add(absolutePath);
+}
+
+export function shouldSuppressHmr(filename: string | null): boolean {
+ if (filename === null) {
+ return false;
+ }
+
+ if (suppressedFiles.has(filename)) {
+ suppressedFiles.delete(filename);
+ return true;
+ }
+
+ return false;
+}
diff --git a/packages/studio-server/src/preview-server/hot-middleware/index.tsx b/packages/studio-server/src/preview-server/hot-middleware/index.tsx
index 269ecabe3f..ac0387ba57 100644
--- a/packages/studio-server/src/preview-server/hot-middleware/index.tsx
+++ b/packages/studio-server/src/preview-server/hot-middleware/index.tsx
@@ -11,6 +11,7 @@ import type {LogLevel} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
import type {HotMiddlewareMessage, ModuleMap} from '@remotion/studio-shared';
import {hotMiddlewareOptions} from '@remotion/studio-shared';
+import {shouldSuppressHmr} from '../hmr-suppression';
import type {WebpackStats} from './types';
declare global {
@@ -136,11 +137,19 @@ export const webpackHotMiddleware = (
hotMiddlewareOptions.heartbeat,
);
let latestStats: webpack.Stats | null = null;
+ let currentBuildSuppressed = false;
compiler.hooks.invalid.tap('remotion', onInvalid);
compiler.hooks.done.tap('remotion', onDone);
- function onInvalid() {
+ function onInvalid(filename: string | null) {
+ if (shouldSuppressHmr(filename)) {
+ currentBuildSuppressed = true;
+ latestStats = null;
+ return;
+ }
+
+ currentBuildSuppressed = false;
latestStats = null;
RenderInternals.Log.info({indent: false, logLevel}, 'Building...');
eventStream?.publish({
@@ -152,6 +161,13 @@ export const webpackHotMiddleware = (
// Keep hold of latest stats so they can be propagated to new clients
latestStats = statsResult;
+ if (currentBuildSuppressed) {
+ // Still send the "built" event so the client hash stays in sync,
+ // but skip the "building" spinner. This avoids accumulating
+ // a large HMR delta for the next real build.
+ currentBuildSuppressed = false;
+ }
+
publishStats('built', latestStats, eventStream);
}
diff --git a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts
index c381e5b163..f0cf4e0ef0 100644
--- a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts
+++ b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts
@@ -1,18 +1,22 @@
import {readFileSync, writeFileSync} from 'node:fs';
import path from 'node:path';
+import {RenderInternals} from '@remotion/renderer';
import type {
SaveSequencePropsRequest,
SaveSequencePropsResponse,
} from '@remotion/studio-shared';
import {updateSequenceProps} from '../../codemods/update-sequence-props';
+import {makeHyperlink} from '../../hyperlinks/make-link';
import type {ApiHandler} from '../api-types';
+import {suppressHmrForFile} from '../hmr-suppression';
export const saveSequencePropsHandler: ApiHandler<
SaveSequencePropsRequest,
SaveSequencePropsResponse
> = async ({
- input: {fileName, line, column: _column, key, value, enumPaths},
+ input: {fileName, line, column, key, value, enumPaths},
remotionRoot,
+ logLevel,
}) => {
try {
const absolutePath = path.resolve(remotionRoot, fileName);
@@ -23,7 +27,7 @@ export const saveSequencePropsHandler: ApiHandler<
const fileContents = readFileSync(absolutePath, 'utf-8');
- const updated = await updateSequenceProps({
+ const {output, oldValueString} = await updateSequenceProps({
input: fileContents,
targetLine: line,
key,
@@ -31,7 +35,22 @@ export const saveSequencePropsHandler: ApiHandler<
enumPaths,
});
- writeFileSync(absolutePath, updated);
+ suppressHmrForFile(absolutePath);
+ writeFileSync(absolutePath, output);
+
+ const newValueString = JSON.stringify(JSON.parse(value));
+ const locationLabel = `${fileRelativeToRoot}:${line}:${column}`;
+ const fileLink = makeHyperlink({
+ url: `file://${absolutePath}`,
+ text: locationLabel,
+ fallback: locationLabel,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ RenderInternals.chalk.blueBright(
+ `${fileLink} updated: ${key} ${oldValueString} \u2192 ${newValueString}`,
+ ),
+ );
return {
success: true,