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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
|
import { create } from "zustand";
import {
TrackType,
TimelineElement,
CreateTimelineElement,
TimelineTrack,
TextElement,
DragData,
sortTracksByOrder,
ensureMainTrack,
validateElementTrackCompatibility,
} from "@/types/timeline";
import { useEditorStore } from "./editor-store";
import {
useMediaStore,
getMediaAspectRatio,
type MediaItem,
} from "./media-store";
import { storageService } from "@/lib/storage/storage-service";
import { useProjectStore } from "./project-store";
import { generateUUID } from "@/lib/utils";
import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
import { toast } from "sonner";
// Helper function to manage element naming with suffixes
const getElementNameWithSuffix = (
originalName: string,
suffix: string
): string => {
// Remove existing suffixes to prevent accumulation
const baseName = originalName
.replace(/ \(left\)$/, "")
.replace(/ \(right\)$/, "")
.replace(/ \(audio\)$/, "")
.replace(/ \(split \d+\)$/, "");
return `${baseName} (${suffix})`;
};
interface TimelineStore {
// Private track storage
_tracks: TimelineTrack[];
history: TimelineTrack[][];
redoStack: TimelineTrack[][];
// Always returns properly ordered tracks with main track ensured
tracks: TimelineTrack[];
// Manual method if you need to force recomputation
getSortedTracks: () => TimelineTrack[];
// Snapping settings
snappingEnabled: boolean;
// Snapping actions
toggleSnapping: () => void;
// Ripple editing mode
rippleEditingEnabled: boolean;
toggleRippleEditing: () => void;
// Multi-selection
selectedElements: { trackId: string; elementId: string }[];
selectElement: (trackId: string, elementId: string, multi?: boolean) => void;
deselectElement: (trackId: string, elementId: string) => void;
clearSelectedElements: () => void;
setSelectedElements: (
elements: { trackId: string; elementId: string }[]
) => void;
// Drag state
dragState: {
isDragging: boolean;
elementId: string | null;
trackId: string | null;
startMouseX: number;
startElementTime: number;
clickOffsetTime: number;
currentTime: number;
};
setDragState: (dragState: Partial<TimelineStore["dragState"]>) => void;
startDrag: (
elementId: string,
trackId: string,
startMouseX: number,
startElementTime: number,
clickOffsetTime: number
) => void;
updateDragTime: (currentTime: number) => void;
endDrag: () => void;
// Actions
addTrack: (type: TrackType) => string;
insertTrackAt: (type: TrackType, index: number) => string;
removeTrack: (trackId: string) => void;
addElementToTrack: (trackId: string, element: CreateTimelineElement) => void;
removeElementFromTrack: (trackId: string, elementId: string) => void;
moveElementToTrack: (
fromTrackId: string,
toTrackId: string,
elementId: string
) => void;
updateElementTrim: (
trackId: string,
elementId: string,
trimStart: number,
trimEnd: number
) => void;
updateElementDuration: (
trackId: string,
elementId: string,
duration: number
) => void;
updateElementStartTime: (
trackId: string,
elementId: string,
startTime: number
) => void;
toggleTrackMute: (trackId: string) => void;
// Split operations for elements
splitElement: (
trackId: string,
elementId: string,
splitTime: number
) => string | null;
splitAndKeepLeft: (
trackId: string,
elementId: string,
splitTime: number
) => void;
splitAndKeepRight: (
trackId: string,
elementId: string,
splitTime: number
) => void;
separateAudio: (trackId: string, elementId: string) => string | null;
// Replace media for an element
replaceElementMedia: (
trackId: string,
elementId: string,
newFile: File
) => Promise<boolean>;
// Ripple editing functions
updateElementStartTimeWithRipple: (
trackId: string,
elementId: string,
newStartTime: number
) => void;
removeElementFromTrackWithRipple: (
trackId: string,
elementId: string
) => void;
// Computed values
getTotalDuration: () => number;
// History actions
undo: () => void;
redo: () => void;
pushHistory: () => void;
// Persistence actions
loadProjectTimeline: (projectId: string) => Promise<void>;
saveProjectTimeline: (projectId: string) => Promise<void>;
clearTimeline: () => void;
updateTextElement: (
trackId: string,
elementId: string,
updates: Partial<
Pick<
TextElement,
| "content"
| "fontSize"
| "fontFamily"
| "color"
| "backgroundColor"
| "textAlign"
| "fontWeight"
| "fontStyle"
| "textDecoration"
| "x"
| "y"
| "rotation"
| "opacity"
>
>
) => void;
checkElementOverlap: (
trackId: string,
startTime: number,
duration: number,
excludeElementId?: string
) => boolean;
findOrCreateTrack: (trackType: TrackType) => string;
addMediaAtTime: (item: MediaItem, currentTime?: number) => boolean;
addTextAtTime: (item: TextElement, currentTime?: number) => boolean;
addMediaToNewTrack: (item: MediaItem) => boolean;
addTextToNewTrack: (item: TextElement | DragData) => boolean;
}
export const useTimelineStore = create<TimelineStore>((set, get) => {
// Helper to update tracks and maintain ordering
const updateTracks = (newTracks: TimelineTrack[]) => {
const tracksWithMain = ensureMainTrack(newTracks);
const sortedTracks = sortTracksByOrder(tracksWithMain);
set({
_tracks: tracksWithMain,
tracks: sortedTracks,
});
};
// Helper to auto-save timeline changes
const autoSaveTimeline = async () => {
const activeProject = useProjectStore.getState().activeProject;
if (activeProject) {
try {
await storageService.saveTimeline(activeProject.id, get()._tracks);
} catch (error) {
console.error("Failed to auto-save timeline:", error);
}
}
};
// Helper to update tracks and auto-save
const updateTracksAndSave = (newTracks: TimelineTrack[]) => {
updateTracks(newTracks);
// Auto-save in background
setTimeout(autoSaveTimeline, 100);
};
// Initialize with proper track ordering
const initialTracks = ensureMainTrack([]);
const sortedInitialTracks = sortTracksByOrder(initialTracks);
return {
_tracks: initialTracks,
tracks: sortedInitialTracks,
history: [],
redoStack: [],
selectedElements: [],
rippleEditingEnabled: false,
// Snapping settings defaults
snappingEnabled: true,
getSortedTracks: () => {
const { _tracks } = get();
const tracksWithMain = ensureMainTrack(_tracks);
return sortTracksByOrder(tracksWithMain);
},
pushHistory: () => {
const { _tracks, history } = get();
set({
history: [...history, JSON.parse(JSON.stringify(_tracks))],
redoStack: [],
});
},
undo: () => {
const { history, redoStack, _tracks } = get();
if (history.length === 0) return;
const prev = history[history.length - 1];
updateTracksAndSave(prev);
set({
history: history.slice(0, -1),
redoStack: [...redoStack, JSON.parse(JSON.stringify(_tracks))],
});
},
selectElement: (trackId, elementId, multi = false) => {
set((state) => {
const exists = state.selectedElements.some(
(c) => c.trackId === trackId && c.elementId === elementId
);
if (multi) {
return exists
? {
selectedElements: state.selectedElements.filter(
(c) => !(c.trackId === trackId && c.elementId === elementId)
),
}
: {
selectedElements: [
...state.selectedElements,
{ trackId, elementId },
],
};
} else {
return { selectedElements: [{ trackId, elementId }] };
}
});
},
deselectElement: (trackId, elementId) => {
set((state) => ({
selectedElements: state.selectedElements.filter(
(c) => !(c.trackId === trackId && c.elementId === elementId)
),
}));
},
clearSelectedElements: () => {
set({ selectedElements: [] });
},
setSelectedElements: (elements) => set({ selectedElements: elements }),
addTrack: (type) => {
get().pushHistory();
// Generate proper track name based on type
const trackName =
type === "media"
? "Media Track"
: type === "text"
? "Text Track"
: type === "audio"
? "Audio Track"
: "Track";
const newTrack: TimelineTrack = {
id: generateUUID(),
name: trackName,
type,
elements: [],
muted: false,
};
updateTracksAndSave([...get()._tracks, newTrack]);
return newTrack.id;
},
insertTrackAt: (type, index) => {
get().pushHistory();
// Generate proper track name based on type
const trackName =
type === "media"
? "Media Track"
: type === "text"
? "Text Track"
: type === "audio"
? "Audio Track"
: "Track";
const newTrack: TimelineTrack = {
id: generateUUID(),
name: trackName,
type,
elements: [],
muted: false,
};
const newTracks = [...get()._tracks];
newTracks.splice(index, 0, newTrack);
updateTracksAndSave(newTracks);
return newTrack.id;
},
removeTrack: (trackId) => {
get().pushHistory();
updateTracksAndSave(
get()._tracks.filter((track) => track.id !== trackId)
);
},
addElementToTrack: (trackId, elementData) => {
get().pushHistory();
// Validate element type matches track type
const track = get()._tracks.find((t) => t.id === trackId);
if (!track) {
console.error("Track not found:", trackId);
return;
}
// Use utility function for validation
const validation = validateElementTrackCompatibility(elementData, track);
if (!validation.isValid) {
console.error(validation.errorMessage);
return;
}
// For media elements, validate mediaId exists
if (elementData.type === "media" && !elementData.mediaId) {
console.error("Media element must have mediaId");
return;
}
// For text elements, validate required text properties
if (elementData.type === "text" && !elementData.content) {
console.error("Text element must have content");
return;
}
// Check if this is the first element being added to the timeline
const currentState = get();
const totalElementsInTimeline = currentState._tracks.reduce(
(total, track) => total + track.elements.length,
0
);
const isFirstElement = totalElementsInTimeline === 0;
const newElement: TimelineElement = {
...elementData,
id: generateUUID(),
startTime: elementData.startTime || 0,
trimStart: 0,
trimEnd: 0,
} as TimelineElement; // Type assertion since we trust the caller passes valid data
// If this is the first element and it's a media element, automatically set the project canvas size
// to match the media's aspect ratio and FPS (for videos)
if (isFirstElement && newElement.type === "media") {
const mediaStore = useMediaStore.getState();
const mediaItem = mediaStore.mediaItems.find(
(item) => item.id === newElement.mediaId
);
if (
mediaItem &&
(mediaItem.type === "image" || mediaItem.type === "video")
) {
const editorStore = useEditorStore.getState();
editorStore.setCanvasSizeFromAspectRatio(
getMediaAspectRatio(mediaItem)
);
}
// Set project FPS from the first video element
if (mediaItem && mediaItem.type === "video" && mediaItem.fps) {
const projectStore = useProjectStore.getState();
if (projectStore.activeProject) {
projectStore.updateProjectFps(mediaItem.fps);
}
}
}
updateTracksAndSave(
get()._tracks.map((track) =>
track.id === trackId
? { ...track, elements: [...track.elements, newElement] }
: track
)
);
},
removeElementFromTrack: (trackId, elementId) => {
get().pushHistory();
updateTracksAndSave(
get()
._tracks.map((track) =>
track.id === trackId
? {
...track,
elements: track.elements.filter(
(element) => element.id !== elementId
),
}
: track
)
.filter((track) => track.elements.length > 0)
);
},
moveElementToTrack: (fromTrackId, toTrackId, elementId) => {
get().pushHistory();
const fromTrack = get()._tracks.find((track) => track.id === fromTrackId);
const toTrack = get()._tracks.find((track) => track.id === toTrackId);
const elementToMove = fromTrack?.elements.find(
(element) => element.id === elementId
);
if (!elementToMove || !toTrack) return;
// Validate element type compatibility with target track
const validation = validateElementTrackCompatibility(
elementToMove,
toTrack
);
if (!validation.isValid) {
console.error(validation.errorMessage);
return;
}
const newTracks = get()
._tracks.map((track) => {
if (track.id === fromTrackId) {
return {
...track,
elements: track.elements.filter(
(element) => element.id !== elementId
),
};
} else if (track.id === toTrackId) {
return {
...track,
elements: [...track.elements, elementToMove],
};
}
return track;
})
.filter((track) => track.elements.length > 0);
updateTracksAndSave(newTracks);
},
updateElementTrim: (trackId, elementId, trimStart, trimEnd) => {
get().pushHistory();
updateTracksAndSave(
get()._tracks.map((track) =>
track.id === trackId
? {
...track,
elements: track.elements.map((element) =>
element.id === elementId
? { ...element, trimStart, trimEnd }
: element
),
}
: track
)
);
},
updateElementDuration: (trackId, elementId, duration) => {
get().pushHistory();
updateTracksAndSave(
get()._tracks.map((track) =>
track.id === trackId
? {
...track,
elements: track.elements.map((element) =>
element.id === elementId ? { ...element, duration } : element
),
}
: track
)
);
},
updateElementStartTime: (trackId, elementId, startTime) => {
get().pushHistory();
updateTracksAndSave(
get()._tracks.map((track) =>
track.id === trackId
? {
...track,
elements: track.elements.map((element) =>
element.id === elementId ? { ...element, startTime } : element
),
}
: track
)
);
},
toggleTrackMute: (trackId) => {
get().pushHistory();
updateTracksAndSave(
get()._tracks.map((track) =>
track.id === trackId ? { ...track, muted: !track.muted } : track
)
);
},
updateTextElement: (trackId, elementId, updates) => {
get().pushHistory();
updateTracksAndSave(
get()._tracks.map((track) =>
track.id === trackId
? {
...track,
elements: track.elements.map((element) =>
element.id === elementId && element.type === "text"
? { ...element, ...updates }
: element
),
}
: track
)
);
},
splitElement: (trackId, elementId, splitTime) => {
const { _tracks } = get();
const track = _tracks.find((t) => t.id === trackId);
const element = track?.elements.find((c) => c.id === elementId);
if (!element) return null;
const effectiveStart = element.startTime;
const effectiveEnd =
element.startTime +
(element.duration - element.trimStart - element.trimEnd);
if (splitTime <= effectiveStart || splitTime >= effectiveEnd) return null;
get().pushHistory();
const relativeTime = splitTime - element.startTime;
const firstDuration = relativeTime;
const secondDuration =
element.duration - element.trimStart - element.trimEnd - relativeTime;
const secondElementId = generateUUID();
updateTracksAndSave(
get()._tracks.map((track) =>
track.id === trackId
? {
...track,
elements: track.elements.flatMap((c) =>
c.id === elementId
? [
{
...c,
trimEnd: c.trimEnd + secondDuration,
name: getElementNameWithSuffix(c.name, "left"),
},
{
...c,
id: secondElementId,
startTime: splitTime,
trimStart: c.trimStart + firstDuration,
name: getElementNameWithSuffix(c.name, "right"),
},
]
: [c]
),
}
: track
)
);
return secondElementId;
},
// Split element and keep only the left portion
splitAndKeepLeft: (trackId, elementId, splitTime) => {
const { _tracks } = get();
const track = _tracks.find((t) => t.id === trackId);
const element = track?.elements.find((c) => c.id === elementId);
if (!element) return;
const effectiveStart = element.startTime;
const effectiveEnd =
element.startTime +
(element.duration - element.trimStart - element.trimEnd);
if (splitTime <= effectiveStart || splitTime >= effectiveEnd) return;
get().pushHistory();
const relativeTime = splitTime - element.startTime;
const durationToRemove =
element.duration - element.trimStart - element.trimEnd - relativeTime;
updateTracksAndSave(
get()._tracks.map((track) =>
track.id === trackId
? {
...track,
elements: track.elements.map((c) =>
c.id === elementId
? {
...c,
trimEnd: c.trimEnd + durationToRemove,
name: getElementNameWithSuffix(c.name, "left"),
}
: c
),
}
: track
)
);
},
// Split element and keep only the right portion
splitAndKeepRight: (trackId, elementId, splitTime) => {
const { _tracks } = get();
const track = _tracks.find((t) => t.id === trackId);
const element = track?.elements.find((c) => c.id === elementId);
if (!element) return;
const effectiveStart = element.startTime;
const effectiveEnd =
element.startTime +
(element.duration - element.trimStart - element.trimEnd);
if (splitTime <= effectiveStart || splitTime >= effectiveEnd) return;
get().pushHistory();
const relativeTime = splitTime - element.startTime;
updateTracksAndSave(
get()._tracks.map((track) =>
track.id === trackId
? {
...track,
elements: track.elements.map((c) =>
c.id === elementId
? {
...c,
startTime: splitTime,
trimStart: c.trimStart + relativeTime,
name: getElementNameWithSuffix(c.name, "right"),
}
: c
),
}
: track
)
);
},
// Extract audio from video element to an audio track
separateAudio: (trackId, elementId) => {
const { _tracks } = get();
const track = _tracks.find((t) => t.id === trackId);
const element = track?.elements.find((c) => c.id === elementId);
if (!element || track?.type !== "media") return null;
get().pushHistory();
// Find existing audio track or prepare to create one
const existingAudioTrack = _tracks.find((t) => t.type === "audio");
const audioElementId = generateUUID();
if (existingAudioTrack) {
// Add audio element to existing audio track
updateTracksAndSave(
get()._tracks.map((track) =>
track.id === existingAudioTrack.id
? {
...track,
elements: [
...track.elements,
{
...element,
id: audioElementId,
name: getElementNameWithSuffix(element.name, "audio"),
},
],
}
: track
)
);
} else {
// Create new audio track with the audio element in a single atomic update
const newAudioTrack: TimelineTrack = {
id: generateUUID(),
name: "Audio Track",
type: "audio",
elements: [
{
...element,
id: audioElementId,
name: getElementNameWithSuffix(element.name, "audio"),
},
],
muted: false,
};
updateTracksAndSave([...get()._tracks, newAudioTrack]);
}
return audioElementId;
},
// Replace media for an element
replaceElementMedia: async (trackId, elementId, newFile) => {
const { _tracks } = get();
const track = _tracks.find((t) => t.id === trackId);
const element = track?.elements.find((c) => c.id === elementId);
if (!element || element.type !== "media") return false;
try {
const mediaStore = useMediaStore.getState();
const projectStore = useProjectStore.getState();
if (!projectStore.activeProject) return false;
// Import required media processing functions
const {
getFileType,
getImageDimensions,
generateVideoThumbnail,
getMediaDuration,
} = await import("./media-store");
const fileType = getFileType(newFile);
if (!fileType) return false;
// Process the new media file
let mediaData: any = {
name: newFile.name,
type: fileType,
file: newFile,
url: URL.createObjectURL(newFile),
};
// Get media-specific metadata
if (fileType === "image") {
const { width, height } = await getImageDimensions(newFile);
mediaData.width = width;
mediaData.height = height;
} else if (fileType === "video") {
const [duration, { thumbnailUrl, width, height }] = await Promise.all(
[getMediaDuration(newFile), generateVideoThumbnail(newFile)]
);
mediaData.duration = duration;
mediaData.thumbnailUrl = thumbnailUrl;
mediaData.width = width;
mediaData.height = height;
} else if (fileType === "audio") {
mediaData.duration = await getMediaDuration(newFile);
}
// Add new media item to store
await mediaStore.addMediaItem(projectStore.activeProject.id, mediaData);
// Find the newly created media item
const newMediaItem = mediaStore.mediaItems.find(
(item) => item.file === newFile
);
if (!newMediaItem) return false;
get().pushHistory();
// Update the timeline element to reference the new media
updateTracksAndSave(
_tracks.map((track) =>
track.id === trackId
? {
...track,
elements: track.elements.map((c) =>
c.id === elementId
? {
...c,
mediaId: newMediaItem.id,
name: newMediaItem.name,
// Update duration if the new media has a different duration
duration: newMediaItem.duration || c.duration,
}
: c
),
}
: track
)
);
return true;
} catch (error) {
console.log(
JSON.stringify({
error: "Failed to replace element media",
details: error,
})
);
return false;
}
},
getTotalDuration: () => {
const { _tracks } = get();
if (_tracks.length === 0) return 0;
const trackEndTimes = _tracks.map((track) =>
track.elements.reduce((maxEnd, element) => {
const elementEnd =
element.startTime +
element.duration -
element.trimStart -
element.trimEnd;
return Math.max(maxEnd, elementEnd);
}, 0)
);
return Math.max(...trackEndTimes, 0);
},
redo: () => {
const { redoStack } = get();
if (redoStack.length === 0) return;
const next = redoStack[redoStack.length - 1];
updateTracksAndSave(next);
set({ redoStack: redoStack.slice(0, -1) });
},
dragState: {
isDragging: false,
elementId: null,
trackId: null,
startMouseX: 0,
startElementTime: 0,
clickOffsetTime: 0,
currentTime: 0,
},
setDragState: (dragState) =>
set((state) => ({
dragState: { ...state.dragState, ...dragState },
})),
startDrag: (
elementId,
trackId,
startMouseX,
startElementTime,
clickOffsetTime
) => {
set({
dragState: {
isDragging: true,
elementId,
trackId,
startMouseX,
startElementTime,
clickOffsetTime,
currentTime: startElementTime,
},
});
},
updateDragTime: (currentTime) => {
set((state) => ({
dragState: {
...state.dragState,
currentTime,
},
}));
},
endDrag: () => {
set({
dragState: {
isDragging: false,
elementId: null,
trackId: null,
startMouseX: 0,
startElementTime: 0,
clickOffsetTime: 0,
currentTime: 0,
},
});
},
// Persistence methods
loadProjectTimeline: async (projectId) => {
try {
const tracks = await storageService.loadTimeline(projectId);
if (tracks) {
updateTracks(tracks);
} else {
// No timeline saved yet, initialize with default
const defaultTracks = ensureMainTrack([]);
updateTracks(defaultTracks);
}
// Clear history when loading a project
set({ history: [], redoStack: [] });
} catch (error) {
console.error("Failed to load timeline:", error);
// Initialize with default on error
const defaultTracks = ensureMainTrack([]);
updateTracks(defaultTracks);
set({ history: [], redoStack: [] });
}
},
saveProjectTimeline: async (projectId) => {
try {
await storageService.saveTimeline(projectId, get()._tracks);
} catch (error) {
console.error("Failed to save timeline:", error);
}
},
clearTimeline: () => {
const defaultTracks = ensureMainTrack([]);
updateTracks(defaultTracks);
set({ history: [], redoStack: [], selectedElements: [] });
},
// Snapping actions
toggleSnapping: () => {
set((state) => ({ snappingEnabled: !state.snappingEnabled }));
},
checkElementOverlap: (trackId, startTime, duration, excludeElementId) => {
const track = get()._tracks.find((t) => t.id === trackId);
if (!track) return false;
const overlap = track.elements.some((element) => {
const elementEnd =
element.startTime +
element.duration -
element.trimStart -
element.trimEnd;
if (element.id === excludeElementId) {
return false;
}
return (
(startTime >= element.startTime && startTime < elementEnd) ||
(startTime + duration > element.startTime &&
startTime + duration <= elementEnd) ||
(startTime < element.startTime && startTime + duration > elementEnd)
);
});
return overlap;
},
findOrCreateTrack: (trackType) => {
// Always create new text track to allow multiple text elements
if (trackType === "text") {
return get().addTrack(trackType);
}
const existingTrack = get()._tracks.find((t) => t.type === trackType);
if (existingTrack) {
return existingTrack.id;
}
return get().addTrack(trackType);
},
addMediaAtTime: (item, currentTime = 0) => {
const trackType = item.type === "audio" ? "audio" : "media";
const targetTrackId = get().findOrCreateTrack(trackType);
const duration =
item.duration || TIMELINE_CONSTANTS.DEFAULT_IMAGE_DURATION;
if (get().checkElementOverlap(targetTrackId, currentTime, duration)) {
toast.error(
"Cannot place element here - it would overlap with existing elements"
);
return false;
}
get().addElementToTrack(targetTrackId, {
type: "media",
mediaId: item.id,
name: item.name,
duration,
startTime: currentTime,
trimStart: 0,
trimEnd: 0,
});
return true;
},
addTextAtTime: (item, currentTime = 0) => {
const targetTrackId = get().addTrack("text"); // Always create new text track to allow multiple text elements
get().addElementToTrack(targetTrackId, {
type: "text",
name: item.name || "Text",
content: item.content || "Default Text",
duration: item.duration || TIMELINE_CONSTANTS.DEFAULT_TEXT_DURATION,
startTime: currentTime,
trimStart: 0,
trimEnd: 0,
fontSize: item.fontSize || 48,
fontFamily: item.fontFamily || "Arial",
color: item.color || "#ffffff",
backgroundColor: item.backgroundColor || "transparent",
textAlign: item.textAlign || "center",
fontWeight: item.fontWeight || "normal",
fontStyle: item.fontStyle || "normal",
textDecoration: item.textDecoration || "none",
x: item.x || 0,
y: item.y || 0,
rotation: item.rotation || 0,
opacity: item.opacity !== undefined ? item.opacity : 1,
});
return true;
},
addMediaToNewTrack: (item) => {
const trackType = item.type === "audio" ? "audio" : "media";
const targetTrackId = get().findOrCreateTrack(trackType);
get().addElementToTrack(targetTrackId, {
type: "media",
mediaId: item.id,
name: item.name,
duration: item.duration || TIMELINE_CONSTANTS.DEFAULT_IMAGE_DURATION,
startTime: 0,
trimStart: 0,
trimEnd: 0,
});
return true;
},
addTextToNewTrack: (item) => {
const targetTrackId = get().addTrack("text"); // Always create new text track to allow multiple text elements
get().addElementToTrack(targetTrackId, {
type: "text",
name: item.name || "Text",
content:
("content" in item ? item.content : "Default Text") || "Default Text",
duration: TIMELINE_CONSTANTS.DEFAULT_TEXT_DURATION,
startTime: 0,
trimStart: 0,
trimEnd: 0,
fontSize: ("fontSize" in item ? item.fontSize : 48) || 48,
fontFamily:
("fontFamily" in item ? item.fontFamily : "Arial") || "Arial",
color: ("color" in item ? item.color : "#ffffff") || "#ffffff",
backgroundColor:
("backgroundColor" in item ? item.backgroundColor : "transparent") ||
"transparent",
textAlign:
("textAlign" in item ? item.textAlign : "center") || "center",
fontWeight:
("fontWeight" in item ? item.fontWeight : "normal") || "normal",
fontStyle:
("fontStyle" in item ? item.fontStyle : "normal") || "normal",
textDecoration:
("textDecoration" in item ? item.textDecoration : "none") || "none",
x: ("x" in item ? item.x : 0) || 0,
y: ("y" in item ? item.y : 0) || 0,
rotation: ("rotation" in item ? item.rotation : 0) || 0,
opacity:
"opacity" in item && item.opacity !== undefined ? item.opacity : 1,
});
return true;
},
// Ripple editing functions
toggleRippleEditing: () => {
set((state) => ({
rippleEditingEnabled: !state.rippleEditingEnabled,
}));
},
updateElementStartTimeWithRipple: (trackId, elementId, newStartTime) => {
const { _tracks, rippleEditingEnabled } = get();
if (!rippleEditingEnabled) {
// If ripple editing is disabled, use regular update
get().updateElementStartTime(trackId, elementId, newStartTime);
return;
}
const track = _tracks.find((t) => t.id === trackId);
const element = track?.elements.find((e) => e.id === elementId);
if (!element || !track) return;
get().pushHistory();
const oldStartTime = element.startTime;
const oldEndTime =
element.startTime +
(element.duration - element.trimStart - element.trimEnd);
const newEndTime =
newStartTime + (element.duration - element.trimStart - element.trimEnd);
const timeDelta = newStartTime - oldStartTime;
// Update all tracks, not just the current one
const updatedTracks = _tracks.map((currentTrack) => {
const updatedElements = currentTrack.elements.map((currentElement) => {
if (currentElement.id === elementId && currentTrack.id === trackId) {
// Update the moved element
return { ...currentElement, startTime: newStartTime };
}
// For ripple editing, we need to move elements that come after the moved element
// across all tracks to maintain sync
const currentElementStart = currentElement.startTime;
const currentElementEnd =
currentElement.startTime +
(currentElement.duration -
currentElement.trimStart -
currentElement.trimEnd);
// If moving element to the right (positive delta)
if (timeDelta > 0) {
// Move elements that start after the original position of the moved element
if (currentElementStart >= oldEndTime) {
return {
...currentElement,
startTime: currentElementStart + timeDelta,
};
}
}
// If moving element to the left (negative delta)
else if (timeDelta < 0) {
// Move elements that start after the new position of the moved element
if (
currentElementStart >= newEndTime &&
currentElementStart >= oldStartTime
) {
return {
...currentElement,
startTime: Math.max(0, currentElementStart + timeDelta),
};
}
}
return currentElement;
});
return { ...currentTrack, elements: updatedElements };
});
updateTracksAndSave(updatedTracks);
},
removeElementFromTrackWithRipple: (trackId, elementId) => {
const { _tracks, rippleEditingEnabled } = get();
if (!rippleEditingEnabled) {
// If ripple editing is disabled, use regular removal
get().removeElementFromTrack(trackId, elementId);
return;
}
const track = _tracks.find((t) => t.id === trackId);
const element = track?.elements.find((e) => e.id === elementId);
if (!element || !track) return;
get().pushHistory();
const elementStartTime = element.startTime;
const elementDuration =
element.duration - element.trimStart - element.trimEnd;
const elementEndTime = elementStartTime + elementDuration;
// Remove the element and shift all elements that come after it
const updatedTracks = _tracks
.map((currentTrack) => {
const updatedElements = currentTrack.elements
.filter((currentElement) => {
// Remove the target element
if (
currentElement.id === elementId &&
currentTrack.id === trackId
) {
return false;
}
return true;
})
.map((currentElement) => {
// Shift elements that start after the removed element
if (currentElement.startTime >= elementEndTime) {
return {
...currentElement,
startTime: Math.max(
0,
currentElement.startTime - elementDuration
),
};
}
return currentElement;
});
return { ...currentTrack, elements: updatedElements };
})
.filter((track) => track.elements.length > 0 || track.isMain);
updateTracksAndSave(updatedTracks);
},
};
});
|