Skip to content

πŸŽ₯ Make videos programmatically with React

Fix Element Library first-load flicker and loading feedback

Igor Samokhovets74cb8856c895
diff --git a/packages/docs/docs/studio-protocol/is-inside-studio.mdx b/packages/docs/docs/studio-protocol/is-inside-studio.mdx
index 02a05bc248..331222d975 100644
--- a/packages/docs/docs/studio-protocol/is-inside-studio.mdx
+++ b/packages/docs/docs/studio-protocol/is-inside-studio.mdx
@@ -6,9 +6,7 @@ crumb: '@remotion/studio-protocol'
# isInsideStudio()<AvailableFrom v="4.0.518" />
-Returns whether the current website is loaded in the Element Library modal in Remotion Studio.
-
-Use it to adapt library UI that is redundant inside Studio, such as a "Drag into Studio" handle.
+Checks whether your site is in Studio's Element Library modal. Use it to hide redundant UI, such as a "Drag into Studio" handle.
## Example
@@ -27,15 +25,30 @@ export const ElementActions = () => {
};
```
-Starting with `null` prevents the action from briefly appearing before the browser check runs. On a top-level website, the action appears after the check.
+Starting with `null` hides the action until the check runs, preventing a flash. It then appears on top-level sites.
-## Return value
+## Avoiding flickering on the first load
+
+HTML painted before your client code runs can briefly show unnecessary UI inside Studio, such as a navbar or an Element drag handle.
+
+For request-time SSR, check `remotion-studio=true` in the request URL before rendering. Use the same result for the initial client render to avoid hydration mismatches. The server cannot detect the iframe.
-A boolean. It is `true` when the page has Studio's URL marker or is inside an iframe. The iframe check keeps the result true if client-side navigation removes the URL marker.
+For pre-rendered pages, or when you cannot adapt HTML on the server, put an inline script immediately after `<body>`, before the affected UI is parsed. In the browser, `isInsideStudio()` is equivalent to:
+
+```ts twoslash title="Before-paint check"
+if (
+ new URLSearchParams(window.location.search).get('remotion-studio') === 'true' ||
+ window.parent !== window
+) {
+ // Adapt your UI for Studio before it is painted.
+}
+```
+
+## Return value
-It returns `false` outside a browser, including during server-side rendering.
+Returns `true` when the URL contains `remotion-studio=true` or the page is inside any iframe, even if client-side navigation removes the marker. Returns `false` outside a browser, including during SSR, because there is no `window`.
-The result is a UI hint, not proof of Studio identity. Do not use it as a security boundary.
+This is a UI hint, not proof of Studio identity or a security boundary.
## Compatibility
diff --git a/packages/docs/docusaurus.config.ts b/packages/docs/docusaurus.config.ts
index 102073f2d7..349253732a 100644
--- a/packages/docs/docusaurus.config.ts
+++ b/packages/docs/docusaurus.config.ts
@@ -24,6 +24,22 @@ const fasterConfig = isVercel
const showGitLastUpdate =
process.env.REMOTION_DOCS_DISABLE_GIT_LAST_UPDATE !== '1';
+// Apply the class before the server-rendered layout is parsed so the docs
+// navigation cannot appear for one frame before React hydrates.
+const studioElementsEmbedScript = `
+(() => {
+ const pathname = window.location.pathname;
+ const isElementsPage =
+ pathname === '/elements' || pathname.startsWith('/elements/');
+ const isInsideStudio =
+ new URLSearchParams(window.location.search).get('remotion-studio') ===
+ 'true' || window.parent !== window;
+
+ if (isElementsPage && isInsideStudio) {
+ document.body.classList.add('studio-elements-embed');
+ }
+})();`;
+
const config: Config = {
title: 'Remotion | Make videos programmatically',
tagline: 'Make videos programmatically',
@@ -348,6 +364,17 @@ const config: Config = {
],
],
plugins: [
+ () => ({
+ name: 'mark-studio-elements-embed-before-paint',
+ injectHtmlTags: () => ({
+ preBodyTags: [
+ {
+ tagName: 'script',
+ innerHTML: studioElementsEmbedScript,
+ },
+ ],
+ }),
+ }),
// MapLibre's worker fallback uses a dynamic URL even when setWorkerUrl() is called.
() => ({
name: 'ignore-maplibre-worker-warning',
diff --git a/packages/docs/src/components/Elements/ElementLibrary.tsx b/packages/docs/src/components/Elements/ElementLibrary.tsx
index d90d0e57ed..6a62becea0 100644
--- a/packages/docs/src/components/Elements/ElementLibrary.tsx
+++ b/packages/docs/src/components/Elements/ElementLibrary.tsx
@@ -1,3 +1,4 @@
+import Link from '@docusaurus/Link';
import {setStudioDragData} from '@remotion/studio-protocol';
import React, {useEffect, useRef, useState} from 'react';
import {BlueButton} from '../../../components/layout/Button';
@@ -115,10 +116,10 @@ const ElementCard: React.FC<{
onPointerEnter={activateFromPointer}
onPointerLeave={() => setIsPointerOver(false)}
>
- <a
+ <Link
className={styles.card}
draggable
- href={getElementDocumentationUrl(definition)}
+ to={getElementDocumentationUrl(definition)}
onBlur={() => setIsFocused(false)}
onFocus={() => {
setPlaybackFailed(false);
@@ -167,7 +168,7 @@ const ElementCard: React.FC<{
<div className={styles.content}>
<span className={styles.title}>{definition.displayName}</span>
</div>
- </a>
+ </Link>
<div aria-live="polite" className={styles.installAction}>
<BlueButton
aria-label={`Use – ${definition.displayName}`}
diff --git a/packages/docs/src/test/elements.test.ts b/packages/docs/src/test/elements.test.ts
index 5538af87e5..ee1f1637e5 100644
--- a/packages/docs/src/test/elements.test.ts
+++ b/packages/docs/src/test/elements.test.ts
@@ -1,4 +1,4 @@
-import {describe, expect, test} from 'bun:test';
+import {describe, expect, mock, test} from 'bun:test';
import {existsSync, readdirSync, readFileSync, statSync} from 'fs';
import {createRequire} from 'module';
import path from 'path';
@@ -24,10 +24,15 @@ import {
getElementDefinition,
getElementDimensionsLabel,
} from '../components/Elements/element-utils';
-import {ElementLibrary} from '../components/Elements/ElementLibrary';
import {getElementPreviewDimensions} from '../components/Elements/ElementPreviewComposition';
import {Seo} from '../components/Seo';
+// Docusaurus generates this alias at build time. These checks only inspect SSR markup.
+mock.module('@docusaurus/Link', () => ({
+ default: ({to, ...props}: React.ComponentProps<'a'> & {to: string}) =>
+ React.createElement('a', {...props, href: to}),
+}));
+
const elementsRoot = path.join(__dirname, '..', '..', 'elements');
const templateRoot = path.join(__dirname, '..', '..', 'elements-template');
const staticElementsRoot = path.join(
@@ -297,7 +302,9 @@ describe('Element Library', () => {
).toThrow('Missing source pages: missing/source.');
});
- test('renders cards and filters the real category entry points', () => {
+ test('renders cards and filters the real category entry points', async () => {
+ const {ElementLibrary} =
+ await import('../components/Elements/ElementLibrary');
const sourceCodeBySlug = getRemotionElementSourceMap({elementsRoot});
const overviewMarkup = renderToStaticMarkup(
React.createElement(ElementLibrary, {
diff --git a/packages/studio/src/components/ElementLibraryModal.tsx b/packages/studio/src/components/ElementLibraryModal.tsx
index 80c972cf52..abd6ca20ad 100644
--- a/packages/studio/src/components/ElementLibraryModal.tsx
+++ b/packages/studio/src/components/ElementLibraryModal.tsx
@@ -1,4 +1,10 @@
-import React, {useCallback, useContext, useLayoutEffect, useRef} from 'react';
+import React, {
+ useCallback,
+ useContext,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react';
import {GearIcon} from '../icons/gear';
import {
type ElementInstallModalState,
@@ -11,6 +17,7 @@ import {InlineAction} from './InlineAction';
import {getMaxModalHeight, getMaxModalWidth} from './ModalContainer';
import {ModalHeader} from './ModalHeader';
import {DismissableModal} from './NewComposition/DismissableModal';
+import {Spinner} from './Spinner';
const panelStyle: React.CSSProperties = {
display: 'flex',
@@ -20,20 +27,36 @@ const panelStyle: React.CSSProperties = {
width: getMaxModalWidth(1400),
};
+const contentStyle: React.CSSProperties = {
+ flex: 1,
+ minHeight: 0,
+ position: 'relative',
+};
+
const iframeStyle: React.CSSProperties = {
border: 0,
colorScheme: 'dark',
- flex: 1,
- minHeight: 0,
+ height: '100%',
+ inset: 0,
+ position: 'absolute',
width: '100%',
};
+const loadingStyle: React.CSSProperties = {
+ alignItems: 'center',
+ display: 'flex',
+ inset: 0,
+ justifyContent: 'center',
+ position: 'absolute',
+};
+
export const ElementLibraryModal: React.FC<{
readonly name: string;
readonly url: string;
readonly installState: ElementInstallModalState | null;
}> = ({name, url, installState}) => {
const iframeRef = useRef<HTMLIFrameElement>(null);
+ const [isLoaded, setIsLoaded] = useState(false);
const {setSelectedModal} = useContext(SetSelectedModalContext);
const openElementSettings = useCallback(() => {
setSelectedModal({
@@ -54,6 +77,10 @@ export const ElementLibraryModal: React.FC<{
return;
}
+ setIsLoaded(false);
+ const onLoad = () => setIsLoaded(true);
+ iframe.addEventListener('load', onLoad);
+
// Studio is cross-origin isolated. A credentialless iframe may embed a
// library that does not set Cross-Origin-Resource-Policy headers.
iframe.setAttribute('credentialless', '');
@@ -61,6 +88,10 @@ export const ElementLibraryModal: React.FC<{
iframeUrl.searchParams.set('remotion-studio', 'true');
iframeUrl.searchParams.set('docusaurus-theme', 'dark');
iframe.src = iframeUrl.toString();
+
+ return () => {
+ iframe.removeEventListener('load', onLoad);
+ };
}, [url]);
return (
@@ -83,13 +114,27 @@ export const ElementLibraryModal: React.FC<{
</ActionTooltip>
}
/>
- <iframe
- ref={iframeRef}
- allow="local-network-access; loopback-network"
- data-remotion-element-library=""
- style={iframeStyle}
- aria-label={`${name} library`}
- />
+ <div style={contentStyle}>
+ <iframe
+ ref={iframeRef}
+ allow="local-network-access; loopback-network"
+ data-remotion-element-library=""
+ style={{
+ ...iframeStyle,
+ visibility: isLoaded ? 'visible' : 'hidden',
+ }}
+ aria-label={`${name} library`}
+ />
+ {isLoaded ? null : (
+ <div
+ style={loadingStyle}
+ role="status"
+ aria-label={`Loading ${name}`}
+ >
+ <Spinner duration={0.5} size={24} />
+ </div>
+ )}
+ </div>
{installState === null ? null : (
<ElementInstallConfirmation state={installState} />
)}