-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
allow user to toggle dark mode setting and persist to localstorage
- Loading branch information
1 parent
1cb011c
commit a392bde
Showing
3 changed files
with
49 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
<script setup> | ||
import { ref, onMounted } from 'vue' | ||
const darkIcon = '🌙' | ||
const lightIcon = '☀️' | ||
let darkEnabled = ref(getDarkModePreference()) | ||
let toggleIcon = ref(darkEnabled.value ? lightIcon : darkIcon) | ||
function getDarkModePreference() { | ||
const userSet = localStorage.getItem('darkMode') | ||
// User explicit setting takes precedence | ||
if (userSet !== null) { | ||
return userSet === 'true' | ||
} else { | ||
// If user has no preference, use system preference | ||
if (window.matchMedia && | ||
window.matchMedia('(prefers-color-scheme: dark)').matches) { | ||
return true | ||
} | ||
} | ||
return false | ||
} | ||
function toggleMode() { | ||
darkEnabled.value = !darkEnabled.value | ||
localStorage.setItem('darkMode', darkEnabled.value) | ||
document.body.classList.toggle('dark') | ||
if (darkEnabled.value) { | ||
toggleIcon.value = lightIcon | ||
} else { | ||
toggleIcon.value = darkIcon | ||
} | ||
} | ||
onMounted(() => { | ||
if (darkEnabled.value) { | ||
document.body.classList.add('dark') | ||
} | ||
}) | ||
</script> | ||
|
||
<template> | ||
<h1 class="pull-right" style="margin: 0;"> | ||
<a @click="toggleMode">{{ toggleIcon }}</a> | ||
</h1> | ||
</template> |