diff --git a/frontend/main.ts b/frontend/main.ts index ab42d06..fb951e0 100644 --- a/frontend/main.ts +++ b/frontend/main.ts @@ -8,6 +8,8 @@ export interface choiceMap { let choiceObjects: choiceMap = {}; document.addEventListener('DOMContentLoaded', function() { + changeTheme(); + initcolorTheme(); initSearch(); initSidebar(); initToggle(); @@ -20,6 +22,75 @@ document.addEventListener('DOMContentLoaded', function() { setCurrentdate(document.querySelector('#departure')); }); +function changeTheme() { + let toggleBtn = document.querySelector('#theme-toggle-js'); + + if(toggleBtn) { + toggleBtn.addEventListener('click', function() { + if(toggleBtn.dataset.theme === 'light') { + setTheme('dark', true); + } else { + setTheme('light', true); + } + }); + } +} + +/*** +* init javascript +* 1) detect native color scheme or use set theme in local storage +* 2) detect view (desktop or responsive) if on mobile device with touch screen +* 3) set base font size to 112.5% -> 18px +*/ +function initcolorTheme() { + colorThemeWatcher(); + let theme = localStorage.getItem('theme'); + if (theme == null || theme === 'auto') { + if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { + setTheme('dark', false); + } else { + setTheme('light', false); + } + } else { + setTheme(theme) + } +} + +/*** +* Listener operating system native color configuration +*/ +function colorThemeWatcher() { + try { + window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => { + setTheme(e.matches ? 'dark' : 'light'); + }); + } catch { + console.warn('color theme watcher not supported'); + } +} + +/** +* Define color scheme, colors without losing the base font size configuration +* and add data-theme to html tag +* @param theme +*/ +function setTheme(theme: string, setLocalStorage = true) { + let toggleBtn = document.querySelector('#theme-toggle-js'); + + if(toggleBtn) { + if (setLocalStorage) { + localStorage.setItem('theme', theme); + } + toggleBtn.setAttribute('data-theme', theme); + + if (document.documentElement.classList.contains('dark') && theme === 'light') { + document.documentElement.classList.remove('dark'); + } else if(theme === 'dark'){ + document.documentElement.classList.add('dark'); + } + } +} + function setCurrentdate(input: HTMLInputElement) { if(input) { const now = new Date(); diff --git a/frontend/tailwind.config.cjs b/frontend/tailwind.config.cjs index 3d2eddf..c17b852 100644 --- a/frontend/tailwind.config.cjs +++ b/frontend/tailwind.config.cjs @@ -41,5 +41,6 @@ export default { }, plugins: [], important: true, + darkMode: 'class', } diff --git a/templates/includes/footer.html.tera b/templates/includes/footer.html.tera index a1a8522..abdc14c 100644 --- a/templates/includes/footer.html.tera +++ b/templates/includes/footer.html.tera @@ -1,12 +1,23 @@