| 1 |
/* |
| 2 |
* Copyright (C) 2022 Red Hat, Inc. |
| 3 |
* SPDX-License-Identifier: LGPL-2.1-or-later |
| 4 |
*/ |
| 5 |
|
| 6 |
function debug(...args: unknown[]) { |
| 7 |
if (window.debugging == "all" || window.debugging?.includes("style")) { |
| 8 |
console.debug([`cockpit-dark-theme: ${document.documentElement.id}:`, ...args].join(" ")); |
| 9 |
} |
| 10 |
} |
| 11 |
|
| 12 |
function changeDarkThemeClass(documentElement: Element, dark_mode: boolean) { |
| 13 |
debug(`Setting cockpit theme to ${dark_mode ? "dark" : "light"}`); |
| 14 |
|
| 15 |
if (dark_mode) { |
| 16 |
documentElement.classList.add('pf-v6-theme-dark'); |
| 17 |
} else { |
| 18 |
documentElement.classList.remove('pf-v6-theme-dark'); |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
function _setDarkMode(_style?: string) { |
| 23 |
const style = _style || localStorage.getItem('shell:style') || 'auto'; |
| 24 |
let dark_mode; |
| 25 |
// If a user set's an explicit theme, ignore system changes. |
| 26 |
if ((window.matchMedia?.('(prefers-color-scheme: dark)').matches && style === "auto") || style === "dark") { |
| 27 |
dark_mode = true; |
| 28 |
} else { |
| 29 |
dark_mode = false; |
| 30 |
} |
| 31 |
changeDarkThemeClass(document.documentElement, dark_mode); |
| 32 |
} |
| 33 |
|
| 34 |
window.addEventListener("storage", event => { |
| 35 |
if (event.key === "shell:style") { |
| 36 |
debug(`Storage element 'shell:style' changed from ${event.oldValue} to ${event.newValue}`); |
| 37 |
|
| 38 |
_setDarkMode(); |
| 39 |
} |
| 40 |
}); |
| 41 |
|
| 42 |
// When changing the theme from the shell switcher the localstorage change will not fire for the same page (aka shell) |
| 43 |
// so we need to listen for the event on the window object. |
| 44 |
window.addEventListener("cockpit-style", event => { |
| 45 |
if (event instanceof CustomEvent) { |
| 46 |
const style = event.detail.style; |
| 47 |
debug(`Event received from shell with 'cockpit-style' ${style}`); |
| 48 |
|
| 49 |
_setDarkMode(style); |
| 50 |
} |
| 51 |
}); |
| 52 |
|
| 53 |
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { |
| 54 |
debug(`Operating system theme preference changed to ${window.matchMedia?.('(prefers-color-scheme: dark)').matches ? "dark" : "light"}`); |
| 55 |
_setDarkMode(); |
| 56 |
}); |
| 57 |
|
| 58 |
_setDarkMode(); |