From d7c9ce9bc5e3c4a40d14de80184443ba52cd5bf1 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Mon, 17 Feb 2025 10:43:59 +0100 Subject: [PATCH] docs: fix dark mode background flash (#2825) Fixes https://github.com/denoland/fresh/issues/2823#issuecomment-2661711235 --- www/islands/ThemeToggle.tsx | 28 ++++++++++------------------ www/routes/_app.tsx | 16 +++++++++++++--- www/static/styles.css | 12 ++++++++++-- 3 files changed, 33 insertions(+), 23 deletions(-) diff --git a/www/islands/ThemeToggle.tsx b/www/islands/ThemeToggle.tsx index fb5c10f7..52efb4ac 100644 --- a/www/islands/ThemeToggle.tsx +++ b/www/islands/ThemeToggle.tsx @@ -1,27 +1,19 @@ -import { useEffect, useState } from "preact/hooks"; +import { useState } from "preact/hooks"; import { IS_BROWSER } from "fresh/runtime"; export default function ThemeToggle() { - const getPreferredTheme = () => { + const [theme, setTheme] = useState(() => { if (!IS_BROWSER) return "light"; - const storedTheme = localStorage.getItem("theme"); - if (storedTheme) return storedTheme; - return window.matchMedia("(prefers-color-scheme: dark)").matches - ? "dark" - : "light"; - }; - - const [theme, setTheme] = useState(getPreferredTheme); - - useEffect(() => { - document.documentElement.classList.remove("light", "dark"); - document.documentElement.classList.add(theme); - document.documentElement.setAttribute("data-theme", theme); - localStorage.setItem("theme", theme); - }, [theme]); + return document.documentElement.dataset.theme ?? "light"; + }); const toggleTheme = () => { - setTheme((prev) => (prev === "light" ? "dark" : "light")); + setTheme((prev) => { + const theme = prev === "light" ? "dark" : "light"; + document.documentElement.setAttribute("data-theme", theme); + localStorage.setItem("theme", theme); + return theme; + }); }; return ( diff --git a/www/routes/_app.tsx b/www/routes/_app.tsx index c3a428c6..45963159 100644 --- a/www/routes/_app.tsx +++ b/www/routes/_app.tsx @@ -3,7 +3,7 @@ import { define } from "../utils/state.ts"; export default define.page(function App({ Component, state, url }) { return ( - + @@ -23,6 +23,7 @@ export default define.page(function App({ Component, state, url }) { ? : null} {state.noIndex ? : null} + ) : null} - - + diff --git a/www/static/styles.css b/www/static/styles.css index c4680789..b1406f82 100644 --- a/www/static/styles.css +++ b/www/static/styles.css @@ -3,7 +3,7 @@ @tailwind utilities; /* Light and dark theme variables */ -.light { +:root { --fresh: 50deg, 100%, 56%; --fresh-green: 142deg, 71%, 29%; @@ -17,7 +17,7 @@ --info: 194deg, 76%, 41%; } -.dark { +html[data-theme="dark"]:root { --fresh: 50deg, 100%, 56%; --fresh-green: 142deg, 71%, 29%; @@ -104,3 +104,11 @@ hr { .dark-mode-toggle-button img { @apply fill-foreground-primary; } + +::selection { + background-color: #b1d5ff; +} + +html[data-theme="dark"] ::selection { + background-color: #064c9c; +}