Skip to content

Commit 64c4b4f

Browse files
committed
Add time-aware theme fallback
1 parent 9da5a0e commit 64c4b4f

2 files changed

Lines changed: 28 additions & 4 deletions

File tree

‎index.html‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,36 @@
2323
<script>
2424
(function () {
2525
try {
26-
var savedTheme = localStorage.getItem("compbio-theme");
27-
var prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
26+
var savedTheme;
27+
try {
28+
savedTheme = localStorage.getItem("compbio-theme");
29+
} catch (storageError) {
30+
savedTheme = null;
31+
}
32+
33+
var supportsColorPreference = typeof window.matchMedia === "function";
34+
var prefersDark = supportsColorPreference
35+
&& window.matchMedia("(prefers-color-scheme: dark)").matches;
36+
var prefersLight = supportsColorPreference
37+
&& window.matchMedia("(prefers-color-scheme: light)").matches;
38+
var hasColorPreference = prefersDark || prefersLight;
39+
var localHour = new Date().getHours();
40+
var timeTheme = localHour >= 7 && localHour < 19 ? "light" : "dark";
41+
var automaticTheme = hasColorPreference
42+
? (prefersDark ? "dark" : "light")
43+
: timeTheme;
2844
var theme = savedTheme === "light" || savedTheme === "dark"
2945
? savedTheme
30-
: (prefersDark ? "dark" : "light");
46+
: automaticTheme;
47+
48+
document.documentElement.dataset.defaultTheme = hasColorPreference
49+
? "system"
50+
: timeTheme;
3151
document.documentElement.classList.toggle("dark", theme === "dark");
3252
document.documentElement.style.colorScheme = theme;
53+
document
54+
.querySelector('meta[name="theme-color"]')
55+
?.setAttribute("content", theme === "dark" ? "#0A1220" : "#FFFFFF");
3356
var favicon = document.querySelector("link[data-theme-favicon]");
3457
if (favicon) {
3558
favicon.href = theme === "dark"

‎src/App.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ const BioNetwork = lazy(
3131

3232
const queryClient = new QueryClient();
3333
const routerBasename = import.meta.env.BASE_URL.replace(/\/$/, "") || "/";
34+
const defaultTheme = document.documentElement.dataset.defaultTheme ?? "system";
3435

3536
const ScrollToTop = () => {
3637
const { pathname } = useLocation();
@@ -120,7 +121,7 @@ const AppRoutes = () => {
120121
const App = () => (
121122
<ThemeProvider
122123
attribute="class"
123-
defaultTheme="system"
124+
defaultTheme={defaultTheme}
124125
enableSystem
125126
disableTransitionOnChange
126127
storageKey="compbio-theme"

0 commit comments

Comments
 (0)