summaryrefslogtreecommitdiff
path: root/apps/web/src/stores
diff options
context:
space:
mode:
Diffstat (limited to 'apps/web/src/stores')
-rw-r--r--apps/web/src/stores/media-store.ts38
-rw-r--r--apps/web/src/stores/timeline-store.ts1015
2 files changed, 588 insertions, 465 deletions
diff --git a/apps/web/src/stores/media-store.ts b/apps/web/src/stores/media-store.ts
index 48932db5..ab413b14 100644
--- a/apps/web/src/stores/media-store.ts
+++ b/apps/web/src/stores/media-store.ts
@@ -1,16 +1,25 @@
import { create } from "zustand";
import { storageService } from "@/lib/storage/storage-service";
+export type MediaType = "image" | "video" | "audio";
+
export interface MediaItem {
id: string;
name: string;
- type: "image" | "video" | "audio";
+ type: MediaType;
file: File;
- url: string; // Object URL for preview
+ url?: string; // Object URL for preview
thumbnailUrl?: string; // For video thumbnails
duration?: number; // For video/audio duration
width?: number; // For video/image width
height?: number; // For video/image height
+ // Text-specific properties
+ content?: string; // Text content
+ fontSize?: number; // Font size
+ fontFamily?: string; // Font family
+ color?: string; // Text color
+ backgroundColor?: string; // Background color
+ textAlign?: "left" | "center" | "right"; // Text alignment
}
interface MediaStore {
@@ -25,7 +34,7 @@ interface MediaStore {
}
// Helper function to determine file type
-export const getFileType = (file: File): "image" | "video" | "audio" | null => {
+export const getFileType = (file: File): MediaType | null => {
const { type } = file;
if (type.startsWith("image/")) {
@@ -46,7 +55,7 @@ export const getImageDimensions = (
file: File
): Promise<{ width: number; height: number }> => {
return new Promise((resolve, reject) => {
- const img = new Image();
+ const img = new window.Image();
img.addEventListener("load", () => {
const width = img.naturalWidth;
@@ -69,8 +78,8 @@ export const generateVideoThumbnail = (
file: File
): Promise<{ thumbnailUrl: string; width: number; height: number }> => {
return new Promise((resolve, reject) => {
- const video = document.createElement("video");
- const canvas = document.createElement("canvas");
+ const video = document.createElement("video") as HTMLVideoElement;
+ const canvas = document.createElement("canvas") as HTMLCanvasElement;
const ctx = canvas.getContext("2d");
if (!ctx) {
@@ -115,7 +124,7 @@ export const getMediaDuration = (file: File): Promise<number> => {
return new Promise((resolve, reject) => {
const element = document.createElement(
file.type.startsWith("video/") ? "video" : "audio"
- ) as HTMLVideoElement | HTMLAudioElement;
+ ) as HTMLVideoElement;
element.addEventListener("loadedmetadata", () => {
resolve(element.duration);
@@ -162,17 +171,17 @@ export const useMediaStore = create<MediaStore>((set, get) => ({
console.error("Failed to save media item:", error);
// Remove from local state if save failed
set((state) => ({
- mediaItems: state.mediaItems.filter((item) => item.id !== newItem.id),
+ mediaItems: state.mediaItems.filter((media) => media.id !== newItem.id),
}));
}
},
- removeMediaItem: async (id) => {
+ removeMediaItem: async (id: string) => {
const state = get();
- const item = state.mediaItems.find((item) => item.id === id);
+ const item = state.mediaItems.find((media) => media.id === id);
// Cleanup object URLs to prevent memory leaks
- if (item) {
+ if (item && item.url) {
URL.revokeObjectURL(item.url);
if (item.thumbnailUrl) {
URL.revokeObjectURL(item.thumbnailUrl);
@@ -181,7 +190,7 @@ export const useMediaStore = create<MediaStore>((set, get) => ({
// Remove from local state immediately
set((state) => ({
- mediaItems: state.mediaItems.filter((item) => item.id !== id),
+ mediaItems: state.mediaItems.filter((media) => media.id !== id),
}));
// Remove from persistent storage
@@ -189,7 +198,6 @@ export const useMediaStore = create<MediaStore>((set, get) => ({
await storageService.deleteMediaItem(id);
} catch (error) {
console.error("Failed to delete media item:", error);
- // Could re-add to local state here if needed
}
},
@@ -211,7 +219,9 @@ export const useMediaStore = create<MediaStore>((set, get) => ({
// Cleanup all object URLs
state.mediaItems.forEach((item) => {
- URL.revokeObjectURL(item.url);
+ if (item.url) {
+ URL.revokeObjectURL(item.url);
+ }
if (item.thumbnailUrl) {
URL.revokeObjectURL(item.thumbnailUrl);
}
diff --git a/apps/web/src/stores/timeline-store.ts b/apps/web/src/stores/timeline-store.ts
index 01f4fea6..c4e4e0e3 100644
--- a/apps/web/src/stores/timeline-store.ts
+++ b/apps/web/src/stores/timeline-store.ts
@@ -1,10 +1,17 @@
import { create } from "zustand";
-import type { TrackType } from "@/types/timeline";
+import {
+ TrackType,
+ TimelineElement,
+ CreateTimelineElement,
+ TimelineTrack,
+ sortTracksByOrder,
+ ensureMainTrack,
+} from "@/types/timeline";
import { useEditorStore } from "./editor-store";
import { useMediaStore, getMediaAspectRatio } from "./media-store";
-// Helper function to manage clip naming with suffixes
-const getClipNameWithSuffix = (
+// Helper function to manage element naming with suffixes
+const getElementNameWithSuffix = (
originalName: string,
suffix: string
): string => {
@@ -18,52 +25,43 @@ const getClipNameWithSuffix = (
return `${baseName} (${suffix})`;
};
-export interface TimelineClip {
- id: string;
- mediaId: string;
- name: string;
- duration: number;
- startTime: number;
- trimStart: number;
- trimEnd: number;
-}
-
-export interface TimelineTrack {
- id: string;
- name: string;
- type: TrackType;
- clips: TimelineClip[];
- muted?: boolean;
-}
-
interface TimelineStore {
- tracks: TimelineTrack[];
+ // 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[];
+
// Multi-selection
- selectedClips: { trackId: string; clipId: string }[];
- selectClip: (trackId: string, clipId: string, multi?: boolean) => void;
- deselectClip: (trackId: string, clipId: string) => void;
- clearSelectedClips: () => void;
- setSelectedClips: (clips: { trackId: string; clipId: string }[]) => void;
+ 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;
- clipId: string | null;
+ elementId: string | null;
trackId: string | null;
startMouseX: number;
- startClipTime: number;
+ startElementTime: number;
clickOffsetTime: number;
currentTime: number;
};
setDragState: (dragState: Partial<TimelineStore["dragState"]>) => void;
startDrag: (
- clipId: string,
+ elementId: string,
trackId: string,
startMouseX: number,
- startClipTime: number,
+ startElementTime: number,
clickOffsetTime: number
) => void;
updateDragTime: (currentTime: number) => void;
@@ -71,44 +69,45 @@ interface TimelineStore {
// Actions
addTrack: (type: TrackType) => string;
+ insertTrackAt: (type: TrackType, index: number) => string;
removeTrack: (trackId: string) => void;
- addClipToTrack: (trackId: string, clip: Omit<TimelineClip, "id">) => void;
- removeClipFromTrack: (trackId: string, clipId: string) => void;
- moveClipToTrack: (
+ addElementToTrack: (trackId: string, element: CreateTimelineElement) => void;
+ removeElementFromTrack: (trackId: string, elementId: string) => void;
+ moveElementToTrack: (
fromTrackId: string,
toTrackId: string,
- clipId: string
+ elementId: string
) => void;
- updateClipTrim: (
+ updateElementTrim: (
trackId: string,
- clipId: string,
+ elementId: string,
trimStart: number,
trimEnd: number
) => void;
- updateClipStartTime: (
+ updateElementStartTime: (
trackId: string,
- clipId: string,
+ elementId: string,
startTime: number
) => void;
toggleTrackMute: (trackId: string) => void;
- // Split operations for clips
- splitClip: (
+ // Split operations for elements
+ splitElement: (
trackId: string,
- clipId: string,
+ elementId: string,
splitTime: number
) => string | null;
splitAndKeepLeft: (
trackId: string,
- clipId: string,
+ elementId: string,
splitTime: number
) => void;
splitAndKeepRight: (
trackId: string,
- clipId: string,
+ elementId: string,
splitTime: number
) => void;
- separateAudio: (trackId: string, clipId: string) => string | null;
+ separateAudio: (trackId: string, elementId: string) => string | null;
// Computed values
getTotalDuration: () => number;
@@ -119,479 +118,593 @@ interface TimelineStore {
pushHistory: () => void;
}
-export const useTimelineStore = create<TimelineStore>((set, get) => ({
- tracks: [],
- history: [],
- redoStack: [],
- selectedClips: [],
-
- pushHistory: () => {
- const { tracks, history, redoStack } = get();
+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({
- history: [...history, JSON.parse(JSON.stringify(tracks))],
- redoStack: [],
+ _tracks: tracksWithMain,
+ tracks: sortedTracks,
});
- },
+ };
- undo: () => {
- const { history, redoStack, tracks } = get();
- if (history.length === 0) return;
- const prev = history[history.length - 1];
- set({
- tracks: prev,
- history: history.slice(0, -1),
- redoStack: [...redoStack, JSON.parse(JSON.stringify(tracks))],
- });
- },
+ // Initialize with proper track ordering
+ const initialTracks = ensureMainTrack([]);
+ const sortedInitialTracks = sortTracksByOrder(initialTracks);
- selectClip: (trackId, clipId, multi = false) => {
- set((state) => {
- const exists = state.selectedClips.some(
- (c) => c.trackId === trackId && c.clipId === clipId
- );
- if (multi) {
- return exists
- ? {
- selectedClips: state.selectedClips.filter(
- (c) => !(c.trackId === trackId && c.clipId === clipId)
- ),
- }
- : { selectedClips: [...state.selectedClips, { trackId, clipId }] };
- } else {
- return { selectedClips: [{ trackId, clipId }] };
- }
- });
- },
+ return {
+ _tracks: initialTracks,
+ tracks: sortedInitialTracks,
+ history: [],
+ redoStack: [],
+ selectedElements: [],
+
+ 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];
+ updateTracks(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: crypto.randomUUID(),
+ name: trackName,
+ type,
+ elements: [],
+ muted: false,
+ };
+
+ updateTracks([...get()._tracks, newTrack]);
+ return newTrack.id;
+ },
+
+ insertTrackAt: (type, index) => {
+ get().pushHistory();
- deselectClip: (trackId, clipId) => {
- set((state) => ({
- selectedClips: state.selectedClips.filter(
- (c) => !(c.trackId === trackId && c.clipId === clipId)
- ),
- }));
- },
+ // 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: crypto.randomUUID(),
+ name: trackName,
+ type,
+ elements: [],
+ muted: false,
+ };
- clearSelectedClips: () => {
- set({ selectedClips: [] });
- },
+ const newTracks = [...get()._tracks];
+ newTracks.splice(index, 0, newTrack);
+ updateTracks(newTracks);
+ return newTrack.id;
+ },
- setSelectedClips: (clips) => set({ selectedClips: clips }),
+ removeTrack: (trackId) => {
+ get().pushHistory();
+ updateTracks(get()._tracks.filter((track) => track.id !== trackId));
+ },
- addTrack: (type) => {
- get().pushHistory();
- const newTrack: TimelineTrack = {
- id: crypto.randomUUID(),
- name: `${type.charAt(0).toUpperCase() + type.slice(1)} Track`,
- type,
- clips: [],
- muted: false,
- };
- set((state) => ({
- tracks: [...state.tracks, newTrack],
- }));
- return newTrack.id;
- },
+ addElementToTrack: (trackId, elementData) => {
+ get().pushHistory();
- removeTrack: (trackId) => {
- get().pushHistory();
- set((state) => ({
- tracks: state.tracks.filter((track) => track.id !== trackId),
- }));
- },
+ // Validate element type matches track type
+ const track = get()._tracks.find((t) => t.id === trackId);
+ if (!track) {
+ console.error("Track not found:", trackId);
+ return;
+ }
- addClipToTrack: (trackId, clipData) => {
- get().pushHistory();
+ // Validate element can be added to this track type
+ if (track.type === "media" && elementData.type !== "media") {
+ console.error("Media track only accepts media elements");
+ return;
+ }
+ if (track.type === "text" && elementData.type !== "text") {
+ console.error("Text track only accepts text elements");
+ return;
+ }
+ if (track.type === "audio" && elementData.type !== "media") {
+ console.error("Audio track only accepts media elements");
+ return;
+ }
- // Check if this is the first clip being added to the timeline
- const currentState = get();
- const totalClipsInTimeline = currentState.tracks.reduce(
- (total, track) => total + track.clips.length,
- 0
- );
- const isFirstClip = totalClipsInTimeline === 0;
+ // For media elements, validate mediaId exists
+ if (elementData.type === "media" && !elementData.mediaId) {
+ console.error("Media element must have mediaId");
+ return;
+ }
- const newClip: TimelineClip = {
- ...clipData,
- id: crypto.randomUUID(),
- startTime: clipData.startTime || 0,
- trimStart: 0,
- trimEnd: 0,
- };
+ // For text elements, validate required text properties
+ if (elementData.type === "text" && !elementData.content) {
+ console.error("Text element must have content");
+ return;
+ }
- // If this is the first clip, automatically set the project canvas size
- // to match the media's aspect ratio
- if (isFirstClip && clipData.mediaId) {
- const mediaStore = useMediaStore.getState();
- const mediaItem = mediaStore.mediaItems.find(
- (item) => item.id === clipData.mediaId
+ // 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: crypto.randomUUID(),
+ startTime: elementData.startTime || 0,
+ trimStart: 0,
+ trimEnd: 0,
+ } as TimelineElement; // Type assertion since we trust the caller passes valid data
- if (
- mediaItem &&
- (mediaItem.type === "image" || mediaItem.type === "video")
- ) {
- const editorStore = useEditorStore.getState();
- editorStore.setCanvasSizeFromAspectRatio(
- getMediaAspectRatio(mediaItem)
+ // 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
+ if (isFirstElement && newElement.type === "media") {
+ const mediaStore = useMediaStore.getState();
+ const mediaItem = mediaStore.mediaItems.find(
+ (item) => item.id === newElement.mediaId
);
- }
- }
- set((state) => ({
- tracks: state.tracks.map((track) =>
- track.id === trackId
- ? { ...track, clips: [...track.clips, newClip] }
- : track
- ),
- }));
- },
+ if (
+ mediaItem &&
+ (mediaItem.type === "image" || mediaItem.type === "video")
+ ) {
+ const editorStore = useEditorStore.getState();
+ editorStore.setCanvasSizeFromAspectRatio(
+ getMediaAspectRatio(mediaItem)
+ );
+ }
+ }
- removeClipFromTrack: (trackId, clipId) => {
- get().pushHistory();
- set((state) => ({
- tracks: state.tracks
- .map((track) =>
+ updateTracks(
+ get()._tracks.map((track) =>
track.id === trackId
- ? {
- ...track,
- clips: track.clips.filter((clip) => clip.id !== clipId),
- }
+ ? { ...track, elements: [...track.elements, newElement] }
: track
)
- .filter((track) => track.clips.length > 0),
- }));
- },
+ );
+ },
- moveClipToTrack: (fromTrackId, toTrackId, clipId) => {
- get().pushHistory();
- set((state) => {
- const fromTrack = state.tracks.find((track) => track.id === fromTrackId);
- const clipToMove = fromTrack?.clips.find((clip) => clip.id === clipId);
+ removeElementFromTrack: (trackId, elementId) => {
+ get().pushHistory();
+ updateTracks(
+ get()
+ ._tracks.map((track) =>
+ track.id === trackId
+ ? {
+ ...track,
+ elements: track.elements.filter(
+ (element) => element.id !== elementId
+ ),
+ }
+ : track
+ )
+ .filter((track) => track.elements.length > 0)
+ );
+ },
- if (!clipToMove) return state;
+ moveElementToTrack: (fromTrackId, toTrackId, elementId) => {
+ get().pushHistory();
- return {
- tracks: state.tracks
- .map((track) => {
- if (track.id === fromTrackId) {
- return {
- ...track,
- clips: track.clips.filter((clip) => clip.id !== clipId),
- };
- } else if (track.id === toTrackId) {
- return {
- ...track,
- clips: [...track.clips, clipToMove],
- };
- }
- return track;
- })
- .filter((track) => track.clips.length > 0),
- };
- });
- },
+ const fromTrack = get()._tracks.find((track) => track.id === fromTrackId);
+ const elementToMove = fromTrack?.elements.find(
+ (element) => element.id === elementId
+ );
- updateClipTrim: (trackId, clipId, trimStart, trimEnd) => {
- get().pushHistory();
- set((state) => ({
- tracks: state.tracks.map((track) =>
- track.id === trackId
- ? {
- ...track,
- clips: track.clips.map((clip) =>
- clip.id === clipId ? { ...clip, trimStart, trimEnd } : clip
- ),
- }
- : track
- ),
- }));
- },
+ if (!elementToMove) return;
- updateClipStartTime: (trackId, clipId, startTime) => {
- get().pushHistory();
- set((state) => ({
- tracks: state.tracks.map((track) =>
- track.id === trackId
- ? {
+ const newTracks = get()
+ ._tracks.map((track) => {
+ if (track.id === fromTrackId) {
+ return {
...track,
- clips: track.clips.map((clip) =>
- clip.id === clipId ? { ...clip, startTime } : clip
+ elements: track.elements.filter(
+ (element) => element.id !== elementId
),
- }
- : track
- ),
- }));
- },
-
- toggleTrackMute: (trackId) => {
- get().pushHistory();
- set((state) => ({
- tracks: state.tracks.map((track) =>
- track.id === trackId ? { ...track, muted: !track.muted } : track
- ),
- }));
- },
-
- splitClip: (trackId, clipId, splitTime) => {
- const { tracks } = get();
- const track = tracks.find((t) => t.id === trackId);
- const clip = track?.clips.find((c) => c.id === clipId);
+ };
+ } else if (track.id === toTrackId) {
+ return {
+ ...track,
+ elements: [...track.elements, elementToMove],
+ };
+ }
+ return track;
+ })
+ .filter((track) => track.elements.length > 0);
- if (!clip) return null;
+ updateTracks(newTracks);
+ },
- const effectiveStart = clip.startTime;
- const effectiveEnd =
- clip.startTime + (clip.duration - clip.trimStart - clip.trimEnd);
+ updateElementTrim: (trackId, elementId, trimStart, trimEnd) => {
+ get().pushHistory();
+ updateTracks(
+ get()._tracks.map((track) =>
+ track.id === trackId
+ ? {
+ ...track,
+ elements: track.elements.map((element) =>
+ element.id === elementId
+ ? { ...element, trimStart, trimEnd }
+ : element
+ ),
+ }
+ : track
+ )
+ );
+ },
- if (splitTime <= effectiveStart || splitTime >= effectiveEnd) return null;
+ updateElementStartTime: (trackId, elementId, startTime) => {
+ get().pushHistory();
+ updateTracks(
+ get()._tracks.map((track) =>
+ track.id === trackId
+ ? {
+ ...track,
+ elements: track.elements.map((element) =>
+ element.id === elementId ? { ...element, startTime } : element
+ ),
+ }
+ : track
+ )
+ );
+ },
- get().pushHistory();
+ toggleTrackMute: (trackId) => {
+ get().pushHistory();
+ updateTracks(
+ get()._tracks.map((track) =>
+ track.id === trackId ? { ...track, muted: !track.muted } : track
+ )
+ );
+ },
- const relativeTime = splitTime - clip.startTime;
- const firstDuration = relativeTime;
- const secondDuration =
- clip.duration - clip.trimStart - clip.trimEnd - relativeTime;
+ splitElement: (trackId, elementId, splitTime) => {
+ const { _tracks } = get();
+ const track = _tracks.find((t) => t.id === trackId);
+ const element = track?.elements.find((c) => c.id === elementId);
- const secondClipId = crypto.randomUUID();
+ if (!element) return null;
- set((state) => ({
- tracks: state.tracks.map((track) =>
- track.id === trackId
- ? {
- ...track,
- clips: track.clips.flatMap((c) =>
- c.id === clipId
- ? [
- {
- ...c,
- trimEnd: c.trimEnd + secondDuration,
- name: getClipNameWithSuffix(c.name, "left"),
- },
- {
- ...c,
- id: secondClipId,
- startTime: splitTime,
- trimStart: c.trimStart + firstDuration,
- name: getClipNameWithSuffix(c.name, "right"),
- },
- ]
- : [c]
- ),
- }
- : track
- ),
- }));
+ const effectiveStart = element.startTime;
+ const effectiveEnd =
+ element.startTime +
+ (element.duration - element.trimStart - element.trimEnd);
- return secondClipId;
- },
+ if (splitTime <= effectiveStart || splitTime >= effectiveEnd) return null;
- // Split clip and keep only the left portion
- splitAndKeepLeft: (trackId, clipId, splitTime) => {
- const { tracks } = get();
- const track = tracks.find((t) => t.id === trackId);
- const clip = track?.clips.find((c) => c.id === clipId);
+ get().pushHistory();
- if (!clip) return;
+ const relativeTime = splitTime - element.startTime;
+ const firstDuration = relativeTime;
+ const secondDuration =
+ element.duration - element.trimStart - element.trimEnd - relativeTime;
- const effectiveStart = clip.startTime;
- const effectiveEnd =
- clip.startTime + (clip.duration - clip.trimStart - clip.trimEnd);
+ const secondElementId = crypto.randomUUID();
- if (splitTime <= effectiveStart || splitTime >= effectiveEnd) return;
+ updateTracks(
+ 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
+ )
+ );
- get().pushHistory();
+ return secondElementId;
+ },
- const relativeTime = splitTime - clip.startTime;
- const durationToRemove =
- clip.duration - clip.trimStart - clip.trimEnd - relativeTime;
+ // 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);
- set((state) => ({
- tracks: state.tracks.map((track) =>
- track.id === trackId
- ? {
- ...track,
- clips: track.clips.map((c) =>
- c.id === clipId
- ? {
- ...c,
- trimEnd: c.trimEnd + durationToRemove,
- name: getClipNameWithSuffix(c.name, "left"),
- }
- : c
- ),
- }
- : track
- ),
- }));
- },
+ if (!element) return;
- // Split clip and keep only the right portion
- splitAndKeepRight: (trackId, clipId, splitTime) => {
- const { tracks } = get();
- const track = tracks.find((t) => t.id === trackId);
- const clip = track?.clips.find((c) => c.id === clipId);
+ const effectiveStart = element.startTime;
+ const effectiveEnd =
+ element.startTime +
+ (element.duration - element.trimStart - element.trimEnd);
- if (!clip) return;
+ if (splitTime <= effectiveStart || splitTime >= effectiveEnd) return;
- const effectiveStart = clip.startTime;
- const effectiveEnd =
- clip.startTime + (clip.duration - clip.trimStart - clip.trimEnd);
+ get().pushHistory();
- if (splitTime <= effectiveStart || splitTime >= effectiveEnd) return;
+ const relativeTime = splitTime - element.startTime;
+ const durationToRemove =
+ element.duration - element.trimStart - element.trimEnd - relativeTime;
- get().pushHistory();
+ updateTracks(
+ 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
+ )
+ );
+ },
- const relativeTime = splitTime - clip.startTime;
+ // 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);
- set((state) => ({
- tracks: state.tracks.map((track) =>
- track.id === trackId
- ? {
- ...track,
- clips: track.clips.map((c) =>
- c.id === clipId
- ? {
- ...c,
- startTime: splitTime,
- trimStart: c.trimStart + relativeTime,
- name: getClipNameWithSuffix(c.name, "right"),
- }
- : c
- ),
- }
- : track
- ),
- }));
- },
+ if (!element) return;
- // Extract audio from video clip to an audio track
- separateAudio: (trackId, clipId) => {
- const { tracks } = get();
- const track = tracks.find((t) => t.id === trackId);
- const clip = track?.clips.find((c) => c.id === clipId);
+ const effectiveStart = element.startTime;
+ const effectiveEnd =
+ element.startTime +
+ (element.duration - element.trimStart - element.trimEnd);
- if (!clip || track?.type !== "video") return null;
+ if (splitTime <= effectiveStart || splitTime >= effectiveEnd) return;
- get().pushHistory();
+ get().pushHistory();
- // Find existing audio track or prepare to create one
- const existingAudioTrack = tracks.find((t) => t.type === "audio");
- const audioClipId = crypto.randomUUID();
+ const relativeTime = splitTime - element.startTime;
- if (existingAudioTrack) {
- // Add audio clip to existing audio track
- set((state) => ({
- tracks: state.tracks.map((track) =>
- track.id === existingAudioTrack.id
+ updateTracks(
+ get()._tracks.map((track) =>
+ track.id === trackId
? {
...track,
- clips: [
- ...track.clips,
- {
- ...clip,
- id: audioClipId,
- name: getClipNameWithSuffix(clip.name, "audio"),
- },
- ],
+ elements: track.elements.map((c) =>
+ c.id === elementId
+ ? {
+ ...c,
+ startTime: splitTime,
+ trimStart: c.trimStart + relativeTime,
+ name: getElementNameWithSuffix(c.name, "right"),
+ }
+ : c
+ ),
}
: track
- ),
- }));
- } else {
- // Create new audio track with the audio clip in a single atomic update
- const newAudioTrack: TimelineTrack = {
- id: crypto.randomUUID(),
- name: "Audio Track",
- type: "audio",
- clips: [
- {
- ...clip,
- id: audioClipId,
- name: getClipNameWithSuffix(clip.name, "audio"),
- },
- ],
- muted: false,
- };
+ )
+ );
+ },
- set((state) => ({
- tracks: [...state.tracks, newAudioTrack],
- }));
- }
+ // 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);
- return audioClipId;
- },
+ if (!element || track?.type !== "media") return null;
- getTotalDuration: () => {
- const { tracks } = get();
- if (tracks.length === 0) return 0;
+ get().pushHistory();
- const trackEndTimes = tracks.map((track) =>
- track.clips.reduce((maxEnd, clip) => {
- const clipEnd =
- clip.startTime + clip.duration - clip.trimStart - clip.trimEnd;
- return Math.max(maxEnd, clipEnd);
- }, 0)
- );
+ // Find existing audio track or prepare to create one
+ const existingAudioTrack = _tracks.find((t) => t.type === "audio");
+ const audioElementId = crypto.randomUUID();
- return Math.max(...trackEndTimes, 0);
- },
+ if (existingAudioTrack) {
+ // Add audio element to existing audio track
+ updateTracks(
+ 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: crypto.randomUUID(),
+ name: "Audio Track",
+ type: "audio",
+ elements: [
+ {
+ ...element,
+ id: audioElementId,
+ name: getElementNameWithSuffix(element.name, "audio"),
+ },
+ ],
+ muted: false,
+ };
- redo: () => {
- const { redoStack } = get();
- if (redoStack.length === 0) return;
- const next = redoStack[redoStack.length - 1];
- set({ tracks: next, redoStack: redoStack.slice(0, -1) });
- },
+ updateTracks([...get()._tracks, newAudioTrack]);
+ }
- dragState: {
- isDragging: false,
- clipId: null,
- trackId: null,
- startMouseX: 0,
- startClipTime: 0,
- clickOffsetTime: 0,
- currentTime: 0,
- },
+ return audioElementId;
+ },
- setDragState: (dragState) =>
- set((state) => ({
- dragState: { ...state.dragState, ...dragState },
- })),
+ getTotalDuration: () => {
+ const { _tracks } = get();
+ if (_tracks.length === 0) return 0;
- startDrag: (clipId, trackId, startMouseX, startClipTime, clickOffsetTime) => {
- set({
- dragState: {
- isDragging: true,
- clipId,
- trackId,
- startMouseX,
- startClipTime,
- clickOffsetTime,
- currentTime: startClipTime,
- },
- });
- },
+ 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)
+ );
- updateDragTime: (currentTime) => {
- set((state) => ({
- dragState: {
- ...state.dragState,
- currentTime,
- },
- }));
- },
+ return Math.max(...trackEndTimes, 0);
+ },
- endDrag: () => {
- set({
- dragState: {
- isDragging: false,
- clipId: null,
- trackId: null,
- startMouseX: 0,
- startClipTime: 0,
- clickOffsetTime: 0,
- currentTime: 0,
- },
- });
- },
-}));
+ redo: () => {
+ const { redoStack } = get();
+ if (redoStack.length === 0) return;
+ const next = redoStack[redoStack.length - 1];
+ updateTracks(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,
+ },
+ });
+ },
+ };
+});