Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions app/client/components/theme-provider.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createContext, useCallback, useContext, useState } from "react";
import { createContext, useCallback, useContext, useEffect, useState } from "react";

type Theme = "light" | "dark";
export type Theme = "light" | "dark" | "system";

type ThemeContextValue = {
theme: Theme;
Expand All @@ -13,16 +13,36 @@ export const THEME_COOKIE_NAME = "theme";
const THEME_COOKIE_MAX_AGE = 60 * 60 * 24 * 365; // 1 year
const DEFAULT_THEME: Theme = "dark";

function applyTheme(theme: Theme) {
const isDark =
theme === "dark" || (theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.classList.toggle("dark", isDark);
document.documentElement.style.colorScheme = isDark ? "dark" : "light";
}

export function ThemeProvider({ children, initialTheme }: { children: React.ReactNode; initialTheme?: Theme }) {
const [theme, setThemeState] = useState<Theme>(initialTheme ?? DEFAULT_THEME);

const setTheme = useCallback((newTheme: Theme) => {
setThemeState(newTheme);
document.cookie = `${THEME_COOKIE_NAME}=${newTheme}; path=/; max-age=${THEME_COOKIE_MAX_AGE}`;
document.documentElement.classList.toggle("dark", newTheme === "dark");
document.documentElement.style.colorScheme = newTheme;
applyTheme(newTheme);
}, []);

useEffect(() => {
if (theme !== "system") {
return;
}

const media = window.matchMedia("(prefers-color-scheme: dark)");
const onChange = () => applyTheme("system");

media.addEventListener("change", onChange);
return () => {
media.removeEventListener("change", onChange);
};
}, [theme]);

return <ThemeContext value={{ theme, setTheme }}>{children}</ThemeContext>;
}

Expand Down
16 changes: 11 additions & 5 deletions app/client/components/theme-toggle.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Moon, Sun } from "lucide-react";
import { Monitor, Moon, Sun } from "lucide-react";
import { useTheme } from "./theme-provider";
import { Button } from "./ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
Expand All @@ -13,14 +13,20 @@ export function ThemeToggle() {
variant="ghost"
size="icon"
className="relative rounded-full h-7 w-7 text-muted-foreground hover:text-foreground"
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
onClick={() => setTheme(theme === "light" ? "dark" : theme === "dark" ? "system" : "light")}
aria-label="Toggle theme"
>
<Sun className="h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
{theme === "system" ? (
<Monitor className="h-4 w-4" />
) : (
<>
<Sun className="h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
</>
)}
</Button>
</TooltipTrigger>
<TooltipContent>Toggle theme</TooltipContent>
<TooltipContent>Theme: {theme}</TooltipContent>
</Tooltip>
);
}
20 changes: 18 additions & 2 deletions app/routes/__root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,26 @@ function RootLayout() {
}, []);

return (
<html lang="en" className={theme === "dark" ? "dark" : undefined} style={{ colorScheme: theme }}>
<html
lang="en"
className={theme === "dark" ? "dark" : undefined}
style={{ colorScheme: theme === "system" ? undefined : theme }}
suppressHydrationWarning
>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
/>
{theme === "system" && (
// Applies the OS color scheme before first paint to avoid a flash; the server can't know it
<script
dangerouslySetInnerHTML={{
__html: `(function(){var d=window.matchMedia("(prefers-color-scheme: dark)").matches;var e=document.documentElement;e.classList.toggle("dark",d);e.style.colorScheme=d?"dark":"light";})();`,
}}
/>
)}
<link rel="icon" type="image/png" href="/images/favicon/favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/svg+xml" href="/images/favicon/favicon.svg" />
<link rel="shortcut icon" href="/images/favicon/favicon.ico" />
Expand Down
4 changes: 2 additions & 2 deletions app/server/lib/functions/root-loader-data.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createServerFn } from "@tanstack/react-start";
import { getCookie, getRequestHeaders } from "@tanstack/react-start/server";
import { THEME_COOKIE_NAME } from "~/client/components/theme-provider";
import { THEME_COOKIE_NAME, type Theme } from "~/client/components/theme-provider";
import type { DateFormatPreference, TimeFormatPreference } from "~/client/lib/datetime";
import { getLocaleFromAcceptLanguage } from "~/server/lib/accept-language";
import { auth } from "~/server/lib/auth";
Expand All @@ -12,7 +12,7 @@ export const getRootLoaderData = createServerFn({ method: "GET" }).handler(async
const session = await auth.api.getSession({ headers });

return {
theme: (themeCookie === "light" ? "light" : "dark") as "light" | "dark",
theme: (themeCookie === "light" || themeCookie === "system" ? themeCookie : "dark") as Theme,
locale: getLocaleFromAcceptLanguage(acceptLanguage),
timeZone: process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
dateFormat: (session?.user.dateFormat ?? "MM/DD/YYYY") as DateFormatPreference,
Expand Down