summaryrefslogtreecommitdiff
path: root/apps/web/src/animation/resolve.ts
blob: 19685cead4ed88ca76e7d8911562f744bd0dc0bd (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
import type {
	AnimationPath,
	AnimationValueForPath,
	ElementAnimations,
} from "@/animation/types";
import {
	type AnimationComponentValue,
	composeAnimationValue,
	decomposeAnimationValue,
} from "./binding-values";
import {
	getChannelValueAtTime,
} from "./interpolation";

export function getElementLocalTime({
	timelineTime,
	elementStartTime,
	elementDuration,
}: {
	timelineTime: number;
	elementStartTime: number;
	elementDuration: number;
}): number {
	const localTime = timelineTime - elementStartTime;
	if (localTime <= 0) {
		return 0;
	}

	if (localTime >= elementDuration) {
		return elementDuration;
	}

	return localTime;
}

export function resolveAnimationPathValueAtTime<TPath extends AnimationPath>({
	animations,
	propertyPath,
	localTime,
	fallbackValue,
}: {
	animations: ElementAnimations | undefined;
	propertyPath: TPath;
	localTime: number;
	fallbackValue: AnimationValueForPath<TPath>;
}): AnimationValueForPath<TPath> {
	const binding = animations?.bindings[propertyPath];
	if (!binding) {
		return fallbackValue;
	}

	const fallbackComponents = decomposeAnimationValue({
		kind: binding.kind,
		value: fallbackValue,
	});
	if (!fallbackComponents) {
		return fallbackValue;
	}

	const componentValues = Object.fromEntries(
		binding.components.map((component) => {
			const channel = animations?.channels[component.channelId];
			return [
				component.key,
				getChannelValueAtTime({
					channel,
					time: localTime,
					fallbackValue:
						fallbackComponents[component.key] ??
						(channel?.kind === "discrete" ? false : 0),
				}),
			];
		}),
	) as Record<string, AnimationComponentValue | undefined>;
	return (composeAnimationValue({
		binding,
		componentValues,
	}) ?? fallbackValue) as AnimationValueForPath<TPath>;
}