Skip to content

Commit

Permalink
webapp: implement color mode switcher
Browse files Browse the repository at this point in the history
  • Loading branch information
aiooss-anssi committed Feb 8, 2024
1 parent 7e56c64 commit 24cf5e3
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
37 changes: 37 additions & 0 deletions webapp/static/assets/js/color-mode-switcher.js
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()
}
})
})
4 changes: 3 additions & 1 deletion webapp/templates/index.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<!doctype html>
<html lang="en" data-bs-theme="dark" class="h-100">
<html lang="en" data-bs-theme="light" class="h-100">

<head>
<meta charset="utf-8">
Expand All @@ -11,6 +11,7 @@
<link rel="icon" href="static/favicon.svg">
<link href="static/assets/css/bootstrap.min.css" rel="stylesheet">
<link href="static/assets/css/style.css" rel="stylesheet">
<script src="static/assets/js/color-mode-switcher.js"></script>
<script src="static/assets/js/bootstrap.bundle.min.js" defer></script>
<script type="module" src="static/assets/js/flowdisplay.js" defer></script>
<script type="module" src="static/assets/js/flowlist.js" defer></script>
Expand Down Expand Up @@ -102,6 +103,7 @@
<ul class="list-unstyled">
<li class="mb-1">Use <kbd>Left</kbd>, <kbd>Right</kbd> keys to quickly navigate flows.</li>
<li class="mb-1">Use <kbd>V</kbd> key to quickly switch raw data view.</li>
<li class="mb-1">Use <kbd>T</kbd> key to switch color theme.</li>
</ul>
</div>

Expand Down

0 comments on commit 24cf5e3

Please sign in to comment.