summaryrefslogtreecommitdiff
path: root/apps/web/src/services/storage/migrations/transformers/v11-to-v12.ts
blob: 4efc5b2590242343e1dae2378293e60cb243ce20 (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
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
import type { MigrationResult, ProjectRecord } from "./types";
import { getProjectId, isRecord } from "./utils";

export function transformProjectV11ToV12({
	project,
}: {
	project: ProjectRecord;
}): MigrationResult<ProjectRecord> {
	if (!getProjectId({ project })) {
		return { project, skipped: true, reason: "no project id" };
	}

	if (typeof project.version === "number" && project.version >= 12) {
		return { project, skipped: true, reason: "already v12" };
	}

	const migratedProject = migrateProjectPosition({ project });

	return {
		project: { ...migratedProject, version: 12 },
		skipped: false,
	};
}

function migrateProjectPosition({
	project,
}: {
	project: ProjectRecord;
}): ProjectRecord {
	const scenesValue = project.scenes;
	if (!Array.isArray(scenesValue)) return project;

	const migratedScenes = scenesValue.map((scene) =>
		migrateScenePosition({ scene }),
	);

	return { ...project, scenes: migratedScenes };
}

function migrateScenePosition({ scene }: { scene: unknown }): unknown {
	if (!isRecord(scene)) return scene;

	const tracksValue = scene.tracks;
	if (!Array.isArray(tracksValue)) return scene;

	const migratedTracks = tracksValue.map((track) =>
		migrateTrackPosition({ track }),
	);

	return { ...scene, tracks: migratedTracks };
}

function migrateTrackPosition({ track }: { track: unknown }): unknown {
	if (!isRecord(track)) return track;

	const elementsValue = track.elements;
	if (!Array.isArray(elementsValue)) return track;

	const migratedElements = elementsValue.map((element) =>
		migrateElementPosition({ element }),
	);

	return { ...track, elements: migratedElements };
}

function migrateElementPosition({ element }: { element: unknown }): unknown {
	if (!isRecord(element)) return element;

	const animations = element.animations;
	if (!isRecord(animations) || !isRecord(animations.channels)) return element;

	const channels = animations.channels as Record<string, unknown>;
	const xChannel = channels["transform.position.x"];
	const yChannel = channels["transform.position.y"];

	if (!xChannel && !yChannel) return element;

	const baseTransform = isRecord(element.transform) ? element.transform : {};
	const basePosition = isRecord(baseTransform.position)
		? baseTransform.position
		: {};
	const baseX = typeof basePosition.x === "number" ? basePosition.x : 0;
	const baseY = typeof basePosition.y === "number" ? basePosition.y : 0;

	const xKeyframes = getKeyframes({ channel: xChannel });
	const yKeyframes = getKeyframes({ channel: yChannel });

	const allTimes = Array.from(
		new Set([
			...xKeyframes.map((kf) => kf.time),
			...yKeyframes.map((kf) => kf.time),
		]),
	).sort((a, b) => a - b);

	const vectorKeyframes = allTimes.map((time) => {
		const xKf = xKeyframes.find((kf) => Math.abs(kf.time - time) < 0.001);
		const yKf = yKeyframes.find((kf) => Math.abs(kf.time - time) < 0.001);
		const x =
			typeof xKf?.value === "number"
				? xKf.value
				: interpolateScalarAtTime({
						keyframes: xKeyframes,
						time,
						fallback: baseX,
					});
		const y =
			typeof yKf?.value === "number"
				? yKf.value
				: interpolateScalarAtTime({
						keyframes: yKeyframes,
						time,
						fallback: baseY,
					});
		const interpolation = xKf?.interpolation ?? yKf?.interpolation ?? "linear";
		return {
			id: xKf?.id ?? yKf?.id ?? crypto.randomUUID(),
			time,
			value: { x, y },
			interpolation,
		};
	});

	const newChannels = { ...channels };
	delete newChannels["transform.position.x"];
	delete newChannels["transform.position.y"];
	newChannels["transform.position"] = {
		valueKind: "vector",
		keyframes: vectorKeyframes,
	};

	return {
		...element,
		animations: { ...animations, channels: newChannels },
	};
}

interface ScalarKeyframe {
	id: string;
	time: number;
	value: number;
	interpolation: string;
}

function getKeyframes({ channel }: { channel: unknown }): ScalarKeyframe[] {
	if (!isRecord(channel)) return [];
	if (!Array.isArray(channel.keyframes)) return [];
	return channel.keyframes.flatMap((kf) => {
		if (!isRecord(kf)) return [];
		if (
			typeof kf.id !== "string" ||
			typeof kf.time !== "number" ||
			typeof kf.value !== "number"
		)
			return [];
		return [
			{
				id: kf.id,
				time: kf.time,
				value: kf.value,
				interpolation:
					typeof kf.interpolation === "string" ? kf.interpolation : "linear",
			},
		];
	});
}

function interpolateScalarAtTime({
	keyframes,
	time,
	fallback,
}: {
	keyframes: ScalarKeyframe[];
	time: number;
	fallback: number;
}): number {
	if (keyframes.length === 0) return fallback;

	const sorted = [...keyframes].sort((a, b) => a.time - b.time);
	const first = sorted[0];
	const last = sorted[sorted.length - 1];

	if (!first || !last) return fallback;
	if (time <= first.time) return first.value;
	if (time >= last.time) return last.value;

	for (let i = 0; i < sorted.length - 1; i++) {
		const left = sorted[i];
		const right = sorted[i + 1];
		if (time < left.time || time > right.time) continue;
		if (left.interpolation === "hold") return left.value;
		const t = (time - left.time) / (right.time - left.time);
		return left.value + (right.value - left.value) * t;
	}

	return last.value;
}