From bb6ed2434ed90d1aea904ca51c62e4076d4e2c12 Mon Sep 17 00:00:00 2001 From: Jamie Tanna Date: Sat, 22 Jun 2024 19:16:29 +0100 Subject: [PATCH] feat: detect user's dark mode preferences automagically (#18) As noted in #15, it would be handy to respect the user's preferred light/dark mode settings, if we can detect it. This only gets referenced if there isn't an explicitly set mode in their `localStorage`. This also extracts this logic to a function, so we can more easily write a multi-line conditional, but retains the ternary logic to follow the project's style preferences. Closes #15. --- ui/src/provider/theme.provider.tsx | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/ui/src/provider/theme.provider.tsx b/ui/src/provider/theme.provider.tsx index 9117f27..a5f7960 100644 --- a/ui/src/provider/theme.provider.tsx +++ b/ui/src/provider/theme.provider.tsx @@ -2,6 +2,14 @@ import createStore from "@/lib/makeStore"; export type Theme = "dark" | "light"; +function initialState(): Theme { + if (localStorage.getItem("theme") !== null) { + return localStorage.getItem("theme") === "dark" ? "dark" : "light" + } + + return window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" : "light" +} + export const { StoreProvider: ThemeProvider, useDispatch: setTheme, @@ -11,5 +19,5 @@ export const { localStorage.setItem("theme", next); return next; }, - (localStorage.getItem("theme") === "dark" ? "dark" : "light") as Theme, + initialState(), );