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
89
90
91
92
93
94
95
96
97
98
99
|
import type { TrackType, TimelineTrack } from "@/lib/timeline";
import { isMainTrack } from "./main-track";
export function getDefaultInsertIndexForTrack({
tracks,
trackType,
}: {
tracks: TimelineTrack[];
trackType: TrackType;
}): number {
if (trackType === "audio") {
return tracks.length;
}
if (trackType === "effect") {
return 0;
}
const mainTrackIndex = tracks.findIndex((track) => isMainTrack(track));
if (mainTrackIndex >= 0) {
return mainTrackIndex;
}
const firstAudioTrackIndex = tracks.findIndex((track) => track.type === "audio");
if (firstAudioTrackIndex >= 0) {
return firstAudioTrackIndex;
}
return tracks.length;
}
export function getHighestInsertIndexForTrack({
tracks,
trackType,
}: {
tracks: TimelineTrack[];
trackType: TrackType;
}): number {
const mainTrackIndex = tracks.findIndex((track) => isMainTrack(track));
if (trackType === "audio") {
return mainTrackIndex >= 0 ? mainTrackIndex + 1 : tracks.length;
}
return 0;
}
export function resolvePreferredNewTrackPlacement({
tracks,
trackType,
preferredIndex,
direction,
}: {
tracks: TimelineTrack[];
trackType: TrackType;
preferredIndex: number;
direction: "above" | "below";
}): { insertIndex: number; insertPosition: "above" | "below" | null } {
if (tracks.length === 0) {
return {
insertIndex: 0,
insertPosition: trackType === "audio" ? "below" : null,
};
}
const safePreferredIndex = Math.min(
Math.max(preferredIndex, 0),
tracks.length - 1,
);
const mainTrackIndex = tracks.findIndex((track) => isMainTrack(track));
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,
};
}
|