Skip to content

🎥 Make videos programmatically with React

fix(studio): keep nested hidden clip trims live

JonnyBurgerb537eb6d7504
diff --git a/packages/core/src/SequenceManager.tsx b/packages/core/src/SequenceManager.tsx
index 6fd5de63f6..56f34f2f6e 100644
--- a/packages/core/src/SequenceManager.tsx
+++ b/packages/core/src/SequenceManager.tsx
@@ -30,6 +30,7 @@ import type {VideoConfigValues} from './video-config.js';
const useIsomorphicLayoutEffect =
typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;
+const useCommitEffect = React.useInsertionEffect ?? useIsomorphicLayoutEffect;
export type VisualModePropStatuses = {
propStatuses: PropStatuses;
@@ -243,24 +244,32 @@ const defaultVisualModeDragOverrides: VisualModeDragOverrides = {
export const VisualModeDragOverridesContext =
React.createContext<VisualModeDragOverrides>(defaultVisualModeDragOverrides);
-const InactiveVisualModeDragOverridesContext =
- React.createContext<VisualModeDragOverrides>(defaultVisualModeDragOverrides);
-
export const VisualModeDragOverridesRefContext = React.createContext<
React.RefObject<VisualModeDragOverrides>
>({current: defaultVisualModeDragOverrides});
+const useDragOverrideSnapshot = <T,>(
+ subscribe: (listener: () => void) => () => void,
+ getSnapshot: () => T,
+): T => {
+ const dormant = useContext(SequenceActivityDormantContext);
+ const [, forceUpdate] = useState(0);
+ const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+ useCommitEffect(() => {
+ if (!dormant) {
+ return;
+ }
+
+ // Activity disconnects passive subscriptions, including useSyncExternalStore.
+ // Insertion effects stay connected through nested hidden Activities.
+ return subscribe(() => forceUpdate((current) => current + 1));
+ }, [dormant, subscribe]);
+ return snapshot;
+};
+
export const useDragOverridesForNodePath = (
nodePath: SequencePropsSubscriptionKey | null,
): Record<string, DragOverrideValue> => {
- const dormant = useContext(SequenceActivityDormantContext);
- // Hidden Activities disconnect external-store subscriptions. Context updates
- // still schedule their renders, allowing them to read the latest snapshot.
- useContext(
- dormant
- ? VisualModeDragOverridesContext
- : InactiveVisualModeDragOverridesContext,
- );
const subscription = useContext(VisualModeDragOverridesSubscriptionContext);
const manager = useContext(SequenceManagerActionsContext);
const scopedSubscription =
@@ -276,7 +285,7 @@ export const useDragOverridesForNodePath = (
() => scopedSubscription?.getSnapshot(key) ?? emptyDragOverrides,
[key, scopedSubscription],
);
- return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+ return useDragOverrideSnapshot(subscribe, getSnapshot);
};
export const useActiveFromDragOverrideKeys = (): ReadonlySet<string> => {
@@ -288,12 +297,6 @@ export const useActiveFromDragOverrideKeys = (): ReadonlySet<string> => {
export const useEffectDragOverridesForNodePath = (
nodePath: SequencePropsSubscriptionKey | null,
): Record<string, Record<string, DragOverrideValue>> => {
- const dormant = useContext(SequenceActivityDormantContext);
- useContext(
- dormant
- ? VisualModeDragOverridesContext
- : InactiveVisualModeDragOverridesContext,
- );
const subscription = useContext(VisualModeDragOverridesSubscriptionContext);
const manager = useContext(SequenceManagerActionsContext);
const scopedSubscription =
@@ -310,7 +313,7 @@ export const useEffectDragOverridesForNodePath = (
scopedSubscription?.getEffectSnapshot(key) ?? emptyEffectDragOverrides,
[key, scopedSubscription],
);
- return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+ return useDragOverrideSnapshot(subscribe, getSnapshot);
};
export const VisualModeSettersContext = React.createContext<VisualModeSetters>({
diff --git a/packages/example/e2e/hidden-clip-drag-preview.test.mts b/packages/example/e2e/hidden-clip-drag-preview.test.mts
new file mode 100644
index 0000000000..1ac6fed042
--- /dev/null
+++ b/packages/example/e2e/hidden-clip-drag-preview.test.mts
@@ -0,0 +1,99 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import {expect, test} from '@playwright/test';
+import {EXPANDED_SIDEBAR_STATE, STUDIO_URL, exampleDir} from './constants.mts';
+import {startStudio, stopStudio} from './studio-server.mts';
+
+test.use({
+ storageState: EXPANDED_SIDEBAR_STATE,
+ viewport: {width: 1920, height: 1200},
+});
+
+test('hidden video clips update throughout a left trim, including trimmed nested scenes', async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const fixture = path.join(exampleDir, 'src', 'HiddenClipDragPreview.tsx');
+ const original = fs.readFileSync(fixture, 'utf8');
+
+ try {
+ await startStudio();
+ await page.goto(`${STUDIO_URL}/hidden-clip-drag-preview`);
+ await expect(
+ page
+ .getByRole('group', {name: 'Nested hidden clip', exact: true})
+ .filter({has: page.getByRole('separator')}),
+ ).toBeVisible({timeout: 30_000});
+ await page.keyboard.press('g');
+ await page.locator('input:focus').fill('90');
+ await page.locator('input:focus').press('Enter');
+ await expect(
+ page.getByRole('button', {name: '90', exact: true}),
+ ).toBeVisible();
+ await page.keyboard.press('g');
+ await page.locator('input:focus').fill('150');
+ await page.locator('input:focus').press('Enter');
+
+ // One clip is in a future scene. The other has just become hidden and
+ // inherits a source trim from its Series.Sequence parent.
+ for (const {name, sourceStart} of [
+ {name: 'Hidden clip', sourceStart: 0},
+ {name: 'Nested hidden clip', sourceStart: 30},
+ ]) {
+ const start = page.getByRole('separator', {
+ name: 'Drag to trim start',
+ exact: true,
+ });
+ const clip = page
+ .getByRole('group', {name, exact: true})
+ .filter({has: start});
+ await expect(clip).toBeVisible({timeout: 30_000});
+ const initial = await clip.boundingBox();
+ const handle = await clip
+ .getByRole('separator', {name: 'Drag to trim start', exact: true})
+ .boundingBox();
+ if (initial === null || handle === null) {
+ throw new Error('Expected the hidden clip and its left trim handle');
+ }
+
+ const sourceBeforeDrag = fs.readFileSync(fixture, 'utf8');
+ const pixelsPerFrame = initial.width / 90;
+ const x = handle.x + handle.width / 2;
+ const y = handle.y + handle.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ for (const delta of [10, 20]) {
+ await page.mouse.move(x + pixelsPerFrame * delta, y, {steps: 5});
+ await expect
+ .poll(async () => {
+ const current = await clip.boundingBox();
+ return current === null
+ ? null
+ : {
+ startDelta: Math.round(
+ (current.x - initial.x) / pixelsPerFrame,
+ ),
+ duration: Math.round(current.width / pixelsPerFrame),
+ };
+ })
+ .toEqual({startDelta: delta, duration: 90 - delta});
+ }
+
+ // The preview must work before the source edit or its hot reload.
+ expect(fs.readFileSync(fixture, 'utf8')).toBe(sourceBeforeDrag);
+ await page.mouse.up();
+ const expectedStart = sourceStart + 20;
+ await expect
+ .poll(() => fs.readFileSync(fixture, 'utf8'))
+ .toMatch(
+ new RegExp(
+ String.raw`name="${name}"[^]*?from=\{${expectedStart}\}\s+durationInFrames=\{70\}\s+trimBefore=\{${expectedStart}\}`,
+ ),
+ );
+ }
+ } finally {
+ await page.mouse.up();
+ await stopStudio();
+ fs.writeFileSync(fixture, original);
+ }
+});
diff --git a/packages/example/src/E2eTestRoot.tsx b/packages/example/src/E2eTestRoot.tsx
index 83a29c0b47..d95cfdfdd3 100644
--- a/packages/example/src/E2eTestRoot.tsx
+++ b/packages/example/src/E2eTestRoot.tsx
@@ -12,6 +12,7 @@ import {
ErrorOverlayRepro,
UnsymbolicatedErrorOverlayRepro,
} from './ErrorOverlayE2e/ErrorOverlayRepro';
+import {HiddenClipDragPreview} from './HiddenClipDragPreview';
import {HookOrderChangeE2e} from './HookOrderChangeE2e/HookOrderChangeRepro';
import {Issue8216} from './Issue8216/Issue8216';
import {LightLeakExample} from './LightLeak';
@@ -33,6 +34,14 @@ import {SequenceShiftRepro} from './VisualModeTests/SequenceShiftRepro';
export const E2eTestRoot: React.FC = () => {
return (
<>
+ <Composition
+ id="hidden-clip-drag-preview"
+ component={HiddenClipDragPreview}
+ durationInFrames={300}
+ fps={30}
+ width={1280}
+ height={720}
+ />
<Composition
id="SourceSubscriptionChurn"
component={SourceSubscriptionChurn}
diff --git a/packages/example/src/HiddenClipDragPreview.tsx b/packages/example/src/HiddenClipDragPreview.tsx
new file mode 100644
index 0000000000..6f8aec9602
--- /dev/null
+++ b/packages/example/src/HiddenClipDragPreview.tsx
@@ -0,0 +1,33 @@
+import {Video} from '@remotion/media';
+import React from 'react';
+import {Sequence, Series, staticFile} from 'remotion';
+
+export const HiddenClipDragPreview: React.FC = () => (
+ <>
+ <Sequence name="Hidden scene" from={180} durationInFrames={90}>
+ <Video
+ name="Hidden clip"
+ src={staticFile('demo_smpte_h264_aac.mp4')}
+ from={0}
+ durationInFrames={90}
+ trimBefore={0}
+ muted
+ />
+ </Sequence>
+ <Sequence name="Previously visible scene" from={60} durationInFrames={90}>
+ <Series>
+ <Series.Sequence
+ name="Trimmed scene"
+ trimBefore={30}
+ durationInFrames={90}
+ >
+ <Video
+ name="Nested hidden clip"
+ src={staticFile('demo_smpte_h264_aac.mp4')}
+ muted
+ />
+ </Series.Sequence>
+ </Series>
+ </Sequence>
+ </>
+);
diff --git a/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx b/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx
index d44fb4f220..6e44b9cd1b 100644
--- a/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx
@@ -1411,7 +1411,12 @@ export const getTimelineSequenceLeftEdgeDragTargets = ({
? ownTrimBefore
: trimsMedia
? (originalSequence.trimBefore ??
- Math.max(0, originalSequence.startMediaFrom))
+ Math.max(
+ 0,
+ // The media start already includes frames hidden by ancestors.
+ originalSequence.startMediaFrom -
+ hiddenStartInParentFrames * playbackRate,
+ ))
: (originalSequence.trimBefore ?? 0)) +
hiddenStartInParentFrames * playbackRate,
minimumDuration: getMinimumSequenceDuration({
@@ -2623,6 +2628,17 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
};
}, []);
+ const equalMediaTrimHandles =
+ edgeEnabled &&
+ edgeMode === 'self-trim' &&
+ secondaryAction === 'source-only' &&
+ !isTransitionSeries &&
+ !rollingEnabled &&
+ !touchingPrevious &&
+ transitionEndOffset === null;
+ const leftEdgeHandleInset = equalMediaTrimHandles
+ ? 8
+ : LEFT_EDGE_HANDLE_INSET;
const edgeStyle: React.CSSProperties = {
...baseStyle,
zIndex: isTransitionSeries ? 2 : baseStyle.zIndex,
@@ -2639,7 +2655,7 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
? 'min(10px, 12.5%)'
: edgeMode === 'source-only'
? `calc(${LEFT_EDGE_HANDLE_OUTSET}px + min(14px, 25%))`
- : `calc(${LEFT_EDGE_HANDLE_OUTSET}px + min(${LEFT_EDGE_HANDLE_INSET}px, 12.5%))`,
+ : `calc(${LEFT_EDGE_HANDLE_OUTSET}px + min(${leftEdgeHandleInset}px, 12.5%))`,
cursor:
edgeMode === 'head-trim'
? altKey && rollingEnabled
@@ -2669,13 +2685,13 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
: 'calc(min(2px, 12.5%) + min(10px, 12.5%))'
: touchingPrevious
? 'min(10px, 12.5%)'
- : 'min(4px, 12.5%)'
+ : `min(${leftEdgeHandleInset}px, 12.5%)`
: 0,
width:
transitionEndOffset !== null
? 10
: edgeEnabled
- ? 'min(10px, 12.5%)'
+ ? `min(${equalMediaTrimHandles ? 8 : 10}px, 12.5%)`
: 'min(14px, 25%)',
cursor:
secondaryAction === 'source-only' ? sourceOnlyCursor : trimBeforeCursor,