1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-04-26 07:05:21 -04:00

separate theme restoration script and add meta[name="theme-color"] tag to _document.tsx

This commit is contained in:
Jake Jarvis 2022-01-04 18:04:33 -05:00
parent 72899ced57
commit 20d8b13bb1
Signed by: jake
GPG Key ID: 2B0C9CF251E69A39
3 changed files with 23 additions and 16 deletions

14
lib/restore-theme.js Normal file
View File

@ -0,0 +1,14 @@
import { themeColorLight, themeColorDark } from "./config";
// Inlined JS in pages/_app.tsx to restore these light/dark theme settings ASAP:
// `<html data-theme="...">`, `<meta name="color-scheme" ...>`, and color-scheme CSS property.
export const restoreThemeScript = `
try {
var pref = localStorage.getItem("dark_mode"),
dark = pref === "true" || (!pref && window.matchMedia("(prefers-color-scheme: dark)").matches),
theme = dark ? "dark" : "light";
document.documentElement.setAttribute("data-theme", theme);
document.documentElement.style.colorScheme = theme;
document.head.querySelector('meta[name="theme-color"]').setAttribute("content", dark ? "${themeColorDark}" : "${themeColorLight}");
} catch (e) {}
`.trim();

View File

@ -3,6 +3,7 @@ import { useRouter } from "next/router";
import Script from "next/script";
import { DefaultSeo, SocialProfileJsonLd } from "next-seo";
import * as Fathom from "fathom-client";
import { restoreThemeScript } from "../lib/restore-theme";
import * as config from "../lib/config";
import type { AppProps } from "next/app";
@ -48,6 +49,10 @@ const App = ({ Component, pageProps }: AppProps) => {
return (
<>
<Script id="restore_theme" strategy="afterInteractive">
{restoreThemeScript}
</Script>
{/* @ts-ignore */}
<DefaultSeo
defaultTitle={`${config.siteName} ${config.shortDescription}`}
@ -179,21 +184,6 @@ const App = ({ Component, pageProps }: AppProps) => {
]}
/>
{/*
Inline script to restore light/dark theme preference ASAP:
`<html data-theme="...">`, `<meta name="color-scheme" ...>`, and color-scheme style
*/}
<Script id="restore_theme" strategy="afterInteractive">{`try {
var pref = localStorage.getItem("dark_mode"),
dark = pref === "true" || (!pref && window.matchMedia("(prefers-color-scheme: dark)").matches),
meta = document.createElement("meta");
document.documentElement.setAttribute("data-theme", dark ? "dark" : "light");
document.documentElement.style.colorScheme = dark ? "dark" : "light";
meta.setAttribute("name", "theme-color");
meta.content = dark ? "${config.themeColorDark}" : "${config.themeColorLight}";
document.head.prepend(meta);
} catch (e) {}`}</Script>
<Component {...pageProps} />
</>
);

View File

@ -12,7 +12,10 @@ class MyDocument extends Document {
render() {
return (
<Html lang={config.siteLocale?.replace("_", "-")}>
<Head />
<Head>
{/* set dynamically by script in _app.tsx, but tag must exist first */}
<meta name="theme-color" content="" />
</Head>
<body>
<Main />
<NextScript />