Skip to content
This repository was archived by the owner on Jan 17, 2024. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/lib/ThemeSelector.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
selected = !!ls.theme;
theme ? (ls.theme = theme.toLowerCase()) : ls.removeItem("theme");

updateUIWithPreference(ls);
};

const updateUIWithPreference = (ls: Storage) => {
if (
ls.theme === "dark" ||
(!("theme" in ls) && window.matchMedia("(prefers-color-scheme: dark)").matches)
Expand All @@ -18,6 +22,21 @@
else document.documentElement.classList.remove("dark");
};

const previewTheme = (theme?: string) => {
document.documentElement.classList.remove("dark");
if (!theme) {
if (window.matchMedia("(prefers-color-scheme: dark)").matches)
document.documentElement.classList.add("dark");
} else document.documentElement.classList.add(theme?.toLowerCase());
};

const unpreviewTheme = () => {
if (!ls) return;
document.documentElement.classList.remove("dark");

updateUIWithPreference(ls);
};

onMount(() => {
typeof localStorage !== `undefined` && (ls = localStorage);
if (!ls) return;
Expand Down Expand Up @@ -50,6 +69,8 @@
>
<div
on:click={() => setSelectedTheme()}
on:mouseenter={() => previewTheme()}
on:mouseleave={() => unpreviewTheme()}
class="flex cursor-pointer items-center hover:bg-slate-100 dark:hover:bg-slate-700 dark:text-white"
>
<svg
Expand All @@ -69,6 +90,8 @@
</div>
<div
on:click={() => setSelectedTheme("Light")}
on:mouseenter={() => previewTheme("Light")}
on:mouseleave={() => unpreviewTheme()}
class="flex cursor-pointer items-center hover:bg-slate-100 dark:hover:bg-slate-700 dark:text-white"
>
<svg
Expand All @@ -88,6 +111,8 @@
</div>
<div
on:click={() => setSelectedTheme("Dark")}
on:mouseenter={() => previewTheme("Dark")}
on:mouseleave={() => unpreviewTheme()}
class="flex cursor-pointer items-center hover:bg-slate-100 dark:hover:bg-slate-700 dark:text-white"
>
<svg
Expand Down