Skip to content

🎥 Make videos programmatically with React

Test subscription and inspector continuity across source refreshes

JonnyBurger88dee809e661
diff --git a/packages/studio/src/test/source-subscription-churn.test.tsx b/packages/studio/src/test/source-subscription-churn.test.tsx
index a079576b50..6453d8160c 100644
--- a/packages/studio/src/test/source-subscription-churn.test.tsx
+++ b/packages/studio/src/test/source-subscription-churn.test.tsx
@@ -6,7 +6,7 @@ import type {
UnsubscribeFromSequencePropsBatchRequest,
UnsubscribeFromSequencePropsRequest,
} from '@remotion/studio-shared';
-import {act, render, waitFor} from '@testing-library/react';
+import {act, fireEvent, render, waitFor} from '@testing-library/react';
import {useContext, useState, type ContextType} from 'react';
import {
Internals,
@@ -14,31 +14,33 @@ import {
interpolate,
useCurrentFrame,
useVideoConfig,
+ type TSequence,
} from 'remotion';
import {ExpandedTracksProvider} from '../components/ExpandedTracksProvider';
import {SequencePropsSubscriptionProvider} from '../components/SequencePropsSubscriptionProvider';
import {shouldSubscribeToSequenceProps} from '../components/Timeline/should-subscribe-to-sequence-props';
import {SubscribeToNodePaths} from '../components/Timeline/SubscribeToNodePaths';
+import {useResolveStackAndReactToChange} from '../components/Timeline/use-resolved-stack-react-to-change';
import {StudioServerConnectionCtx} from '../helpers/client-id';
const fileName = __filename;
const source = readFileSync(fileName, 'utf8').split('\ntest(')[0];
-let sourceLineOffset = 0;
+let generatedSourceUrl: string | null = null;
// Supply the source locations normally injected by the Studio bundler. The
// subscription parser reads the same JSX that React mounts below.
const sourceProps = (name: string) => {
const attribute = source.indexOf('name="' + name + '"');
const opening = source.lastIndexOf('<Sequence', attribute);
+ const lineNumber = source.slice(0, opening).split('\n').length;
return {
- [Internals.REMOTION_INTERNAL_STACK_PROP]: Internals.makeOriginalSourceStack(
- {
- fileName,
- lineNumber:
- source.slice(0, opening).split('\n').length + sourceLineOffset,
- columnNumber: 0,
- },
- ),
+ [Internals.REMOTION_INTERNAL_STACK_PROP]: generatedSourceUrl
+ ? `Error\n at Sequence (${generatedSourceUrl}:${lineNumber}:1)`
+ : Internals.makeOriginalSourceStack({
+ fileName,
+ lineNumber,
+ columnNumber: 0,
+ }),
};
};
@@ -91,6 +93,8 @@ test('parent previews keep source subscriptions stable while mounted instances e
typeof CodemodsInternals.computeSequencePropsSubscriptionFromContent
>[] = [];
let subscriptionSource = source;
+ const refreshedSourceUrl = `http://localhost/source-subscription-${crypto.randomUUID()}.js`;
+ let resolveSourceMap: (() => void) | null = null;
let refreshFixture: () => void = () => {
throw new Error('Fixture has not mounted');
};
@@ -111,6 +115,26 @@ test('parent previews keep source subscriptions stable while mounted instances e
globalThis.fetch = ((input, init) => {
const endpoint = String(input);
requests.push(endpoint);
+ if (endpoint === `${refreshedSourceUrl}.map`) {
+ return new Promise<Response>((resolve) => {
+ resolveSourceMap = () =>
+ resolve(
+ Response.json({
+ version: 3,
+ sources: [fileName],
+ sourcesContent: [subscriptionSource],
+ names: [],
+ // Map the first line two lines down, then advance one line
+ // in the original source for every generated line.
+ mappings: source
+ .split('\n')
+ .map((_, index) => (index === 0 ? 'AAEA' : 'AACA'))
+ .join(';'),
+ }),
+ );
+ });
+ }
+
if (endpoint === '/api/unsubscribe-from-sequence-props') {
const unsubscribeBody = JSON.parse(
String(init?.body),
@@ -142,20 +166,49 @@ test('parent previews keep source subscriptions stable while mounted instances e
return Promise.resolve(Response.json({success: true, data: {results}}));
}) as typeof fetch;
+ // Exercise the same shared location hook and conditional source controls as
+ // the inspector, without depending on browser layout to detect a remount.
+ const SourceInspector = ({sequence}: {readonly sequence: TSequence}) => {
+ const {resolvedLocation} = useResolveStackAndReactToChange(
+ sequence.getStack,
+ sequence.controls?.overrideId ?? sequence.id,
+ );
+ return resolvedLocation ? (
+ <fieldset>
+ <legend>Source controls</legend>
+ <label>
+ Inspector draft
+ <input defaultValue="Parent" />
+ </label>
+ <output aria-label="Source line">{resolvedLocation.line}</output>
+ </fieldset>
+ ) : null;
+ };
+
const Subscriptions = () => {
const sequences = Internals.useSequenceManagerSequences();
setters.current = useContext(Internals.VisualModeSettersContext);
- return sequences.map((sequence) =>
- shouldSubscribeToSequenceProps(sequence, true) ? (
- <SubscribeToNodePaths
- key={sequence.id}
- overrideId={sequence.controls.overrideId}
- componentIdentity={sequence.controls.componentIdentity}
- schema={sequence.controls.schema}
- getStack={sequence.getStack}
- effects={sequence.effects}
- />
- ) : null,
+ const inspectedSequence = sequences.find(
+ (sequence) => sequence.displayName === 'Parent',
+ );
+ return (
+ <>
+ {sequences.map((sequence) =>
+ shouldSubscribeToSequenceProps(sequence, true) ? (
+ <SubscribeToNodePaths
+ key={sequence.id}
+ overrideId={sequence.controls.overrideId}
+ componentIdentity={sequence.controls.componentIdentity}
+ schema={sequence.controls.schema}
+ getStack={sequence.getStack}
+ effects={sequence.effects}
+ />
+ ) : null,
+ )}
+ {inspectedSequence ? (
+ <SourceInspector sequence={inspectedSequence} />
+ ) : null}
+ </>
);
};
@@ -322,14 +375,75 @@ test('parent previews keep source subscriptions stable while mounted instances e
expect(requests).toEqual(initialRequests);
// Registration can publish a shifted source stack without another refresh
- // event. Updating that stack must still refresh source props.
- sourceLineOffset = 2;
+ // event. While its source map is pending, keep source controls mounted but
+ // do not subscribe with the previous source location.
+ const inspectorDraft = rendered.getByRole('textbox', {
+ name: 'Inspector draft',
+ }) as HTMLInputElement;
+ const originalLine = rendered.getByRole('status', {
+ name: 'Source line',
+ }).textContent;
+ fireEvent.change(inspectorDraft, {target: {value: 'In-progress edit'}});
+ inspectorDraft.focus();
+ generatedSourceUrl = refreshedSourceUrl;
subscriptionSource = `\n\n${source}`;
- act(() => refreshFixture());
+ await act(async () => {
+ refreshFixture();
+ await Promise.resolve();
+ });
+ await waitFor(() => expect(resolveSourceMap).not.toBeNull());
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ expect(subscriptions).toHaveLength(4);
+ expect(rendered.getByRole('textbox', {name: 'Inspector draft'})).toBe(
+ inspectorDraft,
+ );
+ expect(inspectorDraft.value).toBe('In-progress edit');
+ expect(document.activeElement).toBe(inspectorDraft);
+ expect(
+ rendered.getByRole('status', {name: 'Source line'}).textContent,
+ ).toBe(originalLine);
+
+ await act(async () => {
+ resolveSourceMap!();
+ await Promise.resolve();
+ });
await waitFor(() =>
expect(rendered!.getByTestId('A').textContent).toBe('180'),
);
expect(rendered.getByTestId('B').textContent).toBe('200');
+ expect(
+ rendered.getByRole('status', {name: 'Source line'}).textContent,
+ ).toBe(String(Number(originalLine) + 2));
+ expect(rendered.getByRole('textbox', {name: 'Inspector draft'})).toBe(
+ inspectorDraft,
+ );
+ expect(inspectorDraft.value).toBe('In-progress edit');
+ expect(document.activeElement).toBe(inspectorDraft);
+ expect(subscriptions).toHaveLength(8);
+
+ // Returning to the cached compiler-provided stack must also resolve the
+ // original location immediately, without briefly using the shifted line.
+ generatedSourceUrl = null;
+ subscriptionSource = source;
+ await act(async () => {
+ refreshFixture();
+ await Promise.resolve();
+ });
+ await waitFor(() =>
+ expect(
+ rendered!.getByRole('status', {name: 'Source line'}).textContent,
+ ).toBe(originalLine),
+ );
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ expect(rendered.getByRole('textbox', {name: 'Inspector draft'})).toBe(
+ inspectorDraft,
+ );
+ expect(inspectorDraft.value).toBe('In-progress edit');
+ expect(document.activeElement).toBe(inspectorDraft);
} finally {
await act(async () => {
rendered?.unmount();
@@ -337,15 +451,15 @@ test('parent previews keep source subscriptions stable while mounted instances e
await new Promise((resolve) => setTimeout(resolve, 0));
});
globalThis.fetch = previousFetch;
- sourceLineOffset = 0;
+ generatedSourceUrl = null;
}
- // Four initial subscriptions and four refreshed subscriptions, without
- // transient subscriptions using the previous stack's source location.
- expect(subscriptions).toHaveLength(8);
+ // Four subscriptions per source version, without transient subscriptions
+ // using the previous stack's source location.
+ expect(subscriptions).toHaveLength(12);
expect(subscriptions.every((result) => result.success)).toBe(true);
- // Refresh cleanup and final unmount each send one batch, preserving every release.
- expect(unsubscriptionBatches).toHaveLength(2);
+ // Both refreshes and final unmount send one batch each, preserving every release.
+ expect(unsubscriptionBatches).toHaveLength(3);
expect(unsubscriptionBatches.at(-1)).toHaveLength(4);
expect(unsubscriptionBatches.flat()).toHaveLength(
subscriptions.filter((result) => result.success).length,