summaryrefslogtreecommitdiff
path: root/src/components/ThemeProvider.astro
blob: 5f0723d07004cfbee3055a56fbdcf4cdeb1e3990 (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
{/* Inlined to avoid FOUC. This is a parser blocking script. */}
<script is:inline>
	const lightModePref = window.matchMedia("(prefers-color-scheme: light)");

	function getUserPref() {
		const storedTheme = typeof localStorage !== "undefined" && localStorage.getItem("theme");
		return storedTheme || (lightModePref.matches ? "light" : "dark");
	}

	function setTheme(newTheme) {
		if (newTheme !== "light" && newTheme !== "dark") {
			return console.warn(
				`Invalid theme value '${newTheme}' received. Expected 'light' or 'dark'.`,
			);
		}

		const root = document.documentElement;

		// root already set to newTheme, exit early
		if (newTheme === root.getAttribute("data-theme")) {
			return;
		}

		root.setAttribute("data-theme", newTheme);

		if (typeof localStorage !== "undefined") {
			localStorage.setItem("theme", newTheme);
		}
	}

	// initial setup
	setTheme(getUserPref());

	// View Transitions hook to restore theme
	document.addEventListener("astro:after-swap", () => setTheme(getUserPref()));

	// listen for theme-change custom event, fired in src/components/ThemeToggle.astro
	document.addEventListener("theme-change", (e) => {
		setTheme(e.detail.theme);
	});

	// listen for prefers-color-scheme change.
	lightModePref.addEventListener("change", (e) => setTheme(e.matches ? "light" : "dark"));
</script>