summaryrefslogtreecommitdiff
path: root/apps/web/src/timeline/pixel-utils.ts
blob: 71e8466a7c0a603571244a570ad7ffcd45e25691 (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
import { BASE_TIMELINE_PIXELS_PER_SECOND } from "@/timeline/scale";
import { TICKS_PER_SECOND } from "@/wasm";

export const TIMELINE_INDICATOR_LINE_WIDTH_PX = 2;

function getDevicePixelRatio({
	devicePixelRatio,
}: {
	devicePixelRatio?: number;
}): number {
	if (
		typeof devicePixelRatio === "number" &&
		Number.isFinite(devicePixelRatio) &&
		devicePixelRatio > 0
	) {
		return devicePixelRatio;
	}

	if (typeof window === "undefined") {
		return 1;
	}

	if (Number.isFinite(window.devicePixelRatio) && window.devicePixelRatio > 0) {
		return window.devicePixelRatio;
	}

	return 1;
}

export function getTimelinePixelsPerSecond({
	zoomLevel,
}: {
	zoomLevel: number;
}): number {
	return BASE_TIMELINE_PIXELS_PER_SECOND * zoomLevel;
}

export function timelineTimeToPixels({
	time,
	zoomLevel,
}: {
	time: number;
	zoomLevel: number;
}): number {
	return (time / TICKS_PER_SECOND) * getTimelinePixelsPerSecond({ zoomLevel });
}

export function snapPixelToDeviceGrid({
	pixel,
	devicePixelRatio,
}: {
	pixel: number;
	devicePixelRatio?: number;
}): number {
	const safeDevicePixelRatio = getDevicePixelRatio({ devicePixelRatio });
	return Math.round(pixel * safeDevicePixelRatio) / safeDevicePixelRatio;
}

export function timelineTimeToSnappedPixels({
	time,
	zoomLevel,
	devicePixelRatio,
}: {
	time: number;
	zoomLevel: number;
	devicePixelRatio?: number;
}): number {
	const rawPixel = timelineTimeToPixels({ time, zoomLevel });
	return snapPixelToDeviceGrid({ pixel: rawPixel, devicePixelRatio });
}

export function getCenteredLineLeft({
	centerPixel,
	lineWidthPx = TIMELINE_INDICATOR_LINE_WIDTH_PX,
}: {
	centerPixel: number;
	lineWidthPx?: number;
}): number {
	return centerPixel - lineWidthPx / 2;
}