summaryrefslogtreecommitdiff
path: root/apps/web/src/animation/graphic-param-channel.ts
blob: 32f84714f6815b54538b4c89e86bcaca4d48cbbe (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
import type {
	ElementAnimations,
	GraphicParamPath,
} from "@/animation/types";
import type { ParamDefinition, ParamValues } from "@/params";
import { resolveAnimationPathValueAtTime } from "./resolve";

export const GRAPHIC_PARAM_PATH_PREFIX = "params.";

export function buildGraphicParamPath({
	paramKey,
}: {
	paramKey: string;
}): GraphicParamPath {
	return `${GRAPHIC_PARAM_PATH_PREFIX}${paramKey}`;
}

export function isGraphicParamPath(
	propertyPath: string,
): propertyPath is GraphicParamPath {
	return propertyPath.startsWith(GRAPHIC_PARAM_PATH_PREFIX);
}

export function parseGraphicParamPath({
	propertyPath,
}: {
	propertyPath: string;
}): { paramKey: string } | null {
	if (!isGraphicParamPath(propertyPath)) {
		return null;
	}

	const paramKey = propertyPath.slice(GRAPHIC_PARAM_PATH_PREFIX.length);
	return paramKey.length > 0 ? { paramKey } : null;
}

export function resolveGraphicParamsAtTime({
	params,
	definitions,
	animations,
	localTime,
}: {
	params: ParamValues;
	definitions: ParamDefinition[];
	animations?: ElementAnimations;
	localTime: number;
}): ParamValues {
	const resolved: ParamValues = { ...params };

	for (const param of definitions) {
		const path = buildGraphicParamPath({ paramKey: param.key });
		if (!animations?.[path]) {
			continue;
		}

		resolved[param.key] = resolveAnimationPathValueAtTime({
			animations,
			propertyPath: path,
			localTime: Math.max(0, localTime),
			fallbackValue: params[param.key] ?? param.default,
		});
	}

	return resolved;
}