aboutsummaryrefslogtreecommitdiff
path: root/src/lib/auto-refresh.ts
blob: 72bcdb9d7d8c77ba8e55cdd37f973a1a8207e49a (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

import { invalidateAll } from '$app/navigation';
import { navigating, page } from '$app/stores';
import { get } from 'svelte/store';
import { shouldAutoRefresh } from '$lib/shared/refresh-policy';

/** Away for at least this long before refocus re-runs the page load. */
const MIN_AWAY_MS = 10_000;

/** Poll cadence: near-live for a shared list, cheap for one open tab. */
const POLL_INTERVAL_MS = 15_000;

/**
 * Keeps the current page near-live: polls the server while the tab is visible,
 * and refetches on refocus after an absence. Call from `onMount`; the returned
 * function tears the listeners and timer down.
 */
export function startAutoRefresh(): () => void {
	// When the tab stopped being the active one; null while it is active.
	let deactivatedAt: number | null = null;

	const conditions = () => ({
		routeId: get(page).route.id,
		visible: document.visibilityState === 'visible',
		online: navigator.onLine,
		navigating: get(navigating) !== null,
	});

	const deactivate = () => {
		deactivatedAt ??= Date.now();
	};

	const activate = () => {
		if (deactivatedAt === null) return;
		const awayMs = Date.now() - deactivatedAt;
		deactivatedAt = null;
		if (awayMs >= MIN_AWAY_MS && shouldAutoRefresh(conditions()))
			void invalidateAll();
	};

	const onVisibilityChange = () => {
		if (document.visibilityState === 'hidden') deactivate();
		else activate();
	};

	const timer = setInterval(() => {
		if (shouldAutoRefresh(conditions())) void invalidateAll();
	}, POLL_INTERVAL_MS);

	document.addEventListener('visibilitychange', onVisibilityChange);
	window.addEventListener('blur', deactivate);
	window.addEventListener('focus', activate);

	return () => {
		clearInterval(timer);
		document.removeEventListener('visibilitychange', onVisibilityChange);
		window.removeEventListener('blur', deactivate);
		window.removeEventListener('focus', activate);
	};
}