summaryrefslogtreecommitdiff
path: root/static/js/reload.js
blob: 0f167f15a8b92b50aa5893ea8bcda7f44f11bed9 (plain)
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
document.addEventListener("DOMContentLoaded", function() {
	const departureList = document.getElementById('departurelist');
	const syncFailedMarker = document.getElementById('syncfailedmarker');

	const showDepartures = (departureText) => {
		departureList.innerHTML = departureText;
	};

	const updateOfflineDepartures = () => {
		const listEntries = departureList.children;
		const now = Math.floor(Date.now() / 1000);

		for (const listEntry of listEntries) {
			const departureTimestamp = listEntry.dataset.timestamp;
			if (departureTimestamp < now) {
				departureList.removeChild(listEntry);
			} else {
				countdownNodes = listEntry.querySelectorAll(".time");
				for (i = 0; i < countdownNodes.length; i++) {
					for (const countdown of countdownNodes[i].childNodes) {
						if ((countdown.nodeType == document.TEXT_NODE) && (countdown.textContent.includes("min"))) {
							if (departureTimestamp - 60 < now) {
								countdown.textContent = "sofort";
							} else {
								countdown.textContent = Math.floor((departureTimestamp - now) / 60) + " min";
							}
						}
					}
				}
			}
		}
	};

	const fetchDepartures = () => {
		var fetchUrl = window.location.href;
		if (fetchUrl.includes("?")) {
			fetchUrl += "&ajax=1";
		} else {
			fetchUrl += "?ajax=1";
		}
		fetch(fetchUrl)
			.then(response => {
				if (!response.ok) {
					throw Error(response.statusText);
				}
				return response.text()
			})
			.then(departureText => {
				syncFailedMarker.style.display = "none";
				showDepartures(departureText);
			})
			.catch(err => {
				syncFailedMarker.style.display = "inline-block";
				updateOfflineDepartures();
			});
	};

	setInterval(fetchDepartures, 60000);
});