-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
webapp: implement color mode switcher
- Loading branch information
1 parent
7e56c64
commit 24cf5e3
Showing
2 changed files
with
40 additions
and
1 deletion.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
'use strict' | ||
/* eslint-env browser */ | ||
|
||
/** | ||
* Get user preferred theme from their past choice or browser | ||
* @returns {String} User preferred theme | ||
*/ | ||
function getPreferredTheme () { | ||
const storedTheme = localStorage.getItem('theme') | ||
if (storedTheme) { | ||
return storedTheme | ||
} | ||
// Privacy-hardened browsers always return light | ||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' | ||
} | ||
|
||
// Change body theme early to prevent flash | ||
let currentTheme = getPreferredTheme() | ||
document.documentElement.setAttribute('data-bs-theme', currentTheme) | ||
|
||
// On browser color-scheme change, update | ||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { | ||
currentTheme = getPreferredTheme() | ||
document.documentElement.setAttribute('data-bs-theme', currentTheme) | ||
}) | ||
|
||
window.addEventListener('load', () => { | ||
// Toggle on T key, ignore input fields or key repeat | ||
document.addEventListener('keydown', e => { | ||
if (e.target.tagName !== 'INPUT' && !e.repeat && !e.ctrlKey && e.key === 't') { | ||
currentTheme = currentTheme === 'light' ? 'dark' : 'light' | ||
document.documentElement.setAttribute('data-bs-theme', currentTheme) | ||
localStorage.setItem('theme', currentTheme) | ||
e.preventDefault() | ||
} | ||
}) | ||
}) |
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