aboutsummaryrefslogtreecommitdiff
path: root/src/lib/refresh-on-refocus.ts
blob: fcb042a5387799df6b867eb17aef125cadd38ddc (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

import { invalidateAll } from '$app/navigation';
import { page } from '$app/stores';
import { get } from 'svelte/store';

// Skip the refocus refresh on login and edit pages (in-progress edits).
const EXCLUDED_ROUTES: Record<string, true> = {
	'/login': true,
	'/grocery/[id]': true,
	'/projects/[projectId]/routine/[routineId]': true,
};

const MIN_AWAY_MS = 10_000;

/** Re-run page loads on refocus after MIN_AWAY_MS away; call from onMount. */
export function refreshOnRefocus(): () => void {
	let deactivatedAt: number | null = null;

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

	const activate = () => {
		if (deactivatedAt === null || document.visibilityState !== 'visible')
			return;
		const awayMs = Date.now() - deactivatedAt;
		deactivatedAt = null;
		if (awayMs < MIN_AWAY_MS) return;
		if ((get(page).route.id ?? '') in EXCLUDED_ROUTES) return;
		invalidateAll();
	};

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

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

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