Add support to configure dark mode.

This commit is contained in:
prototypa
2023-01-06 13:10:40 -05:00
parent ac24c9e94e
commit e478745e26
2 changed files with 20 additions and 8 deletions

View File

@ -1,19 +1,27 @@
--- ---
import { SITE } from "~/config.mjs"
--- ---
<script is:inline> <script is:inline define:vars={{ defaultTheme: SITE.defaultTheme }}>
// Set "light" theme as default
// if (!localStorage.theme) {
// localStorage.theme = "light";
// }
if ( function applyTheme(theme) {
if (theme === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}
if ((defaultTheme && defaultTheme.endsWith(":only")) || (!localStorage.theme && defaultTheme !== "system")) {
applyTheme(defaultTheme.replace(":only", ""));
}
else if (
localStorage.theme === 'dark' || localStorage.theme === 'dark' ||
(!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches) (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)
) { ) {
document.documentElement.classList.add('dark'); applyTheme("dark")
} else { } else {
document.documentElement.classList.remove('dark'); applyTheme("light")
} }
function attachEvent(selector, event, fn) { function attachEvent(selector, event, fn) {
@ -34,6 +42,9 @@
}); });
attachEvent('[data-aw-toggle-color-scheme]', 'click', function () { attachEvent('[data-aw-toggle-color-scheme]', 'click', function () {
if (defaultTheme.endsWith(":only")) {
return;
}
document.documentElement.classList.toggle('dark'); document.documentElement.classList.toggle('dark');
localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light'; localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
}); });

View File

@ -11,6 +11,7 @@ export const SITE = {
description: '🚀 AstroWind is a free and ready to start template to make your website using Astro and Tailwind CSS.', description: '🚀 AstroWind is a free and ready to start template to make your website using Astro and Tailwind CSS.',
defaultImage: defaultImage, defaultImage: defaultImage,
defaultTheme: "system", // "system" | "light" | "dark" | "light:only" | "dark:only"
googleAnalyticsId: false, // or "G-XXXXXXXXXX", googleAnalyticsId: false, // or "G-XXXXXXXXXX",
googleSiteVerificationId: 'orcPxI47GSa-cRvY11tUe6iGg2IO_RPvnA1q95iEM3M', googleSiteVerificationId: 'orcPxI47GSa-cRvY11tUe6iGg2IO_RPvnA1q95iEM3M',