Skip to content

🎥 Make videos programmatically with React

@remotion/studio: Fix duplicated timeline rows flickering after deletion

Jonny Burgerbc3277db9a19
diff --git a/packages/example/e2e/studio.test.mts b/packages/example/e2e/studio.test.mts
index 7d0a580e09..b400c763fd 100644
--- a/packages/example/e2e/studio.test.mts
+++ b/packages/example/e2e/studio.test.mts
@@ -1441,9 +1441,11 @@ test.describe('visual mode', () => {
}
});
- test('should collapse programmatically duplicated timeline rows', async ({
+ test('should keep programmatically duplicated timeline rows collapsed across HMR', async ({
page,
}) => {
+ const barChartFile = path.join(exampleDir, 'src', 'BarChart.tsx');
+ const originalSource = fs.readFileSync(barChartFile, 'utf-8');
await page.addInitScript(() => {
window.localStorage.setItem(
'remotion.sidebarRightCollapsing',
@@ -1460,6 +1462,11 @@ test.describe('visual mode', () => {
.getByLabel('4 other programmatically duplicated instances are hidden'),
).toBeVisible({timeout: 15_000});
await expect(page.getByText('25% gridline', {exact: true})).toHaveCount(0);
+ const gridlineVisibilityToggle = firstGridline
+ .locator('..')
+ .locator('..')
+ .locator('[data-timeline-layer-eye]');
+ await expect(gridlineVisibilityToggle).toBeVisible({timeout: 15_000});
await firstGridline.click();
const duplicationLabel = page.getByText('5 instances', {
@@ -1486,6 +1493,99 @@ test.describe('visual mode', () => {
.locator('.__remotion-studio-menu-item')
.filter({hasText: 'Delete all'}),
).toBeVisible();
+
+ await page.keyboard.press('Escape');
+ await page.evaluate(() => {
+ const state = window as typeof window & {
+ timelineGroupingBadStates: Set<string>;
+ stopTimelineGroupingObserver: () => void;
+ };
+ state.timelineGroupingBadStates = new Set();
+ const recordTimelineGrouping = () => {
+ const timelineList = document.querySelector('[data-timeline-list]');
+ const exactTextDivs = [
+ ...(timelineList?.querySelectorAll('div') ?? []),
+ ].filter((element) => element.childNodes.length === 1);
+ const firstGridline = exactTextDivs.find(
+ (element) => element.textContent === '0% gridline',
+ );
+ if (
+ firstGridline &&
+ !firstGridline.parentElement?.querySelector(
+ '[aria-label="4 other programmatically duplicated instances are hidden"]',
+ )
+ ) {
+ state.timelineGroupingBadStates.add(
+ 'missing-gridline-duplicate-count',
+ );
+ }
+
+ for (const label of [
+ '25% gridline',
+ '50% gridline',
+ '75% gridline',
+ '100% gridline',
+ ]) {
+ if (exactTextDivs.some((element) => element.textContent === label)) {
+ state.timelineGroupingBadStates.add('expanded-gridline-duplicates');
+ }
+ }
+ };
+ let animationFrame = requestAnimationFrame(function sample() {
+ recordTimelineGrouping();
+ animationFrame = requestAnimationFrame(sample);
+ });
+ state.stopTimelineGroupingObserver = () =>
+ cancelAnimationFrame(animationFrame);
+ });
+
+ try {
+ const eyebrow = page.locator(
+ '[data-timeline-marquee-item][title="Eyebrow"]',
+ );
+ await eyebrow.click({button: 'right'});
+ await page
+ .locator('[data-remotion-menu-tree-id]')
+ .last()
+ .getByRole('button', {name: 'Delete', exact: true})
+ .click();
+
+ await expect
+ .poll(() => fs.readFileSync(barChartFile, 'utf-8'))
+ .not.toContain('name="Eyebrow"');
+ await expect(eyebrow).toHaveCount(0, {timeout: 30_000});
+ await expect(firstGridline).toBeVisible();
+ await expect(
+ firstGridline
+ .locator('..')
+ .getByLabel(
+ '4 other programmatically duplicated instances are hidden',
+ ),
+ ).toBeVisible();
+ await expect(page.getByText('25% gridline', {exact: true})).toHaveCount(
+ 0,
+ );
+ await expect(gridlineVisibilityToggle).toBeVisible({timeout: 30_000});
+
+ expect(
+ await page.evaluate(() => {
+ const state = window as typeof window & {
+ timelineGroupingBadStates: Set<string>;
+ stopTimelineGroupingObserver: () => void;
+ };
+ state.stopTimelineGroupingObserver();
+ return [...state.timelineGroupingBadStates];
+ }),
+ ).toEqual([]);
+
+ await page.getByRole('button', {name: /^Undo/}).click();
+ await expect
+ .poll(() => fs.readFileSync(barChartFile, 'utf-8'))
+ .toBe(originalSource);
+ await expect(eyebrow).toBeVisible({timeout: 30_000});
+ } finally {
+ fs.writeFileSync(barChartFile, originalSource);
+ }
});
test('should split the right-clicked clip at the playhead from either timeline surface', async ({
diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsx
index 48c80f2b80..6adc0b1eb6 100644
--- a/packages/studio/src/components/Timeline/Timeline.tsx
+++ b/packages/studio/src/components/Timeline/Timeline.tsx
@@ -23,7 +23,6 @@ import {isStudioInteractivityEnabled} from '../../helpers/interactivity-enabled'
import {useIsStill} from '../../helpers/is-current-selected-still';
import {useCachedCompositionComponentInfo} from '../../helpers/open-in-editor';
import {getStudioMaxTimelineTracks} from '../../helpers/studio-runtime-config';
-import {timelineSequenceNodePathToKey} from '../../helpers/timeline-node-path-key';
import {useSyncExternalStore} from '../../helpers/use-sync-external-store';
import {callApi} from '../call-api';
import {ContextMenu} from '../ContextMenu';
@@ -39,6 +38,10 @@ import {shouldShowTrackInTimeline} from './should-show-track-in-timeline';
import {shouldSubscribeToSequenceProps} from './should-subscribe-to-sequence-props';
import {SubscribeToNodePaths} from './SubscribeToNodePaths';
import {TimelineAssetDropFrameContext} from './timeline-asset-drop-context';
+import {
+ addTimelineDisplayGroups,
+ type TimelineTrackWithDisplayGroup,
+} from './timeline-display-groups';
import {timelineVerticalScroll} from './timeline-refs';
import {TimelineDragHandler} from './TimelineDragHandler';
import {TimelineHeightContainer} from './TimelineHeightContainer';
@@ -281,16 +284,18 @@ const TimelineInner: React.FC = () => {
const videoConfigIsNull = videoConfig === null;
- const timeline = useMemo((): TimelineTrackData[] => {
+ const timeline = useMemo((): TimelineTrackWithDisplayGroup[] => {
if (videoConfigIsNull) {
return [];
}
- return calculateTimeline({
- sequences,
- overrideIdsToNodePaths: overrideIdToNodePathMappings,
- compositions,
- });
+ return addTimelineDisplayGroups(
+ calculateTimeline({
+ sequences,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ compositions,
+ }),
+ );
}, [
sequences,
videoConfigIsNull,
@@ -322,20 +327,17 @@ const TimelineInner: React.FC = () => {
// Keep `filtered` complete so a future toggle can show every programmatic
// instance without recalculating the timeline or losing its instance index.
const collapsed = useMemo(() => {
- const seenNodePaths = new Set<string>();
+ const seenDisplayGroups = new Set<string>();
return filtered.filter((track) => {
- if (track.nodePathInfo === null) {
+ if (track.displayGroup === null) {
return true;
}
- const key = timelineSequenceNodePathToKey(
- track.nodePathInfo.sequenceSubscriptionKey,
- );
- if (seenNodePaths.has(key)) {
+ if (seenDisplayGroups.has(track.displayGroup.key)) {
return false;
}
- seenNodePaths.add(key);
+ seenDisplayGroups.add(track.displayGroup.key);
return true;
});
}, [filtered]);
diff --git a/packages/studio/src/components/Timeline/TimelineLayerChildren.tsx b/packages/studio/src/components/Timeline/TimelineLayerChildren.tsx
index ab40022405..30e7264d54 100644
--- a/packages/studio/src/components/Timeline/TimelineLayerChildren.tsx
+++ b/packages/studio/src/components/Timeline/TimelineLayerChildren.tsx
@@ -7,7 +7,6 @@ import React, {
} from 'react';
import type {TSequence} from 'remotion';
import {LIGHT_TEXT, TRANSPARENT, WHITE} from '../../helpers/colors';
-import type {TimelineTrackData} from '../../helpers/get-timeline-sequence-sort-key';
import {
FOCUS_VISIBLE_ONLY_CLASS_NAME,
HOVERABLE_CLASS_NAME,
@@ -15,6 +14,7 @@ import {
} from '../../helpers/hoverable';
import {toggleBooleanMapKey} from '../../helpers/persist-boolean-map';
import {timelineNodePathInfoToKey} from '../../helpers/timeline-node-path-key';
+import type {TimelineTrackWithDisplayGroup} from './timeline-display-groups';
import {TimelineCollapseToggle} from './TimelineCollapseToggle';
// Reserve the same space before and after children register or unregister.
@@ -41,7 +41,7 @@ export const TimelineLayerChildrenProvider =
TimelineLayerChildrenContext.Provider;
export const useTimelineLayerChildren = (
- tracks: TimelineTrackData[],
+ tracks: TimelineTrackWithDisplayGroup[],
sequences: TSequence[],
compositionId: string | null,
) => {
@@ -98,17 +98,19 @@ export const useTimelineLayerChildren = (
}
ancestors.set(track.sequence.id, parentIds);
- // Source identity survives remounts. For layers without source metadata,
- // use the structural position instead of the ephemeral sequence ID.
+ // Source identity survives remounts. While it is resolving, the stack
+ // gives interactive layers a stable display identity.
const identity = track.nodePathInfo
? ['source', timelineNodePathInfoToKey(track.nodePathInfo)]
- : [
- 'position',
- ...[...parentIds]
- .reverse()
- .concat(track.sequence.id)
- .map((id) => siblingIndices.get(id)),
- ];
+ : track.displayGroup
+ ? ['stack', track.displayGroup.key]
+ : [
+ 'position',
+ ...[...parentIds]
+ .reverse()
+ .concat(track.sequence.id)
+ .map((id) => siblingIndices.get(id)),
+ ];
keys.set(track.sequence.id, JSON.stringify([compositionId, identity]));
}
diff --git a/packages/studio/src/components/Timeline/TimelineList.tsx b/packages/studio/src/components/Timeline/TimelineList.tsx
index c117e2105e..f76140e499 100644
--- a/packages/studio/src/components/Timeline/TimelineList.tsx
+++ b/packages/studio/src/components/Timeline/TimelineList.tsx
@@ -31,6 +31,10 @@ const TimelineListTrack: React.FC<{
nodePathInfo={track.nodePathInfo}
keyframeDisplayOffset={track.keyframeDisplayOffset}
sequenceFrameOffset={track.sequenceFrameOffset}
+ numberOfHiddenDuplicates={Math.max(
+ 0,
+ (track.displayGroup?.numberOfSequences ?? 1) - 1,
+ )}
/>
);
});
@@ -39,7 +43,7 @@ export const TimelineList: React.FC = () => {
const {rows, tracksEnd, virtualItems} = useTimelineVirtualization();
return (
- <div style={{...container, height: tracksEnd}}>
+ <div data-timeline-list="true" style={{...container, height: tracksEnd}}>
{virtualItems.map((virtualItem) => (
<div
key={virtualItem.key}
diff --git a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
index ba3fd7375e..39748a8a8e 100644
--- a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
@@ -299,6 +299,7 @@ const TimelineSequenceItemInner: React.FC<{
readonly keyframeDisplayOffset: number;
readonly sequenceFrameOffset: number;
readonly siblingIndex: number;
+ readonly numberOfHiddenDuplicates: number;
}> = ({
afterDropLineOffset,
connectedCompositions,
@@ -308,6 +309,7 @@ const TimelineSequenceItemInner: React.FC<{
keyframeDisplayOffset,
sequenceFrameOffset,
siblingIndex,
+ numberOfHiddenDuplicates,
}) => {
const nodePath = nodePathInfo?.sequenceSubscriptionKey ?? null;
const {hovered, onPointerEnter, onPointerLeave} =
@@ -396,11 +398,6 @@ const TimelineSequenceItemInner: React.FC<{
sequence.displayName === '' && connectedCompositions.length === 1
? connectedCompositions[0].id
: displayName;
- const numberOfHiddenDuplicates = Math.max(
- 0,
- (nodePathInfo?.numberOfSequencesWithThisNodePath ?? 1) - 1,
- );
-
const canDeleteFromSource = Boolean(nodePath && validatedLocation?.source);
const nodePathKey = useMemo(
() =>
diff --git a/packages/studio/src/components/Timeline/TimelineVirtualization.tsx b/packages/studio/src/components/Timeline/TimelineVirtualization.tsx
index 030090ea6c..2845a94a2c 100644
--- a/packages/studio/src/components/Timeline/TimelineVirtualization.tsx
+++ b/packages/studio/src/components/Timeline/TimelineVirtualization.tsx
@@ -1,8 +1,8 @@
import {
defaultRangeExtractor,
type Range,
- type VirtualItem,
useVirtualizer,
+ type VirtualItem,
} from '@tanstack/react-virtual';
import React, {
createContext,
@@ -13,9 +13,9 @@ import React, {
useMemo,
useRef,
} from 'react';
-import type {TimelineTrackData} from '../../helpers/get-timeline-sequence-sort-key';
import {TIMELINE_ITEM_BORDER_BOTTOM} from '../../helpers/timeline-layout';
import {MAX_TIMELINE_TRACKS_NOTICE_HEIGHT} from './MaxTimelineTracks';
+import type {TimelineTrackWithDisplayGroup} from './timeline-display-groups';
import {timelineVerticalScroll} from './timeline-refs';
import {
getTimelineSequenceSelectionKey,
@@ -28,7 +28,7 @@ import {useTimelineTrackHeights} from './use-timeline-height';
export type TimelineVirtualRow = {
readonly afterDropLineOffset: number;
readonly siblingIndex: number;
- readonly track: TimelineTrackData;
+ readonly track: TimelineTrackWithDisplayGroup;
};
type TimelineVirtualizationContextValue = {
@@ -53,7 +53,7 @@ export const TimelineVirtualizationProvider: React.FC<{
readonly children: React.ReactNode;
readonly hasBeenCut: boolean;
readonly isStill: boolean;
- readonly timeline: readonly TimelineTrackData[];
+ readonly timeline: readonly TimelineTrackWithDisplayGroup[];
}> = ({children, hasBeenCut, isStill, timeline}) => {
const trackHeights = useTimelineTrackHeights({timeline});
const {revealRequest, selectedItems} = useTimelineSelection();
diff --git a/packages/studio/src/components/Timeline/timeline-display-groups.ts b/packages/studio/src/components/Timeline/timeline-display-groups.ts
new file mode 100644
index 0000000000..a982035d4d
--- /dev/null
+++ b/packages/studio/src/components/Timeline/timeline-display-groups.ts
@@ -0,0 +1,90 @@
+import type {TimelineTrackData} from '../../helpers/get-timeline-sequence-sort-key';
+import {timelineSequenceNodePathToKey} from '../../helpers/timeline-node-path-key';
+
+export type TimelineDisplayGroup = {
+ readonly key: string;
+ readonly numberOfSequences: number;
+};
+
+export type TimelineTrackWithDisplayGroup = TimelineTrackData & {
+ readonly displayGroup: TimelineDisplayGroup | null;
+};
+
+export const addTimelineDisplayGroups = (
+ tracks: readonly TimelineTrackData[],
+): TimelineTrackWithDisplayGroup[] => {
+ const stacksBySequenceId = new Map<string, string | null>();
+ const resolvedNodePathKeysByStack = new Map<string, Set<string>>();
+
+ for (const track of tracks) {
+ // Only controlled sequences can eventually resolve to a source node.
+ const stack =
+ track.sequence.controls === null ? null : track.sequence.getStack();
+ stacksBySequenceId.set(track.sequence.id, stack);
+
+ if (stack === null || track.nodePathInfo === null) {
+ continue;
+ }
+
+ const nodePathKey = `node-path:${timelineSequenceNodePathToKey(
+ track.nodePathInfo.sequenceSubscriptionKey,
+ )}`;
+ const nodePathKeys =
+ resolvedNodePathKeysByStack.get(stack) ?? new Set<string>();
+ nodePathKeys.add(nodePathKey);
+ resolvedNodePathKeysByStack.set(stack, nodePathKeys);
+ }
+
+ const displayKeys = tracks.map((track): string | null => {
+ if (track.nodePathInfo !== null) {
+ return `node-path:${timelineSequenceNodePathToKey(
+ track.nodePathInfo.sequenceSubscriptionKey,
+ )}`;
+ }
+
+ const stack = stacksBySequenceId.get(track.sequence.id) ?? null;
+ if (stack === null) {
+ return null;
+ }
+
+ const resolvedNodePathKeys = resolvedNodePathKeysByStack.get(stack);
+ if (resolvedNodePathKeys?.size === 1) {
+ const resolvedNodePathKey = resolvedNodePathKeys.values().next().value;
+ if (resolvedNodePathKey === undefined) {
+ throw new Error('Expected a resolved timeline node path key');
+ }
+
+ return resolvedNodePathKey;
+ }
+
+ // This identity is display-only. Source operations continue to require
+ // track.nodePathInfo.
+ return `stack:${stack}`;
+ });
+ const counts = new Map<string, number>();
+ for (const key of displayKeys) {
+ if (key !== null) {
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ }
+
+ return tracks.map((track, index) => {
+ const key = displayKeys[index];
+ if (key === null) {
+ return {...track, displayGroup: null};
+ }
+
+ const numberOfSequences = counts.get(key);
+ if (numberOfSequences === undefined) {
+ throw new Error('Expected a timeline display group count');
+ }
+
+ return {
+ ...track,
+ displayGroup: {
+ key,
+ numberOfSequences,
+ },
+ };
+ });
+};