summaryrefslogtreecommitdiffstats
path: root/src/scripts/lib/dom.ts
blob: a88686af905cb767cc987f13d1d42255f02f4a3e (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
function isAbove(a: HTMLElement, b: HTMLElement) {
	return a.offsetTop + a.clientHeight < b.offsetTop;
}

export function getVerticalNeighbor(
	dir: -1 | 1,
	items: Iterable<HTMLElement>,
	current: HTMLElement,
) {
	let candidates: HTMLElement[] = [];

	if (dir === -1) {
		let adjacentY = Number.MIN_SAFE_INTEGER;

		for (const item of items) {
			if (!isAbove(item, current)) {
				continue;
			}

			if (item.offsetTop > adjacentY) {
				adjacentY = item.offsetTop;
				candidates = [item];
			} else if (item.offsetTop === adjacentY) {
				candidates.push(item);
			}
		}
	} else {
		let adjacentY = Number.MAX_SAFE_INTEGER;

		for (const item of items) {
			if (!isAbove(current, item)) {
				continue;
			}

			if (item.offsetTop < adjacentY) {
				adjacentY = item.offsetTop;
				candidates = [item];
			} else if (item.offsetTop === adjacentY) {
				candidates.push(item);
			}
		}
	}

	const currentX = current.offsetLeft + 0.5 * current.clientWidth;
	let match = candidates[0];
	let bestDist = Number.MAX_SAFE_INTEGER;

	for (const candidate of candidates) {
		const candidateX = candidate.offsetLeft + 0.5 * candidate.clientWidth;
		const dist = Math.abs(currentX - candidateX);

		if (dist < bestDist) {
			bestDist = dist;
			match = candidate;
		}
	}

	return match;
}