summaryrefslogtreecommitdiff
path: root/apps/web/src/lib/commands/timeline/element/update-element-trim.ts
blob: 6afcb9d0c87c85e306a3d612c1895fa1f984ff85 (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
import { Command } from "@/lib/commands/base-command";
import type { TimelineTrack } from "@/types/timeline";
import { EditorCore } from "@/core";
import { clampAnimationsToDuration } from "@/lib/animation";

export class UpdateElementTrimCommand extends Command {
	private savedState: TimelineTrack[] | null = null;
	private readonly elementId: string;
	private readonly trimStart: number;
	private readonly trimEnd: number;
	private readonly startTime: number | undefined;
	private readonly duration: number | undefined;

	constructor({
		elementId,
		trimStart,
		trimEnd,
		startTime,
		duration,
	}: {
		elementId: string;
		trimStart: number;
		trimEnd: number;
		startTime?: number;
		duration?: number;
	}) {
		super();
		this.elementId = elementId;
		this.trimStart = trimStart;
		this.trimEnd = trimEnd;
		this.startTime = startTime;
		this.duration = duration;
	}

	execute(): void {
		const editor = EditorCore.getInstance();
		this.savedState = editor.timeline.getTracks();

		const updatedTracks = this.savedState.map((track) => {
			const newElements = track.elements.map((element) => {
				if (element.id !== this.elementId) {
					return element;
				}

				const nextDuration = this.duration ?? element.duration;
				return {
					...element,
					trimStart: this.trimStart,
					trimEnd: this.trimEnd,
					startTime: this.startTime ?? element.startTime,
					duration: nextDuration,
					animations: clampAnimationsToDuration({
						animations: element.animations,
						duration: nextDuration,
					}),
				};
			});
			return { ...track, elements: newElements } as typeof track;
		});

		editor.timeline.updateTracks(updatedTracks);
	}

	undo(): void {
		if (this.savedState) {
			const editor = EditorCore.getInstance();
			editor.timeline.updateTracks(this.savedState);
		}
	}
}