summaryrefslogtreecommitdiff
path: root/apps/web/src/lib/timeline/placement/insert-index.ts
blob: 04fa5a4a2a73098156e47159d69d1fdc6ac09b03 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import type { SceneTracks, TrackType } from "@/lib/timeline";

export function getDefaultInsertIndexForTrack({
	tracks,
	trackType,
}: {
	tracks: SceneTracks;
	trackType: TrackType;
}): number {
	if (trackType === "audio") {
		return tracks.overlay.length + 1 + tracks.audio.length;
	}

	if (trackType === "effect") {
		return 0;
	}

	return tracks.overlay.length;
}

export function getHighestInsertIndexForTrack({
	tracks,
	trackType,
}: {
	tracks: SceneTracks;
	trackType: TrackType;
}): number {
	if (trackType === "audio") {
		return tracks.overlay.length + 1;
	}

	return 0;
}

export function resolvePreferredNewTrackPlacement({
	tracks,
	trackType,
	preferredIndex,
	direction,
}: {
	tracks: SceneTracks;
	trackType: TrackType;
	preferredIndex: number;
	direction: "above" | "below";
}): { insertIndex: number; insertPosition: "above" | "below" | null } {
	const trackCount = tracks.overlay.length + 1 + tracks.audio.length;
	if (trackCount === 0) {
		return {
			insertIndex: 0,
			insertPosition: trackType === "audio" ? "below" : null,
		};
	}

	const safePreferredIndex = Math.min(
		Math.max(preferredIndex, 0),
		trackCount - 1,
	);
	const mainTrackIndex = tracks.overlay.length;

	if (trackType === "audio") {
		if (safePreferredIndex <= mainTrackIndex) {
			return {
				insertIndex: mainTrackIndex + 1,
				insertPosition: "below",
			};
		}

		return {
			insertIndex:
				direction === "above" ? safePreferredIndex : safePreferredIndex + 1,
			insertPosition: direction,
		};
	}

	const insertIndex =
		direction === "above" ? safePreferredIndex : safePreferredIndex + 1;
	if (mainTrackIndex >= 0 && insertIndex > mainTrackIndex) {
		return {
			insertIndex: mainTrackIndex,
			insertPosition: "above",
		};
	}

	return {
		insertIndex,
		insertPosition: direction,
	};
}